Programs & Examples On #Gtktreeview

GtkTreeView is a widget for displaying both trees and lists. It is part of the GTK library.

Cast Double to Integer in Java

Indeed, the simplest way is to use intValue(). However, this merely returns the integer part; it does not do any rounding. If you want the Integer nearest to the Double value, you'll need to do this:

Integer integer = Integer.valueOf((int) Math.round(myDouble)));

And don't forget the null case:

Integer integer = myDouble == null ? null : Integer.valueOf((int) Math.round(myDouble)));

Math.round() handles odd duck cases, like infinity and NaN, with relative grace.

Spring @PropertySource using YAML

@PropertySource can be configured by factory argument. So you can do something like:

@PropertySource(value = "classpath:application-test.yml", factory = YamlPropertyLoaderFactory.class)

Where YamlPropertyLoaderFactory is your custom property loader:

public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
    @Override
    public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
        if (resource == null){
            return super.createPropertySource(name, resource);
        }

        return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
    }
}

Inspired by https://stackoverflow.com/a/45882447/4527110

How to upgrade pip3?

You are using pip3 to install flask-script which is associated with python 3.5. However, you are trying to upgrade pip associated with the python 2.7, try running pip3 install --upgrade pip.

It might be a good idea to take some time and read about virtual environments in Python. It isn't a best practice to install all of your packages to the base python installation. This would be a good start: http://docs.python-guide.org/en/latest/dev/virtualenvs/

Switching between GCC and Clang/LLVM using CMake

System wide C++ change on Ubuntu:

sudo apt-get install clang
sudo update-alternatives --config c++

Will print something like this:

  Selection    Path              Priority   Status
------------------------------------------------------------
* 0            /usr/bin/g++       20        auto mode
  1            /usr/bin/clang++   10        manual mode
  2            /usr/bin/g++       20        manual mode

Then just select clang++.

Abort a git cherry-pick?

I found the answer is git reset --merge - it clears the conflicted cherry-pick attempt.

How do I compare two columns for equality in SQL Server?

What's wrong with CASE for this? In order to see the result, you'll need at least a byte, and that's what you get with a single character.

CASE WHEN COLUMN1 = COLUMN2 THEN '1' ELSE '0' END AS MyDesiredResult

should work fine, and for all intents and purposes accomplishes the same thing as using a bit field.

Codesign error: Provisioning profile cannot be found after deleting expired profile

I agree with Brad's answer, that you can fix this problem by editing your target/project by hand, deleting any lines like this:

PROVISIONING_PROFILE = "487F3EAC-05FB-4A2A-9EA0-31F1F35760EB";
"PROVISIONING_PROFILE[sdk=iphoneos*]" = "487F3EAC-05FB-4A2A-9EA0-31F1F35760EB";

However, in Xcode 4.2 and later, there is a much easier way to access this text and select and delete it. In the Project Navigator on the left, select your project (the topmost line of the Project Navigator). Now simply choose View > Version Editor > Show Version Editor. This displays your project as text, and you can search for PROVISIONING and delete the troublesome line, right there in the editor pane of Xcode.

Locking a file in Python

Locking is platform and device specific, but generally, you have a few options:

  1. Use flock(), or equivalent (if your os supports it). This is advisory locking, unless you check for the lock, its ignored.
  2. Use a lock-copy-move-unlock methodology, where you copy the file, write the new data, then move it (move, not copy - move is an atomic operation in Linux -- check your OS), and you check for the existence of the lock file.
  3. Use a directory as a "lock". This is necessary if you're writing to NFS, since NFS doesn't support flock().
  4. There's also the possibility of using shared memory between the processes, but I've never tried that; it's very OS-specific.

For all these methods, you'll have to use a spin-lock (retry-after-failure) technique for acquiring and testing the lock. This does leave a small window for mis-synchronization, but its generally small enough to not be an major issue.

If you're looking for a solution that is cross platform, then you're better off logging to another system via some other mechanism (the next best thing is the NFS technique above).

Note that sqlite is subject to the same constraints over NFS that normal files are, so you can't write to an sqlite database on a network share and get synchronization for free.

HTML CSS How to stop a table cell from expanding

It's entirely possible if your code has enough relative logic to work with.

Simply use the viewport units though for some the math may be a bit more complicated. I used this to prevent list items from bloating certain table columns with much longer text.

ol {max-width: 10vw; padding: 0; overflow: hidden;}

Apparently max-width on colgroup elements do not work which is pretty lame to be dependent entirely on child elements to control something on the parent.

File Upload without Form

You can use FormData to submit your data by a POST request. Here is a simple example:

var myFormData = new FormData();
myFormData.append('pictureFile', pictureInput.files[0]);

$.ajax({
  url: 'upload.php',
  type: 'POST',
  processData: false, // important
  contentType: false, // important
  dataType : 'json',
  data: myFormData
});

You don't have to use a form to make an ajax request, as long as you know your request setting (like url, method and parameters data).

Count unique values using pandas groupby

I think you can use SeriesGroupBy.nunique:

print (df.groupby('param')['group'].nunique())
param
a    2
b    1
Name: group, dtype: int64

Another solution with unique, then create new df by DataFrame.from_records, reshape to Series by stack and last value_counts:

a = df[df.param.notnull()].groupby('group')['param'].unique()
print (pd.DataFrame.from_records(a.values.tolist()).stack().value_counts())
a    2
b    1
dtype: int64

C++ correct way to return pointer to array from function

Your code (which looks ok) doesn't return a pointer to an array. It returns a pointer to the first element of an array.

In fact that's usually what you want to do. Most manipulation of arrays are done via pointers to individual elements, not via pointers to the array as a whole.

You can define a pointer to an array, for example this:

double (*p)[42];

defines p as a pointer to a 42-element array of doubles. A big problem with that is that you have to specify the number of elements in the array as part of the type -- and that number has to be a compile-time constant. Most programs that deal with arrays need to deal with arrays of varying sizes; a given array's size won't vary after it's been created, but its initial size isn't necessarily known at compile time, and different array objects can have different sizes.

A pointer to the first element of an array lets you use either pointer arithmetic or the indexing operator [] to traverse the elements of the array. But the pointer doesn't tell you how many elements the array has; you generally have to keep track of that yourself.

If a function needs to create an array and return a pointer to its first element, you have to manage the storage for that array yourself, in one of several ways. You can have the caller pass in a pointer to (the first element of) an array object, probably along with another argument specifying its size -- which means the caller has to know how big the array needs to be. Or the function can return a pointer to (the first element of) a static array defined inside the function -- which means the size of the array is fixed, and the same array will be clobbered by a second call to the function. Or the function can allocate the array on the heap -- which makes the caller responsible for deallocating it later.

Everything I've written so far is common to C and C++, and in fact it's much more in the style of C than C++. Section 6 of the comp.lang.c FAQ discusses the behavior of arrays and pointers in C.

But if you're writing in C++, you're probably better off using C++ idioms. For example, the C++ standard library provides a number of headers defining container classes such as <vector> and <array>, which will take care of most of this stuff for you. Unless you have a particular reason to use raw arrays and pointers, you're probably better off just using C++ containers instead.

EDIT : I think you edited your question as I was typing this answer. The new code at the end of your question is, as you observer, no good; it returns a pointer to an object that ceases to exist as soon as the function returns. I think I've covered the alternatives.

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

TLDR; Neither use the synchronized modifier nor the synchronized(this){...} expression but synchronized(myLock){...} where myLock is a final instance field holding a private object.


The difference between using the synchronized modifier on the method declaration and the synchronized(..){ } expression in the method body are this:

  • The synchronized modifier specified on the method's signature
    1. is visible in the generated JavaDoc,
    2. is programmatically determinable via reflection when testing a method's modifier for Modifier.SYNCHRONIZED,
    3. requires less typing and indention compared to synchronized(this) { .... }, and
    4. (depending on your IDE) is visible in the class outline and code completion,
    5. uses the this object as lock when declared on non-static method or the enclosing class when declared on a static method.
  • The synchronized(...){...} expression allows you
    1. to only synchronize the execution of parts of a method's body,
    2. to be used within a constructor or a (static) initialization block,
    3. to choose the lock object which controls the synchronized access.

However, using the synchronized modifier or synchronized(...) {...} with this as the lock object (as in synchronized(this) {...}), have the same disadvantage. Both use it's own instance as the lock object to synchronize on. This is dangerous because not only the object itself but any other external object/code that holds a reference to that object can also use it as a synchronization lock with potentially severe side effects (performance degradation and deadlocks).

Therefore best practice is to neither use the synchronized modifier nor the synchronized(...) expression in conjunction with this as lock object but a lock object private to this object. For example:

public class MyService {
    private final lock = new Object();

    public void doThis() {
       synchronized(lock) {
          // do code that requires synchronous execution
        }
    }

    public void doThat() {
       synchronized(lock) {
          // do code that requires synchronous execution
        }
    }
}

You can also use multiple lock objects but special care needs to be taken to ensure this does not result in deadlocks when used nested.

public class MyService {
    private final lock1 = new Object();
    private final lock2 = new Object();

    public void doThis() {
       synchronized(lock1) {
          synchronized(lock2) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThat() and doMore().
          }
    }

    public void doThat() {
       synchronized(lock1) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThis().
              // doMore() may execute concurrently
        }
    }

    public void doMore() {
       synchronized(lock2) {
              // code here is guaranteed not to be executes at the same time
              // as the synchronized code in doThis().
              // doThat() may execute concurrently
        }
    }
}

How to add message box with 'OK' button?

Since in your situation you only want to notify the user with a short and simple message, a Toast would make for a better user experience.

Toast.makeText(getApplicationContext(), "Data saved", Toast.LENGTH_LONG).show();

Update: A Snackbar is recommended now instead of a Toast for Material Design apps.

If you have a more lengthy message that you want to give the reader time to read and understand, then you should use a DialogFragment. (The documentation currently recommends wrapping your AlertDialog in a fragment rather than calling it directly.)

Make a class that extends DialogFragment:

public class MyDialogFragment extends DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {

        // Use the Builder class for convenient dialog construction
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("App Title");
        builder.setMessage("This is an alert with no consequence");
        builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // You don't have to do anything here if you just 
                // want it dismissed when clicked
            }
        });

        // Create the AlertDialog object and return it
        return builder.create();
    }
}

Then call it when you need it in your activity:

DialogFragment dialog = new MyDialogFragment();
dialog.show(getSupportFragmentManager(), "MyDialogFragmentTag");

See also

enter image description here

Foreign Key to non-primary key

Necromancing.
I assume when somebody lands here, he needs a foreign key to column in a table that contains non-unique keys.

The problem is, that if you have that problem, the database-schema is denormalized.

You're for example keeping rooms in a table, with a room-uid primary key, a DateFrom and a DateTo field, and another uid, here RM_ApertureID to keep track of the same room, and a soft-delete field, like RM_Status, where 99 means 'deleted', and <> 99 means 'active'.

So when you create the first room, you insert RM_UID and RM_ApertureID as the same value as RM_UID. Then, when you terminate the room to a date, and re-establish it with a new date range, RM_UID is newid(), and the RM_ApertureID from the previous entry becomes the new RM_ApertureID.

So, if that's the case, RM_ApertureID is a non-unique field, and so you can't set a foreign-key in another table.

And there is no way to set a foreign key to a non-unique column/index, e.g. in T_ZO_REM_AP_Raum_Reinigung (WHERE RM_UID is actually RM_ApertureID).
But to prohibit invalid values, you need to set a foreign key, otherwise, data-garbage is the result sooner rather than later...

Now what you can do in this case (short of rewritting the entire application) is inserting a CHECK-constraint, with a scalar function checking the presence of the key:

IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


IF  EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[fu_Constaint_ValidRmApertureId]') AND type in (N'FN', N'IF', N'TF', N'FS', N'FT'))
DROP FUNCTION [dbo].[fu_Constaint_ValidRmApertureId]
GO




CREATE FUNCTION [dbo].[fu_Constaint_ValidRmApertureId](
     @in_RM_ApertureID uniqueidentifier 
    ,@in_DatumVon AS datetime 
    ,@in_DatumBis AS datetime 
    ,@in_Status AS integer 
) 
    RETURNS bit 
AS 
BEGIN   
    DECLARE @bNoCheckForThisCustomer AS bit 
    DECLARE @bIsInvalidValue AS bit 
    SET @bNoCheckForThisCustomer = 'false' 
    SET @bIsInvalidValue = 'false' 

    IF @in_Status = 99 
        RETURN 'false' 


    IF @in_DatumVon > @in_DatumBis 
    BEGIN 
        RETURN 'true' 
    END 


    IF @bNoCheckForThisCustomer = 'true'
        RETURN @bIsInvalidValue 


    IF NOT EXISTS
    ( 
        SELECT 
             T_Raum.RM_UID 
            ,T_Raum.RM_Status 
            ,T_Raum.RM_DatumVon 
            ,T_Raum.RM_DatumBis 
            ,T_Raum.RM_ApertureID 
        FROM T_Raum 
        WHERE (1=1) 
        AND T_Raum.RM_ApertureID = @in_RM_ApertureID 
        AND @in_DatumVon >= T_Raum.RM_DatumVon 
        AND @in_DatumBis <= T_Raum.RM_DatumBis 
        AND T_Raum.RM_Status <> 99  
    ) 
        SET @bIsInvalidValue = 'true' -- IF ! 

    RETURN @bIsInvalidValue 
END 



GO



IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]'))
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung DROP CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]
GO


-- ALTER TABLE dbo.T_AP_Kontakte WITH CHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]  
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung WITH NOCHECK ADD CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
CHECK 
( 
    NOT 
    ( 
        dbo.fu_Constaint_ValidRmApertureId(ZO_RMREM_RM_UID, ZO_RMREM_GueltigVon, ZO_RMREM_GueltigBis, ZO_RMREM_Status) = 1 
    ) 
) 
GO


IF  EXISTS (SELECT * FROM sys.check_constraints WHERE object_id = OBJECT_ID(N'[dbo].[Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung]') AND parent_object_id = OBJECT_ID(N'[dbo].[T_ZO_REM_AP_Raum_Reinigung]')) 
ALTER TABLE dbo.T_ZO_REM_AP_Raum_Reinigung CHECK CONSTRAINT [Check_RM_ApertureIDisValid_T_ZO_REM_AP_Raum_Reinigung] 
GO

Save range to variable

... And the answer is:

Set SrcRange = Sheets("Src").Range("A2:A9")
SrcRange.Copy Destination:=Sheets("Dest").Range("A2")

The Set makes all the difference. Then it works like a charm.

Access denied for user 'root'@'localhost' (using password: YES) (Mysql::Error)

I faced the same error after upgrading MySQL server from 5.1.73 to 5.5.45 There is another way to fix that error.

In my case I was able to connect to MySQL using root password but MySQL actively refused to GRANT PRIVILEGES to any user;

  1. Connect to MySQL as root

    mysql -u root -p
    

    then enter your MySQL root password;

  2. Select database;

    use mysql;
    
  3. Most probably there is only one record for root in mysql.user table allowing to connect only from localhost (that was in my case) but by the default there should be two records for root, one for localhost and another one for 127.0.0.1;

  4. Create additional record for root user with Host='127.0.0.1' if it's not there;

        SET @s = CONCAT('INSERT INTO mysql.user SELECT ',
                REPLACE((SELECT GROUP_CONCAT(COLUMN_NAME) 
                         FROM INFORMATION_SCHEMA.COLUMNS
                         WHERE TABLE_NAME = 'user' AND TABLE_SCHEMA = 'mysql')
                ,"Host","'127.0.0.1'"),
                ' FROM mysql.user WHERE User="root"'); 
    
         PREPARE stmt FROM @s; 
         EXECUTE stmt;
    
  5. Additionally to that you can execute mysql_upgrade -u -p to see if everything is ok.

How to avoid Number Format Exception in java?

That depends on your environment. JSF for example would take the burden of manually checking and converting Strings <-> Numbers from you, Bean Validation is another option.

What you can do immediately in the snippet you provide:

  1. Extract method getAsInt(String param), in it:
  2. Use String.isEmpty() (Since Java 6),
  3. surround with try / catch

What you should definitely think about if you happen to write a lot of code like this:

public void myBusinessMethod(@ValidNumber String numberInput) {
// ...    
}

(This would be interceptor-based).

Last but not least: Save the work and try to switch to a framework which gives you support for these common tasks...

React - Preventing Form Submission

There's another, more accessible solution: Don't put the action on your buttons. There's a lot of functionality built into forms already. Instead of handling button presses, handle form submissions and resets. Simply add onSubmit={handleSubmit} and onReset={handleReset} to your form elements.

To stop the actual submission just include event in your function and an event.preventDefault(); to stop the default submission behavior. Now your form behaves correctly from an accessibility standpoint and you're handling any form of submission the user might take.

Row Offset in SQL Server

You can use ROW_NUMBER() function to get what you want:

SELECT *
FROM (SELECT ROW_NUMBER() OVER(ORDER BY id) RowNr, id FROM tbl) t
WHERE RowNr BETWEEN 10 AND 20

Border length smaller than div width?

I just accomplished the opposite of this using :after and ::after because I needed to make my bottom border exactly 1.3rem wider:

My element got super deformed when I used :before and :after at the same time because the elements are horizontally aligned with display: flex, flex-direction: row and align-items: center.

You could use this for making something wider or narrower, or probably any mathematical dimension mods:

a.nav_link-active {
  color: $e1-red;
  margin-top: 3.7rem;
}
a.nav_link-active:visited {
  color: $e1-red;
}
a.nav_link-active:after {
  content: '';
  margin-top: 3.3rem;      // margin and height should
  height: 0.4rem;          // add up to active link margin
  background: $e1-red;
  margin-left: -$nav-spacer-margin;
  display: block;
}
a.nav_link-active::after {
  content: '';
  margin-top: 3.3rem;      // margin and height should
  height: 0.4rem;          // add up to active link margin
  background: $e1-red;
  margin-right: -$nav-spacer-margin;
  display: block;
}

Sorry, this is SCSS, just multiply the numbers by 10 and change the variables with some normal values.

How to connect to MySQL Database?

Install Oracle's MySql.Data NuGet package.

using MySql.Data;
using MySql.Data.MySqlClient;

namespace Data
{
    public class DBConnection
    {
        private DBConnection()
        {
        }

        public string Server { get; set; }
        public string DatabaseName { get; set; }
        public string UserName { get; set; }
        public string Password { get; set; }

        private MySqlConnection Connection { get; set;}

        private static DBConnection _instance = null;
        public static DBConnection Instance()
        {
            if (_instance == null)
                _instance = new DBConnection();
           return _instance;
        }
    
        public bool IsConnect()
        {
            if (Connection == null)
            {
                if (String.IsNullOrEmpty(databaseName))
                    return false;
                string connstring = string.Format("Server={0}; database={1}; UID={2}; password={3}", Server, DatabaseName, UserName, Password);
                Connection = new MySqlConnection(connstring);
                Connection.Open();
            }
    
            return true;
        }
    
        public void Close()
        {
            Connection.Close();
        }        
    }
}

Example:

var dbCon = DBConnection.Instance();
dbCon.Server = "YourServer";
dbCon.DatabaseName = "YourDatabase";
dbCon.UserName = "YourUsername";
dbCon.Password = "YourPassword";
if (dbCon.IsConnect())
{
    //suppose col0 and col1 are defined as VARCHAR in the DB
    string query = "SELECT col0,col1 FROM YourTable";
    var cmd = new MySqlCommand(query, dbCon.Connection);
    var reader = cmd.ExecuteReader();
    while(reader.Read())
    {
        string someStringFromColumnZero = reader.GetString(0);
        string someStringFromColumnOne = reader.GetString(1);
        Console.WriteLine(someStringFromColumnZero + "," + someStringFromColumnOne);
    }
    dbCon.Close();
}

C# IPAddress from string

You've probably miss-typed something above that bit of code or created your own class called IPAddress. If you're using the .net one, that function should be available.

Have you tried using System.Net.IPAddress just in case?

System.Net.IPAddress ipaddress = System.Net.IPAddress.Parse("127.0.0.1");  //127.0.0.1 as an example

The docs on Microsoft's site have a complete example which works fine on my machine.

.keyCode vs. .which

I'd recommend event.key currently. MDN docs: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/key

event.KeyCode and event.which both have nasty deprecated warnings at the top of their MDN pages:
https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/keyCode https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/which

For alphanumeric keys, event.key appears to be implemented identically across all browsers. For control keys (tab, enter, escape, etc), event.key has the same value across Chrome/FF/Safari/Opera but a different value in IE10/11/Edge (IEs apparently use an older version of the spec but match each other as of Jan 14 2018).

For alphanumeric keys a check would look something like:

event.key === 'a'

For control characters you'd need to do something like:

event.key === 'Esc' || event.key === 'Escape'

I used the example here to test on multiple browsers (I had to open in codepen and edit to get it to work with IE10): https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent/code

event.code is mentioned in a different answer as a possibility, but IE10/11/Edge don't implement it, so it's out if you want IE support.

change html text from link with jquery

$('#a_tbnotesverbergen').text('My New Link Text');

OR

$('#a_tbnotesverbergen').html('My New Link Text or HTML');

ReCaptcha API v2 Styling

Add a data-size property to the google recaptcha element and make it equal to "compact" in case of mobile.

Refer: google recaptcha docs

How to make a smaller RatingBar?

apply this.

<RatingBar android:id="@+id/indicator_ratingbar"
    style="?android:attr/ratingBarStyleIndicator"
    android:layout_marginLeft="5dip"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="center_vertical" />

How can I rename a conda environment?

conda create --name new_name --copy --clone old_name is better

I use conda create --name new_name --clone old_name which is without --copy but encountered pip breaks...

the following url may help Installing tensorflow in cloned conda environment breaks conda environment it was cloned from

Error when testing on iOS simulator: Couldn't register with the bootstrap server

I just had this error. I tried restarting the simulator and Xcode but my project would only work again after a clean and build. No idea what caused it.

Has an event handler already been added?

The only way that worked for me is creating a Boolean variable that I set to true when I add the event. Then I ask: If the variable is false, I add the event.

bool alreadyAdded = false;

This variable can be global.

if(!alreadyAdded)
{
    myClass.MyEvent += MyHandler;
    alreadyAdded = true;
}

How can I keep Bootstrap popovers alive while being hovered?

Here's my take: http://jsfiddle.net/WojtekKruszewski/Zf3m7/22/

Sometimes while moving mouse from popover trigger to actual popover content diagonally, you hover over elements below. I wanted to handle such situations – as long as you reach popover content before the timeout fires, you're safe (the popover won't disappear). It requires delay option.

This hack basically overrides Popover leave function, but calls the original (which starts timer to hide the popover). Then it attaches a one-off listener to mouseenter popover content element's.

If mouse enters the popover, the timer is cleared. Then it turns it listens to mouseleave on popover and if it's triggered, it calls the original leave function so that it could start hide timer.

var originalLeave = $.fn.popover.Constructor.prototype.leave;
$.fn.popover.Constructor.prototype.leave = function(obj){
  var self = obj instanceof this.constructor ?
    obj : $(obj.currentTarget)[this.type](this.getDelegateOptions()).data('bs.' + this.type)
  var container, timeout;

  originalLeave.call(this, obj);

  if(obj.currentTarget) {
    container = $(obj.currentTarget).siblings('.popover')
    timeout = self.timeout;
    container.one('mouseenter', function(){
      //We entered the actual popover – call off the dogs
      clearTimeout(timeout);
      //Let's monitor popover content instead
      container.one('mouseleave', function(){
        $.fn.popover.Constructor.prototype.leave.call(self, self);
      });
    })
  }
};

How to add an extra column to a NumPy array

np.r_[ ... ] and np.c_[ ... ] are useful alternatives to vstack and hstack, with square brackets [] instead of round ().
A couple of examples:

: import numpy as np
: N = 3
: A = np.eye(N)

: np.c_[ A, np.ones(N) ]              # add a column
array([[ 1.,  0.,  0.,  1.],
       [ 0.,  1.,  0.,  1.],
       [ 0.,  0.,  1.,  1.]])

: np.c_[ np.ones(N), A, np.ones(N) ]  # or two
array([[ 1.,  1.,  0.,  0.,  1.],
       [ 1.,  0.,  1.,  0.,  1.],
       [ 1.,  0.,  0.,  1.,  1.]])

: np.r_[ A, [A[1]] ]              # add a row
array([[ 1.,  0.,  0.],
       [ 0.,  1.,  0.],
       [ 0.,  0.,  1.],
       [ 0.,  1.,  0.]])
: # not np.r_[ A, A[1] ]

: np.r_[ A[0], 1, 2, 3, A[1] ]    # mix vecs and scalars
  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.])

: np.r_[ A[0], [1, 2, 3], A[1] ]  # lists
  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.])

: np.r_[ A[0], (1, 2, 3), A[1] ]  # tuples
  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.])

: np.r_[ A[0], 1:4, A[1] ]        # same, 1:4 == arange(1,4) == 1,2,3
  array([ 1.,  0.,  0.,  1.,  2.,  3.,  0.,  1.,  0.])

(The reason for square brackets [] instead of round () is that Python expands e.g. 1:4 in square -- the wonders of overloading.)

Create an array with same element repeated multiple times

Another one-liner:

Array.prototype.map.call([]+Array(5+1),function(){ return '2'; })

Unable to open debugger port in IntelliJ

Add the following parameter debug-enabled="true" to this line in the glassfish configuration. Example:

<java-config  debug-options="-Xdebug -Xrunjdwp:transport=dt_socket,server=y,suspend=n,address=9009" debug-enabled="true"
  system-classpath="" native-library-path-prefix="D:\Project\lib\windows\64bit" classpath-suffix="">

Start and stop the glassfish domain or service which was using this configuration.

How can I introduce multiple conditions in LIKE operator?

I also had the same requirement where I didn't have choice to pass like operator multiple times by either doing an OR or writing union query.

This worked for me in Oracle 11g:

REGEXP_LIKE (column, 'ABC.*|XYZ.*|PQR.*'); 

Is it possible to capture a Ctrl+C signal and run a cleanup function, in a "defer" fashion?

This is another version which work in case you have some tasks to cleanup. Code will leave clean up process in their method.

package main

import (
    "fmt"
    "os"
    "os/signal"
    "syscall"

)



func main() {

    _,done1:=doSomething1()
    _,done2:=doSomething2()

    //do main thread


    println("wait for finish")
    <-done1
    <-done2
    fmt.Print("clean up done, can exit safely")

}

func doSomething1() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something1
        done<-true
    }()
    return nil,done
}


func doSomething2() (error, chan bool) {
    //do something
    done:=make(chan bool)
    c := make(chan os.Signal, 2)
    signal.Notify(c, os.Interrupt, syscall.SIGTERM)
    go func() {
        <-c
        //cleanup of something2
        done<-true
    }()
    return nil,done
}

in case you need to clean main function you need to capture signal in main thread using go func() as well.

How to increase timeout for a single test case in mocha

(since I ran into this today)

Be careful when using ES2015 fat arrow syntax:

This will fail :

it('accesses the network', done => {

  this.timeout(500); // will not work

  // *this* binding refers to parent function scope in fat arrow functions!
  // i.e. the *this* object of the describe function

  done();
});

EDIT: Why it fails:

As @atoth mentions in the comments, fat arrow functions do not have their own this binding. Therefore, it's not possible for the it function to bind to this of the callback and provide a timeout function.

Bottom line: Don't use arrow functions for functions that need an increased timeout.

What is the difference between ndarray and array in numpy?

Just a few lines of example code to show the difference between numpy.array and numpy.ndarray

Warm up step: Construct a list

a = [1,2,3]

Check the type

print(type(a))

You will get

<class 'list'>

Construct an array (from a list) using np.array

a = np.array(a)

Or, you can skip the warm up step, directly have

a = np.array([1,2,3])

Check the type

print(type(a))

You will get

<class 'numpy.ndarray'>

which tells you the type of the numpy array is numpy.ndarray

You can also check the type by

isinstance(a, (np.ndarray))

and you will get

True

Either of the following two lines will give you an error message

np.ndarray(a)                # should be np.array(a)
isinstance(a, (np.array))    # should be isinstance(a, (np.ndarray))

How do I print colored output with Python 3?

This one answer I have got from the earlier python2 answers that is

  1. Install termcolor module.

    pip3 install termcolor

  2. Import the colored library from termcolor.

    from termcolor import colored

  3. Use the provided methods, below is an example.

    print(colored('hello', 'red'), colored('world', 'green'))

Spring Boot REST service exception handling

For REST controllers, I would recommend to use Zalando Problem Spring Web.

https://github.com/zalando/problem-spring-web

If Spring Boot aims to embed some auto-configuration, this library does more for exception handling. You just need to add the dependency:

<dependency>
    <groupId>org.zalando</groupId>
    <artifactId>problem-spring-web</artifactId>
    <version>LATEST</version>
</dependency>

And then define one or more advice traits for your exceptions (or use those provided by default)

public interface NotAcceptableAdviceTrait extends AdviceTrait {

    @ExceptionHandler
    default ResponseEntity<Problem> handleMediaTypeNotAcceptable(
            final HttpMediaTypeNotAcceptableException exception,
            final NativeWebRequest request) {
        return Responses.create(Status.NOT_ACCEPTABLE, exception, request);
    }

}

Then you can defined the controller advice for exception handling as:

@ControllerAdvice
class ExceptionHandling implements MethodNotAllowedAdviceTrait, NotAcceptableAdviceTrait {

}

Using unset vs. setting a variable to empty

Based on the comments above, here is a simple test:

isunset() { [[ "${!1}" != 'x' ]] && [[ "${!1-x}" == 'x' ]] && echo 1; }
isset()   { [ -z "$(isunset "$1")" ] && echo 1; }

Example:

$ unset foo; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's unset
$ foo=     ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set
$ foo=bar  ; [[ $(isunset foo) ]] && echo "It's unset" || echo "It's set"
It's set

Find out who is locking a file on a network share

Partial answer: With Process Explorer, you can view handles on a network share opened from your machine.

Use the Menu "Find Handle" and then you can type a path like this

\Device\LanmanRedirector\server\share\

Sort an array in Java

You may use Arrays.sort() function.

sort() method is a java.util.Arrays class method.          
Declaration : Arrays.sort(arrName)

Dropping a connected user from an Oracle 10g database schema

just use SQL :

disconnect; 

conn tiger/scott as sysdba;

Why use the params keyword?

One more important thing needs to be highlighted. It's better to use params because it is better for performance. When you call a method with params argument and passed to it nothing:

public void ExampleMethod(params string[] args)
{
// do some stuff
}

call:

ExampleMethod();

Then a new versions of the .Net Framework do this (from .Net Framework 4.6):

ExampleMethod(Array.Empty<string>());

This Array.Empty object can be reused by framework later, so there are no needs to do redundant allocations. These allocations will occur when you call this method like this:

 ExampleMethod(new string[] {});

Python UTC datetime object's ISO format doesn't include Z (Zulu or Zero offset)

The following javascript and python scripts give identical outputs. I think it's what you are looking for.

JavaScript

new Date().toISOString()

Python

from datetime import datetime

datetime.utcnow().isoformat()[:-3]+'Z'

The output they give is the utc (zelda) time formatted as an ISO string with a 3 millisecond significant digit and appended with a Z.

2019-01-19T23:20:25.459Z

How to import a SQL Server .bak file into MySQL?

In this problem, the answer is not updated in a timely. So it's happy to say that in 2020 Migrating to MsSQL into MySQL is that much easy. An online converter like RebaseData will do your job with one click. You can just upload your .bak file which is from MsSQL and convert it into .sql format which is readable to MySQL.

Additional note: This can not only convert your .bak files but also this site is for all types of Database migrations that you want.

Align DIV's to bottom or baseline

An old post but thought i would share an answer for anyone looking. And because when you use absolute things can go wrong. What I would do is

HTML

<div id="parentDiv"></div>
<div class="childDiv"></div>

The Css

parentDiv{

}
childDiv{
    height:40px;
    margin-top:-20px;
}

And that would just sit that bottom div back up into the parent div. safe for most browsers too

No Multiline Lambda in Python: Why not?

because a lambda function is supposed to be one-lined, as its the simplest form of a function, an entrance, then return

Are static methods inherited in Java?

Many have voiced out their answer in words. This is an extended explanation in codes:

public class A {
    public static void test() {
        System.out.println("A");
    }
    public static void test2() {
        System.out.println("Test");
    }
}

public class B extends A {
    public static void test() {
        System.out.println("B");
    }
}

// Called statically
A.test();
B.test();
System.out.println();

// Called statically, testing static inheritance
A.test2();
B.test2();
System.out.println();

// Called via instance object
A a = new A();
B b = new B();
a.test();
b.test();
System.out.println();

// Testing inheritance via instance call
a.test2();
b.test2();
System.out.println();

// Testing whether calling static method via instance object is dependent on compile or runtime type
((A) b).hi();
System.out.println();

// Testing whether null instance works
A nullObj = null;
nullObj.hi();

Results:

A
B

Test
Test

A
B

Test
Test

A

A

Therefore, this is the conclusion:

  1. When we call the static in a static manner via ., it will look for the static defined in that class, or the class nearest to that in the inheritance chain. This proves that static methods are inherited.
  2. When static method is called from an instance, it calls the static method defined in the compile-time type.
  3. Static method can be called from a null instance. My guess is that the compiler will use the variable type to find the class during compilation, and translate that to the appropriate static method call.

bower automatically update bower.json

from bower help, save option has a capital S

-S, --save  Save installed packages into the project's bower.json dependencies

How to pass anonymous types as parameters?

You can do it like this:

public void LogEmployees<T>(List<T> list) // Or IEnumerable<T> list
{
    foreach (T item in list)
    {

    }
}

... but you won't get to do much with each item. You could call ToString, but you won't be able to use (say) Name and Id directly.

indexOf Case Sensitive?

Here is my solution which does not allocate any heap memory, therefore it should be significantly faster than most of the other implementations mentioned here.

public static int indexOfIgnoreCase(final String haystack,
                                    final String needle) {
    if (needle.isEmpty() || haystack.isEmpty()) {
        // Fallback to legacy behavior.
        return haystack.indexOf(needle);
    }

    for (int i = 0; i < haystack.length(); ++i) {
        // Early out, if possible.
        if (i + needle.length() > haystack.length()) {
            return -1;
        }

        // Attempt to match substring starting at position i of haystack.
        int j = 0;
        int ii = i;
        while (ii < haystack.length() && j < needle.length()) {
            char c = Character.toLowerCase(haystack.charAt(ii));
            char c2 = Character.toLowerCase(needle.charAt(j));
            if (c != c2) {
                break;
            }
            j++;
            ii++;
        }
        // Walked all the way to the end of the needle, return the start
        // position that this was found.
        if (j == needle.length()) {
            return i;
        }
    }

    return -1;
}

And here are the unit tests that verify correct behavior.

@Test
public void testIndexOfIgnoreCase() {
    assertThat(StringUtils.indexOfIgnoreCase("A", "A"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("a", "A"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("A", "a"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("a", "a"), is(0));

    assertThat(StringUtils.indexOfIgnoreCase("a", "ba"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase("ba", "a"), is(1));

    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", " Royal Blue"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase(" Royal Blue", "Royal Blue"), is(1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "royal"), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "oyal"), is(1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "al"), is(3));
    assertThat(StringUtils.indexOfIgnoreCase("", "royal"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", ""), is(0));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "BLUE"), is(6));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "BIGLONGSTRING"), is(-1));
    assertThat(StringUtils.indexOfIgnoreCase("Royal Blue", "Royal Blue LONGSTRING"), is(-1));  
}

Rails: select unique values from a column

Another way to collect uniq columns with sql:

Model.group(:rating).pluck(:rating)

How to Convert the value in DataTable into a string array in c#

 
            string[] result = new string[table.Columns.Count];
            DataRow dr = table.Rows[0];
            for (int i = 0; i < dr.ItemArray.Length; i++)
            {
                result[i] = dr[i].ToString();
            }
            foreach (string str in result)
                Console.WriteLine(str);

Binding value to input in Angular JS

Use ng-value for set value of input box after clicking on a button:

"input type="email"  class="form-control" id="email2" ng-value="myForm.email2" placeholder="Email"

and

Set Value as:

 $scope.myForm.email2 = $scope.names[0].success;

Remove ALL styling/formatting from hyperlinks

As Chris said before me, just an a should override. For example:

a { color:red; }
a:hover { color:blue; }
.nav a { color:green; }

In this instance the .nav a would ALWAYS be green, the :hover wouldn't apply to it.

If there's some other rule affecting it, you COULD use !important, but you shouldn't. It's a bad habit to fall into.

.nav a { color:green !important; } /*I'm a bad person and shouldn't use !important */

Then it'll always be green, irrelevant of any other rule.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

Yes, the moment jQuery sees the URL belongs to a different domain, it assumes that call as a cross domain call, thus crossdomain:true is not required here.

Also, important to note that you cannot make a synchronous call with $.ajax if your URL belongs to a different domain (cross domain) or you are using JSONP. Only async calls are allowed.

Note: you can call the service synchronously if you specify the async:false with your request.

How to get the selected radio button’s value?

In case someone was looking for an answer and landed here like me, from Chrome 34 and Firefox 33 you can do the following:

var form = document.theForm;
var radios = form.elements['genderS'];
alert(radios.value);

or simpler:

alert(document.theForm.genderS.value);

refrence: https://developer.mozilla.org/en-US/docs/Web/API/RadioNodeList/value

How to paste yanked text into the Vim command line

OS X

If you are using Vim in Mac OS X, unfortunately it comes with older version, and not complied with clipboard options. Luckily, Homebrew can easily solve this problem.

Install Vim:

brew install vim --with-lua --with-override-system-vi

Install the GUI version of Vim:

brew install macvim --with-lua --with-override-system-vi

Restart the terminal for it to take effect.


Append the following line to ~/.vimrc
set clipboard=unnamed

Now you can copy the line in Vim with yy and paste it system-wide.

Mvn install or Mvn package

from http://maven.apache.org/guides/getting-started/maven-in-five-minutes.html

package: take the compiled code and package it in its distributable format, such as a JAR.

install: install the package into the local repository, for use as a dependency in other projects locally

So the answer to your question is, it depends on whether you want it in installed into your local repo. Install will also run package because it's higher up in the goal phase stack.

Location Services not working in iOS 8

The old code for asking location won't work in iOS 8. You can try this method for location authorization:

- (void)requestAlwaysAuthorization
{
    CLAuthorizationStatus status = [CLLocationManager authorizationStatus];

    // If the status is denied or only granted for when in use, display an alert
    if (status == kCLAuthorizationStatusAuthorizedWhenInUse || status ==        kCLAuthorizationStatusDenied) {
        NSString *title;
        title = (status == kCLAuthorizationStatusDenied) ? @"Location services are off" :   @"Background location is not enabled";
        NSString *message = @"To use background location you must turn on 'Always' in the Location Services Settings";

        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title
                                                            message:message
                                                           delegate:self
                                                  cancelButtonTitle:@"Cancel"
                                                  otherButtonTitles:@"Settings", nil];
        [alertView show];
    }
    // The user has not enabled any location services. Request background authorization.
    else if (status == kCLAuthorizationStatusNotDetermined) {
        [self.locationManager requestAlwaysAuthorization];
    }
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 1) {
        // Send the user to the Settings for this app
        NSURL *settingsURL = [NSURL URLWithString:UIApplicationOpenSettingsURLString];
        [[UIApplication sharedApplication] openURL:settingsURL];
    }
}

Dictionary text file

What about /usr/share/dict/words on any Unix system? How many words are we talking about? Like OED-Unabridged?

How to delete specific characters from a string in Ruby?

For those coming across this and looking for performance, it looks like #delete and #tr are about the same in speed and 2-4x faster than gsub.

text = "Here is a string with / some forwa/rd slashes"
tr = Benchmark.measure { 10000.times { text.tr('/', '') } }
# tr.total => 0.01
delete = Benchmark.measure { 10000.times { text.delete('/') } }
# delete.total => 0.01
gsub = Benchmark.measure { 10000.times { text.gsub('/', '') } }
# gsub.total => 0.02 - 0.04

Are there any naming convention guidelines for REST APIs?

If you authenticate your clients with Oauth2 I think you will need underscore for at least two of your parameter names:

  • client_id
  • client_secret

I have used camelCase in my (not yet published) REST API. While writing the API documentation I have been thinking of changing everything to snake_case so I don't have to explain why the Oauth params are snake_case while other params are not.

See: https://tools.ietf.org/html/rfc6749

py2exe - generate single executable file

I'm told bbfreeze will create a single file .EXE, and is newer than py2exe.

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

This command shows the configured heap sizes in bytes.

java -XX:+PrintFlagsFinal -version | grep HeapSize

It works on Amazon AMI on EC2 as well.

How to install beautiful soup 4 with python 2.7 on windows

Install pip

Download get-pip. Remember to save it as "get-pip.py"

Now go to the download folder. Right click on get-pip.py then open with python.exe.

You can add system variable by

(by doing this you can use pip and easy_install without specifying path)

1 Clicking on Properties of My Computer

2 Then chose Advanced System Settings

3 Click on Advanced Tab

4 Click on Environment Variables

5 From System Variables >>> select variable path.

6 Click edit then add the following lines at the end of it

 ;c:\Python27;c:\Python27\Scripts

(please dont copy this, just go to your python directory and copy the paths similar to this)

NB:- you have to do this once only.

Install beautifulsoup4

Open cmd and type

pip install beautifulsoup4

Converting a vector<int> to string

Maybe std::ostream_iterator and std::ostringstream:

#include <vector>
#include <string>
#include <algorithm>
#include <sstream>
#include <iterator>
#include <iostream>

int main()
{
  std::vector<int> vec;
  vec.push_back(1);
  vec.push_back(4);
  vec.push_back(7);
  vec.push_back(4);
  vec.push_back(9);
  vec.push_back(7);

  std::ostringstream oss;

  if (!vec.empty())
  {
    // Convert all but the last element to avoid a trailing ","
    std::copy(vec.begin(), vec.end()-1,
        std::ostream_iterator<int>(oss, ","));

    // Now add the last element with no delimiter
    oss << vec.back();
  }

  std::cout << oss.str() << std::endl;
}

What is the difference between `let` and `var` in swift?

Let is an immutable variable, meaning that it cannot be changed, other languages call this a constant. In C++ it you can define it as const.

Var is a mutable variable, meaning that it can be changed. In C++ (2011 version update), it is the same as using auto, though swift allows for more flexibility in the usage. This is the more well-known variable type to beginners.

How do I get values from a SQL database into textboxes using C#?

If you want to display single value access from database into textbox, please refer to the code below:

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
TextBox1.Text=cmd.ExecuteScalar();
Con.Close();

or

SqlConnection con=new SqlConnection("connection string");
SqlCommand cmd=new SqlConnection(SqlQuery,Con);
Con.Open();
SqlDataReader dr=new SqlDataReadr();
dr=cmd.Executereader();
if(dr.read())
{
    TextBox1.Text=dr.GetValue(0).Tostring();
}
Con.Close();

jQuery: How to get the HTTP status code from within the $.ajax.error method?

An other solution is to use the response.status function. This will give you the http status wich is returned by the ajax call.

function checkHttpStatus(url) {     
    $.ajax({
        type: "GET",
        data: {},
        url: url,
        error: function(response) {
            alert(url + " returns a " + response.status);
        }, success() {
            alert(url + " Good link");
        }
    });
}

Delete an element from a dictionary

>>> def delete_key(dict, key):
...     del dict[key]
...     return dict
... 
>>> test_dict = {'one': 1, 'two' : 2}
>>> print delete_key(test_dict, 'two')
{'one': 1}
>>>

this doesn't do any error handling, it assumes the key is in the dict, you might want to check that first and raise if its not

How to compare two vectors for equality element by element in C++?

C++11 standard on == for std::vector

Others have mentioned that operator== does compare vector contents and works, but here is a quote from the C++11 N3337 standard draft which I believe implies that.

We first look at Chapter 23.2.1 "General container requirements", which documents things that must be valid for all containers, including therefore std::vector.

That section Table 96 "Container requirements" which contains an entry:

Expression   Operational semantics
===========  ======================
a == b       distance(a.begin(), a.end()) == distance(b.begin(), b.end()) &&
             equal(a.begin(), a.end(), b.begin())

The distance part of the semantics means that the size of both containers are the same, but stated in a generalized iterator friendly way for non random access addressable containers. distance() is defined at 24.4.4 "Iterator operations".

Then the key question is what does equal() mean. At the end of the table we see:

Notes: the algorithm equal() is defined in Clause 25.

and in section 25.2.11 "Equal" we find its definition:

template<class InputIterator1, class InputIterator2>
bool equal(InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2);

template<class InputIterator1, class InputIterator2,
class BinaryPredicate>
bool equal(InputIterator1 first1, InputIterator1 last1,
           InputIterator2 first2, BinaryPredicate pred);

1 Returns: true if for every iterator i in the range [first1,last1) the following corresponding conditions hold: *i == *(first2 + (i - first1)), pred(*i, *(first2 + (i - first1))) != false. Otherwise, returns false.

In our case, we care about the overloaded version without BinaryPredicate version, which corresponds to the first pseudo code definition *i == *(first2 + (i - first1)), which we see is just an iterator-friendly definition of "all iterated items are the same".

Similar questions for other containers:

Error starting Tomcat from NetBeans - '127.0.0.1*' is not recognized as an internal or external command

I didnt try Sumama Waheed's answer but what worked for me was replacing the bin/catalina.jar with a working jar (I disposed of an older tomcat) and after adding in NetBeans, I put the original catalina.jar again.

Detecting when Iframe content has loaded (Cross browser)

See this blog post. It uses jQuery, but it should help you even if you are not using it.

Basically you add this to your document.ready()

$('iframe').load(function() {
    RunAfterIFrameLoaded();
});

Eclipse CDT: no rule to make target all

Sometimes if you are making a target via make files double check that all c files are named correctly with correct file structure.

using where and inner join in mysql

Try this :

SELECT
    (
      SELECT
          `NAME`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
    ) as `NAME`
FROM
     school_locations
WHERE
     (
      SELECT
          `TYPE`
      FROM
          locations
      WHERE
          ID = school_locations.LOCATION_ID
     ) = 'coun';

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

Is there an equivalent to the SUBSTRING function in MS Access SQL?

You can use the VBA string functions (as @onedaywhen points out in the comments, they are not really the VBA functions, but their equivalents from the MS Jet libraries. As far as function signatures go, they are called and work the same, even though the actual presence of MS Access is not required for them to be available.):

SELECT DISTINCT Left(LastName, 1)
FROM Authors;

SELECT DISTINCT Mid(LastName, 1, 1)
FROM Authors;

How do I run a batch file from my Java Application?

To run batch files using java if that's you're talking about...

String path="cmd /c start d:\\sample\\sample.bat";
Runtime rn=Runtime.getRuntime();
Process pr=rn.exec(path);`

This should do it.

JPA Hibernate Persistence exception [PersistenceUnit: default] Unable to build Hibernate SessionFactory

I found some issue about that kind of error

  1. Database username or password not match in the mysql or other other database. Please set application.properties like this

  

# =============================== # = DATA SOURCE # =============================== # Set here configurations for the database connection # Connection url for the database please let me know "[email protected]" spring.datasource.url = jdbc:mysql://localhost:3306/bookstoreapiabc # Username and secret spring.datasource.username = root spring.datasource.password = # Keep the connection alive if idle for a long time (needed in production) spring.datasource.testWhileIdle = true spring.datasource.validationQuery = SELECT 1 # =============================== # = JPA / HIBERNATE # =============================== # Use spring.jpa.properties.* for Hibernate native properties (the prefix is # stripped before adding them to the entity manager). # Show or not log for each sql query spring.jpa.show-sql = true # Hibernate ddl auto (create, create-drop, update): with "update" the database # schema will be automatically updated accordingly to java entities found in # the project spring.jpa.hibernate.ddl-auto = update # Allows Hibernate to generate SQL optimized for a particular DBMS spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5Dialect

Issue no 2.

Your local server has two database server and those database server conflict. this conflict like this mysql server & xampp or lampp or wamp server. Please one of the database like mysql server because xampp or lampp server automatically install mysql server on this machine

Heroku deployment error H10 (App crashed)

I had this problem when trying to run Rails in a subdirectory, and not in /. For example, I had Angular/Node/Gulp app running in /client and a Rails app running in /server, but both of them were in the same git repo, so I could track changes across the front end and back end. I got this error when trying to deploy them to Heroku. For anyone else having this issue, here is a custom buildpack that will allow running Rails in a subdirectory.

https://github.com/aarongray/heroku-buildpack-ruby

make: Nothing to be done for `all'

When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.

If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.

If they are not present, make blindly builds everything under the rule.

Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!

regular expression for finding 'href' value of a <a> link

I'd recommend using an HTML parser over a regex, but still here's a regex that will create a capturing group over the value of the href attribute of each links. It will match whether double or single quotes are used.

<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1

You can view a full explanation of this regex at here.

Snippet playground:

_x000D_
_x000D_
const linkRx = /<a\s+(?:[^>]*?\s+)?href=(["'])(.*?)\1/;_x000D_
const textToMatchInput = document.querySelector('[name=textToMatch]');_x000D_
_x000D_
document.querySelector('button').addEventListener('click', () => {_x000D_
  console.log(textToMatchInput.value.match(linkRx));_x000D_
});
_x000D_
<label>_x000D_
  Text to match:_x000D_
  <input type="text" name="textToMatch" value='<a href="google.com"'>_x000D_
  _x000D_
  <button>Match</button>_x000D_
 </label>
_x000D_
_x000D_
_x000D_

Can't use Swift classes inside Objective-C

my problem was I got stuck after xcode created the bridge file but still I got error in header file name MYPROJECTNAME-swift.h

1.I check in terminal and search for all auto created swift bridge files:

find ~/library/Developer/Xcode/DerivedData/ -name "*-Swift.h"|xargs basename|sort -

you see what xcode created.

  1. in my case, I had space in my project name and xcode replace this is '_'

CSS display:inline property with list-style-image: property on <li> tags

Try using float: left (or right) instead of display: inline. Inline display replaces list-item display, which is what adds the bullet points.

When should we call System.exit in Java

Java Language Specification says that

Program Exit

A program terminates all its activity and exits when one of two things happens:

All the threads that are not daemon threads terminate.

Some thread invokes the exit method of class Runtime or class System, and the exit operation is not forbidden by the security manager.

It means that You should use it when You have big program (well, at lest bigger than this one) and want to finish its execution.

How to simplify a null-safe compareTo() implementation?

I would implement a null safe comparator. There may be an implementation out there, but this is so straightforward to implement that I've always rolled my own.

Note: Your comparator above, if both names are null, won't even compare the value fields. I don't think this is what you want.

I would implement this with something like the following:

// primarily by name, secondarily by value; null-safe; case-insensitive
public int compareTo(final Metadata other) {

    if (other == null) {
        throw new NullPointerException();
    }

    int result = nullSafeStringComparator(this.name, other.name);
    if (result != 0) {
        return result;
    }

    return nullSafeStringComparator(this.value, other.value);
}

public static int nullSafeStringComparator(final String one, final String two) {
    if (one == null ^ two == null) {
        return (one == null) ? -1 : 1;
    }

    if (one == null && two == null) {
        return 0;
    }

    return one.compareToIgnoreCase(two);
}

EDIT: Fixed typos in code sample. That's what I get for not testing it first!

EDIT: Promoted nullSafeStringComparator to static.

Setting java locale settings

I had to control this in a script that ran on a machine with French locale, but a specific Java program had to run with en_US. As already pointed out, the following works:

java -Duser.language=en -Duser.country=US ...

Alternatively,

LC_ALL=en_US.UTF-8 java ...

I prefer the latter.

SQL Network Interfaces, error: 50 - Local Database Runtime error occurred. Cannot create an automatic instance

Running this:

sqllocaldb create "v12.0"

From cmd prompt solved this for me...

How can I read and manipulate CSV file data in C++?

You can try the Boost Tokenizer library, in particular the Escaped List Separator

Assign format of DateTime with data annotations?

Use EditorFor rather than TextBoxFor

Display Adobe pdf inside a div

Here is another way to display PDF inside Div by using Iframe like below.

_x000D_
_x000D_
<div>_x000D_
  <iframe src="/pdf/test.pdf" style="width:100%;height:700px;"></iframe>_x000D_
</div>_x000D_
<div>_x000D_
  <!-- I agree button -->_x000D_
</div>
_x000D_
_x000D_
_x000D_

Mask output of `The following objects are masked from....:` after calling attach() function

If you look at the down arrow in environment tab. The attached file can appear multiple times. You may need to highlight and run detach(filename) several times until all cases are gone then attach(newfilename) should have no output message.

attached files under environment tab

Controlling number of decimal digits in print output in R

If you are producing the entire output yourself, you can use sprintf(), e.g.

> sprintf("%.10f",0.25)
[1] "0.2500000000"

specifies that you want to format a floating point number with ten decimal points (in %.10f the f is for float and the .10 specifies ten decimal points).

I don't know of any way of forcing R's higher level functions to print an exact number of digits.

Displaying 100 digits does not make sense if you are printing R's usual numbers, since the best accuracy you can get using 64-bit doubles is around 16 decimal digits (look at .Machine$double.eps on your system). The remaining digits will just be junk.

Should you use rgba(0, 0, 0, 0) or rgba(255, 255, 255, 0) for transparency in CSS?

I would recommend using rgba(255,255,255,0) because broken (newest) safari thinks that if you are using transparent or rgba(0,0,0,0) in linear-gradent you really mean gray, For more info please head to - What happens in Safari with the transparent color?

How do I write a method to calculate total cost for all items in an array?

In your for loop you need to multiply the units * price. That gives you the total for that particular item. Also in the for loop you should add that to a counter that keeps track of the grand total. Your code would look something like

float total;
total += theItem.getUnits() * theItem.getPrice();

total should be scoped so it's accessible from within main unless you want to pass it around between function calls. Then you can either just print out the total or create a method that prints it out for you.

php implode (101) with quotes

Another possible option, depending on what you need the array for:

$array = array('lastname', 'email', 'phone');
echo json_encode($array);

This will put '[' and ']' around the string, which you may or may not want.

vertical align middle in <div>

I found this solution by Sebastian Ekström. It's quick, dirty, and works really well. Even if you don't know the parent's height:

.element {
  position: relative;
  top: 50%;
  -webkit-transform: translateY(-50%);
  -ms-transform: translateY(-50%);
  transform: translateY(-50%);
}

Read the full article here.

Stop node.js program from command line

I ran into an issue where I have multiple node servers running, and I want to just kill one of them and redeploy it from a script.

Note: This example is in a bash shell on Mac.

To do so I make sure to make my node call as specific as possible. For example rather than calling node server.js from the apps directory, I call node app_name_1/app/server.js

Then I can kill it using:

kill -9 $(ps aux | grep 'node\ app_name_1/app/server.js' | awk '{print $2}')

This will only kill the node process running app_name_1/app/server.js.

If you ran node app_name_2/app/server.js this node process will continue to run.

If you decide you want to kill them all you can use killall node as others have mentioned.

org.apache.catalina.LifecycleException: Failed to start component [StandardServer[8005]]A child container failed during start

In my case, the servlet-api.jar file in jre/lib/ext in the jdk directory conflicts with the servlet-api.jar file in tomcat, removing the servlet-api.jar in jre/lib/ext in the jdk directory can solve the problem.

Convert array of JSON object strings to array of JS objects

var json = jQuery.parseJSON(s); //If you have jQuery.

Since the comment looks cluttered, please use the parse function after enclosing those square brackets inside the quotes.

var s=['{"Select":"11","PhotoCount":"12"}','{"Select":"21","PhotoCount":"22"}'];

Change the above code to

var s='[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

Eg:

$(document).ready(function() {
    var s= '[{"Select":"11","PhotoCount":"12"},{"Select":"21","PhotoCount":"22"}]';

    s = jQuery.parseJSON(s);

    alert( s[0]["Select"] );
});

And then use the parse function. It'll surely work.

EDIT :Extremely sorry that I gave the wrong function name. it's jQuery.parseJSON

Jquery

The json api

Edit (30 April 2020):

Editing since I got an upvote for this answer. There's a browser native function available instead of JQuery (for nonJQuery users), JSON.parse("<json string here>")

How to install iPhone application in iPhone Simulator

Enter the following in the terminal:

$/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iPhone\ Simulator.app/Contents/MacOS/iPhone\ Simulator -SimulateApplication path/to/your/file/projectname.app/projectname

How can git be installed on CENTOS 5.5?

yum -y install zlib-devel openssl-devel cpio expat-devel gettext-devel

Get the required version of GIT from https://www.kernel.org/pub/software/scm/git/ 

wget https://www.kernel.org/pub/software/scm/git/{version.gz}

tar -xzvf git-version.gz

cd git-version

./configure

make

make install

Difference between "this" and"super" keywords in Java

When writing code you generally don't want to repeat yourself. If you have an class that can be constructed with various numbers of parameters a common solution to avoid repeating yourself is to simply call another constructor with defaults in the missing arguments. There is only one annoying restriction to this - it must be the first line of the declared constructor. Example:

MyClass()
{
   this(default1, default2);
}

MyClass(arg1, arg2)
{
   validate arguments, etc...
   note that your validation logic is only written once now
}

As for the super() constructor, again unlike super.method() access it must be the first line of your constructor. After that it is very much like the this() constructors, DRY (Don't Repeat Yourself), if the class you extend has a constructor that does some of what you want then use it and then continue with constructing your object, example:

YourClass extends MyClass
{
   YourClass(arg1, arg2, arg3)
   {
      super(arg1, arg2) // calls MyClass(arg1, arg2)
      validate and process arg3...
   }
}

Additional information:

Even though you don't see it, the default no argument constructor always calls super() first. Example:

MyClass()
{
}

is equivalent to

MyClass()
{
   super();
}

I see that many have mentioned using the this and super keywords on methods and variables - all good. Just remember that constructors have unique restrictions on their usage, most notable is that they must be the very first instruction of the declared constructor and you can only use one.

Determine which element the mouse pointer is on top of in JavaScript

You can look at the target of the mouseover event on some suitable ancestor:

var currentElement = null;

document.addEventListener('mouseover', function (e) {
    currentElement = e.target;
});

Here’s a demo.

How to check if an user is logged in Symfony2 inside a controller?

If you using roles you could check for ROLE_USER that is the solution i use:

if (TRUE === $this->get('security.authorization_checker')->isGranted('ROLE_USER')) {
    // user is logged in
} 

What is two way binding?

Two-way binding means that any data-related changes affecting the model are immediately propagated to the matching view(s), and that any changes made in the view(s) (say, by the user) are immediately reflected in the underlying model. When app data changes, so does the UI, and conversely.

This is a very solid concept to build a web application on top of, because it makes the "Model" abstraction a safe, atomic data source to use everywhere within the application. Say, if a model, bound to a view, changes, then its matching piece of UI (the view) will reflect that, no matter what. And the matching piece of UI (the view) can safely be used as a mean of collecting user inputs/data, so as to maintain the application data up-to-date.

A good two-way binding implementation should obviously make this connection between a model and some view(s) as simple as possible, from a developper point of view.

It is then quite untrue to say that Backbone does not support two-way binding: while not a core feature of the framework, it can be performed quite simply using Backbone's Events though. It costs a few explicit lines of code for the simple cases; and can become quite hazardous for more complex bindings. Here is a simple case (untested code, written on the fly just for the sake of illustration):

Model = Backbone.Model.extend
  defaults:
    data: ''

View = Backbone.View.extend
  template: _.template("Edit the data: <input type='text' value='<%= data %>' />")

  events:
    # Listen for user inputs, and edit the model.
    'change input': @setData

  initialize: (options) ->
    # Listen for model's edition, and trigger UI update
    @listenTo @model, 'change:data', @render

  render: ->
    @$el.html @template(@model.attributes)
    @

  setData: (e) =>
    e.preventDefault()
    @model.set 'data', $(e.currentTarget).value()

model: new Model()
view = new View {el: $('.someEl'), model: model}

This is a pretty typical pattern in a raw Backbone application. As one can see, it requires a decent amount of (pretty standard) code.

AngularJS and some other alternatives (Ember, Knockout…) provide two-way binding as a first-citizen feature. They abstract many edge-cases under some DSL, and do their best at integrating two-way binding within their ecosystem. Our example would look something like this with AngularJS (untested code, see above):

<div ng-app="app" ng-controller="MainCtrl">
  Edit the data:
  <input name="mymodel.data" ng-model="mymodel.data">
</div>
angular.module('app', [])
  .controller 'MainCtrl', ($scope) ->
    $scope.mymodel = {data: ''}

Rather short!

But, be aware that some fully-fledged two-way binding extensions do exist for Backbone as well (in raw, subjective order of decreasing complexity): Epoxy, Stickit, ModelBinder

One cool thing with Epoxy, for instance, is that it allows you to declare your bindings (model attributes <-> view's DOM element) either within the template (DOM), or within the view implementation (JavaScript). Some people strongly dislike adding "directives" to the DOM/template (such as the ng-* attributes required by AngularJS, or the data-bind attributes of Ember).

Taking Epoxy as an example, one can rework the raw Backbone application into something like this (…):

Model = Backbone.Model.extend
  defaults:
    data: ''

View = Backbone.Epoxy.View.extend
  template: _.template("Edit the data: <input type='text' />")
  # or, using the inline form: <input type='text' data-bind='value:data' />

  bindings:
    'input': 'value:data'

  render: ->
    @$el.html @template(@model.attributes)
    @

model: new Model()
view = new View {el: $('.someEl'), model: model}

All in all, pretty much all "mainstream" JS frameworks support two-way binding. Some of them, such as Backbone, do require some extra work to make it work smoothly, but those are the same which do not enforce a specific way to do it, to begin with. So it is really about your state of mind.

Also, you may be interested in Flux, a different architecture for web applications promoting one-way binding through a circular pattern. It is based on the concept of fast, holistic re-rendering of UI components upon any data change to ensure cohesiveness and make it easier to reason about the code/dataflow. In the same trend, you might want to check the concept of MVI (Model-View-Intent), for instance Cycle.

How to reload a page using Angularjs?

Be sure to include the $route service into your scope and do this:

$route.reload();

See this:

How to reload or re-render the entire page using AngularJS

How to outline text in HTML / CSS

Try this:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

...and you might also want to do this too:

_x000D_
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml">_x000D_
<head>_x000D_
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />_x000D_
<title>Untitled Document</title>_x000D_
<style type="text/css">_x000D_
.OutlineText {_x000D_
 font: Tahoma, Geneva, sans-serif;_x000D_
 font-size: 64px;_x000D_
    color: white;_x000D_
    text-shadow:_x000D_
    /* Outline 1 */_x000D_
    -1px -1px 0 #000000,_x000D_
    1px -1px 0 #000000,_x000D_
    -1px 1px 0 #000000,_x000D_
    1px 1px 0 #000000,  _x000D_
    -2px 0 0 #000000,_x000D_
    2px 0 0 #000000,_x000D_
    0 2px 0 #000000,_x000D_
    0 -2px 0 #000000, _x000D_
    /* Outline 2 */_x000D_
    -2px -2px 0 #ff0000,_x000D_
    2px -2px 0 #ff0000,_x000D_
    -2px 2px 0 #ff0000,_x000D_
    2px 2px 0 #ff0000,  _x000D_
    -3px 0 0 #ff0000,_x000D_
    3px 0 0 #ff0000,_x000D_
    0 3px 0 #ff0000,_x000D_
    0 -3px 0 #ff0000; /* Terminate with a semi-colon */_x000D_
}_x000D_
</style></head>_x000D_
_x000D_
<body>_x000D_
<div class="OutlineText">Hello world!</div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

You can do as many Outlines as you like, and there's enough scope for coming up with lots of creative ideas.

Have fun!

'Connect-MsolService' is not recognized as the name of a cmdlet

This issue can occur if the Azure Active Directory Module for Windows PowerShell isn't loaded correctly.

To resolve this issue, follow these steps.
1.Install the Azure Active Directory Module for Windows PowerShell on the computer (if it isn't already installed). To install the Azure Active Directory Module for Windows PowerShell, go to the following Microsoft website:
Manage Azure AD using Windows PowerShell

2.If the MSOnline module isn't present, use Windows PowerShell to import the MSOnline module.

Import-Module MSOnline 

After it complete, we can use this command to check it.

PS C:\Users> Get-Module -ListAvailable -Name MSOnline*


    Directory: C:\windows\system32\WindowsPowerShell\v1.0\Modules


ModuleType Version    Name                                ExportedCommands
---------- -------    ----                                ----------------
Manifest   1.1.166.0  MSOnline                            {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}
Manifest   1.1.166.0  MSOnlineExtended                    {Get-MsolDevice, Remove-MsolDevice, Enable-MsolDevice, Disable-MsolDevice...}

More information about this issue, please refer to it.


Update:

We should import azure AD powershell to VS 2015, we can add tool and select Azure AD powershell.

enter image description here

addEventListener for keydown on Canvas

Sometimes just setting canvas's tabindex to '1' (or '0') works. But sometimes - it doesn't, for some strange reason.

In my case (ReactJS app, dynamic canvas el creation and mount) I need to call canvasEl.focus() to fix it. Maybe this is somehow related to React (my old app based on KnockoutJS works without '..focus()' )

Tesseract running error

tesseract  --tessdata-dir <tessdata-folder> <image-path> stdout --oem 2 -l <lng>

In my case, the mistakes that I've made or attempts that wasn't a success.

  • I cloned the github repo and copied files from there to
    • /usr/local/share/tessdata/
    • /usr/share/tesseract-ocr/tessdata/
    • /usr/share/tessdata/
  • Used TESSDATA_PREFIX with above paths
  • sudo apt-get install tesseract-ocr-eng

First 2 attempts did not worked because, the files from git clone did not worked for the reasons that I do not know. I am not sure why #3 attempt worked for me.

Finally,

  1. I downloaded the eng.traindata file using wget
  2. Copied it to some directory
  3. Used --tessdata-dir with directory name

Take away for me is to learn the tool well & make use of it, rather than relying on package manager installation & directories

Sorting a list with stream.sorted() in Java

Java 8 provides different utility api methods to help us sort the streams better.

If your list is a list of Integers(or Double, Long, String etc.,) then you can simply sort the list with default comparators provided by java.

List<Integer> integerList = Arrays.asList(1, 4, 3, 4, 5);

Creating comparator on fly:

integerList.stream().sorted((i1, i2) -> i1.compareTo(i2)).forEach(System.out::println);

With default comparator provided by java 8 when no argument passed to sorted():

integerList.stream().sorted().forEach(System.out::println); //Natural order

If you want to sort the same list in reverse order:

 integerList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println); // Reverse Order

If your list is a list of user defined objects, then:

List<Person> personList = Arrays.asList(new Person(1000, "First", 25, 30000),
        new Person(2000, "Second", 30, 45000),
        new Person(3000, "Third", 35, 25000));

Creating comparator on fly:

personList.stream().sorted((p1, p2) -> ((Long)p1.getPersonId()).compareTo(p2.getPersonId()))
        .forEach(person -> System.out.println(person.getName()));

Using Comparator.comparingLong() method(We have comparingDouble(), comparingInt() methods too):

personList.stream().sorted(Comparator.comparingLong(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

Using Comparator.comparing() method(Generic method which compares based on the getter method provided):

personList.stream().sorted(Comparator.comparing(Person::getPersonId)).forEach(person -> System.out.println(person.getName()));

We can do chaining too using thenComparing() method:

personList.stream().sorted(Comparator.comparing(Person::getPersonId).thenComparing(Person::getAge)).forEach(person -> System.out.println(person.getName())); //Sorting by person id and then by age.

Person class

public class Person {
    private long personId;
    private String name;
    private int age;
    private double salary;

    public long getPersonId() {
        return personId;
    }

    public void setPersonId(long personId) {
        this.personId = personId;
    }

    public Person(long personId, String name, int age, double salary) {
        this.personId = personId;
        this.name = name;
        this.age = age;

        this.salary = salary;
    }

    public String getName() {
        return name;
    }

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

    public int getAge() {
        return age;
    }

    public void setAge(int age) {
        this.age = age;
    }

    public double getSalary() {
        return salary;
    }

    public void setSalary(double salary) {
        this.salary = salary;
    }
}

Easy way to convert Iterable to Collection

I didn't see a simple one line solution without any dependencies. I simple use

List<Users> list;
Iterable<IterableUsers> users = getUsers();

// one line solution
list = StreamSupport.stream(users.spliterator(), true).collect(Collectors.toList());

Output ("echo") a variable to a text file

Your sample code seems to be OK. Thus, the root problem needs to be dug up somehow. Let's eliminate chance for typos in the script. First off, make sure you put Set-Strictmode -Version 2.0 in the beginning of your script. This will help you to catch misspelled variable names. Like so,

# Test.ps1
set-strictmode -version 2.0 # Comment this line and no error will be reported.
$foo = "bar"
set-content -path ./test.txt -value $fo # Error! Should be "$foo"

PS C:\temp> .\test.ps1
The variable '$fo' cannot be retrieved because it has not been set.
At C:\temp\test.ps1:3 char:40
+ set-content -path ./test.txt -value $fo <<<<
    + CategoryInfo          : InvalidOperation: (fo:Token) [], RuntimeException
    + FullyQualifiedErrorId : VariableIsUndefined

The next part about question marks sounds like you have a problem with Unicode. What's the output when you type the file with Powershell like so,

$file = "\\server\share\file.txt"
cat $file

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

Some quick but extremely useful additional information that I just learned from another post, but can't seem to find the documentation for (if anyone can share a link to it on MSDN that would be amazing):

The validation messages associated with these attributes will actually replace placeholders associated with the attributes. For example:

[MaxLength(100, "{0} can have a max of {1} characters")]
public string Address { get; set; }

Will output the following if it is over the character limit: "Address can have a max of 100 characters"

The placeholders I am aware of are:

  • {0} = Property Name
  • {1} = Max Length
  • {2} = Min Length

Much thanks to bloudraak for initially pointing this out.

What does enumerate() mean?

As other users have mentioned, enumerate is a generator that adds an incremental index next to each item of an iterable.

So if you have a list say l = ["test_1", "test_2", "test_3"], the list(enumerate(l)) will give you something like this: [(0, 'test_1'), (1, 'test_2'), (2, 'test_3')].

Now, when this is useful? A possible use case is when you want to iterate over items, and you want to skip a specific item that you only know its index in the list but not its value (because its value is not known at the time).

for index, value in enumerate(joint_values):
   if index == 3:
       continue

   # Do something with the other `value`

So your code reads better because you could also do a regular for loop with range but then to access the items you need to index them (i.e., joint_values[i]).

Although another user mentioned an implementation of enumerate using zip, I think a more pure (but slightly more complex) way without using itertools is the following:

def enumerate(l, start=0):
    return zip(range(start, len(l) + start), l)

Example:

l = ["test_1", "test_2", "test_3"]
enumerate(l)
enumerate(l, 10)

Output:

[(0, 'test_1'), (1, 'test_2'), (2, 'test_3')]

[(10, 'test_1'), (11, 'test_2'), (12, 'test_3')]

As mentioned in the comments, this approach with range will not work with arbitrary iterables as the original enumerate function does.

How do I use checkboxes in an IF-THEN statement in Excel VBA 2010?

If Sheets("Sheet1").OLEObjects("CheckBox1").Object.Value = True Then

I believe Tim is right. You have a Form Control. For that you have to use this

If ActiveSheet.Shapes("Check Box 1").ControlFormat.Value = 1 Then

Git Push error: refusing to update checked out branch

cd into the repo/directory that you're pushing into on the remote machine and enter

$ git config core.bare true

How to remove leading whitespace from each line in a file

Here you go:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt

Or:

user@host:~$ sed 's/^[\t ]*//g' < file-in.txt > file-out.txt

How to change lowercase chars to uppercase using the 'keyup' event?

Solution 1 (Elegant approach with great user experience)

HTML

<input id="inputID" class="uppercase" name="inputName" value="" />

CSS

.uppercase{
    text-transform: uppercase;
}

JS

$('#inputID').on('blur', function(){
    this.value = this.value.toUpperCase();
});

By using CSS text-transform: uppercase; you'll eliminate the animation of lower to uppercase as the user types into the field.

Use blur event to handle converting to uppercase. This happens behind the scene as CSS took care of the user's visually appealing masking.

Solution 2 (Great, but less elegant)

If you insist on using keyup, here it is...

$('#inputID').on('keyup', function(){
    var caretPos = this.selectionStart;
    this.value = this.value.toUpperCase();
    this.setSelectionRange(caretPos, caretPos);
});

User would notice the animation of lowercase to uppercase as they type into the field. It gets the job done.

Solution 3 (Just get the job done)

$('#inputID').on('keyup', function(){
    this.value = this.value.toUpperCase();
});

This method is most commonly suggested but I do not recommend.

The downside of this solution is you'll be annoying the user as the cursor's caret position keeps jumping to the end of the text after every key input. Unless you know your users will never encounter typos or they will always clear the text and retype every single time, this method works.

Undefined Reference to

g++ test.cpp LinearNode.cpp LinkedList.cpp -o test

How to convert .pem into .key?

If you're looking for a file to use in httpd-ssl.conf as a value for SSLCertificateKeyFile, a PEM file should work just fine.

See this SO question/answer for more details on the SSL options in that file.

Why is SSLCertificateKeyFile needed for Apache?

How can I revert a single file to a previous version?

Let's start with a qualitative description of what we want to do (much of this is said in Ben Straub's answer). We've made some number of commits, five of which changed a given file, and we want to revert the file to one of the previous versions. First of all, git doesn't keep version numbers for individual files. It just tracks content - a commit is essentially a snapshot of the work tree, along with some metadata (e.g. commit message). So, we have to know which commit has the version of the file we want. Once we know that, we'll need to make a new commit reverting the file to that state. (We can't just muck around with history, because we've already pushed this content, and editing history messes with everyone else.)

So let's start with finding the right commit. You can see the commits which have made modifications to given file(s) very easily:

git log path/to/file

If your commit messages aren't good enough, and you need to see what was done to the file in each commit, use the -p/--patch option:

git log -p path/to/file

Or, if you prefer the graphical view of gitk

gitk path/to/file

You can also do this once you've started gitk through the view menu; one of the options for a view is a list of paths to include.

Either way, you'll be able to find the SHA1 (hash) of the commit with the version of the file you want. Now, all you have to do is this:

# get the version of the file from the given commit
git checkout <commit> path/to/file
# and commit this modification
git commit

(The checkout command first reads the file into the index, then copies it into the work tree, so there's no need to use git add to add it to the index in preparation for committing.)

If your file may not have a simple history (e.g. renames and copies), see VonC's excellent comment. git can be directed to search more carefully for such things, at the expense of speed. If you're confident the history's simple, you needn't bother.

How do I change the default port (9000) that Play uses when I execute the "run" command?

For Play 2.2.x on Windows with a distributable tar file I created a file in the distributable root directory called: {PROJECT_NAME}_config.txt and added:

-Dhttp.port=8080

Where {PROJECT_NAME} should be replaced with the name of your project. Then started the {PROJECT_NAME}.bat script as usual in the bin\ directory.

Calculate percentage Javascript

Try:

const result = Math.round((data.expense / data.income) * 100)

How to change position of Toast in Android?

//A custom toast class where you can show custom or default toast as desired)

public class ToastMessage {
            private Context context;
            private static ToastMessage instance;

            /**
             * @param context
             */
            private ToastMessage(Context context) {
                this.context = context;
            }

            /**
             * @param context
             * @return
             */
            public synchronized static ToastMessage getInstance(Context context) {
                if (instance == null) {
                    instance = new ToastMessage(context);
                }
                return instance;
            }

            /**
             * @param message
             */
            public void showLongMessage(String message) {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }

            /**
             * @param message
             */
            public void showSmallMessage(String message) {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            }

            /**
             * The Toast displayed via this method will display it for short period of time
             *
             * @param message
             */
            public void showLongCustomToast(String message) {
                LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
                TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
                msgTv.setText(message);
                Toast toast = new Toast(context);
                toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();


            }

            /**
             * The toast displayed by this class will display it for long period of time
             *
             * @param message
             */
            public void showSmallCustomToast(String message) {

                LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
                TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
                msgTv.setText(message);
                Toast toast = new Toast(context);
                toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();
            }

        }

How to call Stored Procedure in a View?

I was able to call stored procedure in a view (SQL Server 2005).

CREATE FUNCTION [dbo].[dimMeasure] 
   RETURNS  TABLE  AS

    (
     SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost; Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2')
    )
RETURN
GO

Inside stored procedure we need to set:

set nocount on
SET FMTONLY OFF
CREATE VIEW [dbo].[dimMeasure]
AS

SELECT * FROM OPENROWSET('SQLNCLI', 'Server=localhost;Trusted_Connection=yes;', 'exec ceaw.dbo.sp_dimMeasure2')

GO

Set session variable in laravel

In Laravel 6.x

// Retrieve a piece of data from the session...
$value = session('key');

// Specifying a default value...
$value = session('key', 'default');

// Store a piece of data in the session...
session(['key' => 'value']);

https://laravel.com/docs/6.x/session

Failed to authenticate on SMTP server error using gmail

Nothing wrong with your method, it's a G-mail security issue.

  1. Login g-mail account settings.

  2. Enable 2-step verification.

  3. Generate app-password.

  4. Use new-generated password in place of your real g-mail password.

Don't forget to clear cache.

php artisan config:cache.
php artisan config:clear.

MAIL_DRIVER=smtp
MAIL_HOST=mailtrap.io
MAIL_PORT=587
[email protected]
MAIL_PASSWORD=generatedAppPassword
MAIL_ENCRYPTION=tls

How to increase dbms_output buffer?

Here you go:

DECLARE
BEGIN
  dbms_output.enable(NULL); -- Disables the limit of DBMS
  -- Your print here !
END;

Timeout a command in bash without unnecessary delay

I have a cron job that calls a php script and, some times, it get stuck on php script. This solution was perfect to me.

I use:

scripttimeout -t 60 /script.php

Assignment inside lambda expression in Python

There's no need to use a lambda, when you can remove all the null ones, and put one back if the input size changes:

input = [Object(name=""), Object(name="fake_name"), Object(name="")] 
output = [x for x in input if x.name]
if(len(input) != len(output)):
    output.append(Object(name=""))

How to parse JSON boolean value?

You can cast this value to a Boolean in a very simple manner: by comparing it with integer value 1, like this:

boolean multipleContacts = new Integer(1).equals(jsonObject.get("MultipleContacts"))

If it is a String, you could do this:

boolean multipleContacts = "1".equals(jsonObject.get("MultipleContacts"))

How to set editable true/false EditText in Android programmatically?

Since setEditable(false) is deprecated, use textView.setKeyListener(null); to make editText non-clickable.

Drop view if exists

DROP VIEW if exists {ViewName}
Go
CREATE View {ViewName} AS 
SELECT * from {TableName}  
Go

Error LNK2019: Unresolved External Symbol in Visual Studio

I was getting this error after adding the include files and linking the library. It was because the lib was built with non-unicode and my application was unicode. Matching them fixed it.

Uploading into folder in FTP?

The folder is part of the URL you set when you create request: "ftp://www.contoso.com/test.htm". If you use "ftp://www.contoso.com/wibble/test.htm" then the file will be uploaded to a folder named wibble.

You may need to first use a request with Method = WebRequestMethods.Ftp.MakeDirectory to make the wibble folder if it doesn't already exist.

Shorten string without cutting words in JavaScript

For what it's worth I wrote this to truncate to word boundary without leaving punctuation or whitespace at the end of the string:

_x000D_
_x000D_
function truncateStringToWord(str, length, addEllipsis)_x000D_
{_x000D_
    if(str.length <= length)_x000D_
    {_x000D_
        // provided string already short enough_x000D_
        return(str);_x000D_
    }_x000D_
_x000D_
    // cut string down but keep 1 extra character so we can check if a non-word character exists beyond the boundary_x000D_
    str = str.substr(0, length+1);_x000D_
_x000D_
    // cut any non-whitespace characters off the end of the string_x000D_
    if (/[^\s]+$/.test(str))_x000D_
    {_x000D_
        str = str.replace(/[^\s]+$/, "");_x000D_
    }_x000D_
_x000D_
    // cut any remaining non-word characters_x000D_
    str = str.replace(/[^\w]+$/, "");_x000D_
_x000D_
    var ellipsis = addEllipsis && str.length > 0 ? '&hellip;' : '';_x000D_
_x000D_
    return(str + ellipsis);_x000D_
}_x000D_
_x000D_
var testString = "hi stack overflow, how are you? Spare";_x000D_
var i = testString.length;_x000D_
_x000D_
document.write('<strong>Without ellipsis:</strong><br>');_x000D_
_x000D_
while(i > 0)_x000D_
{_x000D_
  document.write(i+': "'+ truncateStringToWord(testString, i) +'"<br>');_x000D_
  i--;_x000D_
}_x000D_
_x000D_
document.write('<strong>With ellipsis:</strong><br>');_x000D_
_x000D_
i = testString.length;_x000D_
while(i > 0)_x000D_
{_x000D_
  document.write(i+': "'+ truncateStringToWord(testString, i, true) +'"<br>');_x000D_
  i--;_x000D_
}
_x000D_
_x000D_
_x000D_

Calculating the difference between two Java date instances

Best thing to do is

(Date1-Date2)/86 400 000 

That number is the number of milliseconds in a day.

One date-other date gives you difference in milliseconds.

Collect the answer in a double variable.

How do you iterate through every file/directory recursively in standard C++?

If using the Win32 API you can use the FindFirstFile and FindNextFile functions.

http://msdn.microsoft.com/en-us/library/aa365200(VS.85).aspx

For recursive traversal of directories you must inspect each WIN32_FIND_DATA.dwFileAttributes to check if the FILE_ATTRIBUTE_DIRECTORY bit is set. If the bit is set then you can recursively call the function with that directory. Alternatively you can use a stack for providing the same effect of a recursive call but avoiding stack overflow for very long path trees.

#include <windows.h>
#include <string>
#include <vector>
#include <stack>
#include <iostream>

using namespace std;

bool ListFiles(wstring path, wstring mask, vector<wstring>& files) {
    HANDLE hFind = INVALID_HANDLE_VALUE;
    WIN32_FIND_DATA ffd;
    wstring spec;
    stack<wstring> directories;

    directories.push(path);
    files.clear();

    while (!directories.empty()) {
        path = directories.top();
        spec = path + L"\\" + mask;
        directories.pop();

        hFind = FindFirstFile(spec.c_str(), &ffd);
        if (hFind == INVALID_HANDLE_VALUE)  {
            return false;
        } 

        do {
            if (wcscmp(ffd.cFileName, L".") != 0 && 
                wcscmp(ffd.cFileName, L"..") != 0) {
                if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
                    directories.push(path + L"\\" + ffd.cFileName);
                }
                else {
                    files.push_back(path + L"\\" + ffd.cFileName);
                }
            }
        } while (FindNextFile(hFind, &ffd) != 0);

        if (GetLastError() != ERROR_NO_MORE_FILES) {
            FindClose(hFind);
            return false;
        }

        FindClose(hFind);
        hFind = INVALID_HANDLE_VALUE;
    }

    return true;
}

int main(int argc, char* argv[])
{
    vector<wstring> files;

    if (ListFiles(L"F:\\cvsrepos", L"*", files)) {
        for (vector<wstring>::iterator it = files.begin(); 
             it != files.end(); 
             ++it) {
            wcout << it->c_str() << endl;
        }
    }
    return 0;
}

convert string to number node.js

You do not have to install something.

parseInt(req.params.year, 10);

should work properly.

console.log(typeof parseInt(req.params.year)); // returns 'number'

What is your output, if you use parseInt? is it still a string?

MySQL fails on: mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"

In case someone lands here after making the same mistake I did:

  1. Switched to plugin="mysql_native_password" temporarily. Performed my tasks.
  2. Attempted to switch back to the "auth_socket" plugin, but incorrectly referenced it as plugin="auth_socket" which resulted in mysql "ERROR 1524 (HY000): Plugin 'auth_socket' is not loaded"
  3. Lacking a way to login to fix this mistake, I was forced to have to stop mysql and use mysql_safe to bypass authentication in order to switch to the appropriate plugin plugin="unix_socket"

Hopefully this saves someone some time if they receive the original poster's error message, but the true cause was flubbing the plugin name, not actually lacking the existence of the "auth_socket" plugin itself, which according to the MariaDB documentation:

In MariaDB 10.4.3 and later, the unix_socket authentication plugin is installed by default, and it is used by the 'root'@'localhost' user account by default.

How to increase number of threads in tomcat thread pool?

From Tomcat Documentation

maxConnections When this number has been reached, the server will accept, but not process, one further connection. once the limit has been reached, the operating system may still accept connections based on the acceptCount setting. (The maximum queue length for incoming connection requests when all possible request processing threads are in use. Any requests received when the queue is full will be refused. The default value is 100.) For BIO the default is the value of maxThreads unless an Executor is used in which case the default will be the value of maxThreads from the executor. For NIO and NIO2 the default is 10000. For APR/native, the default is 8192. Note that for APR/native on Windows, the configured value will be reduced to the highest multiple of 1024 that is less than or equal to maxConnections. This is done for performance reasons.

maxThreads
The maximum number of request processing threads to be created by this Connector, which therefore determines the maximum number of simultaneous requests that can be handled. If not specified, this attribute is set to 200. If an executor is associated with this connector, this attribute is ignored as the connector will execute tasks using the executor rather than an internal thread pool.

DateTime.Compare how to check if a date is less than 30 days old?

No, the Compare function will return either 1, 0, or -1. 0 when the two values are equal, -1 and 1 mean less than and greater than, I believe in that order, but I often mix them up.

How do I get a list of installed CPAN modules?

It's worth noting that perldoc perllocal will only report on modules installed via CPAN. If someone installs modules manually, it won't find them. Also, if you have multiple people installing modules and the perllocal.pod is under source control, people might resolve conflicts incorrectly and corrupt the list (this has happened here at work, for example).

Regrettably, the solution appears to be walking through @INC with File::Find or something similar. However, that doesn't just find the modules, it also finds related modules in a distribution. For example, it would report TAP::Harness and TAP::Parser in addition to the actual distribution name of Test::Harness (assuming you have version 3 or above). You could potentially match them up with distribution names and discard those names which don't match, but then you might be discarding locally built and installed modules.

I believe brian d foy's backpan indexing work is supposed to have code to hand it at .pm file and it will attempt to infer the distribution, but even this fails at times because what's in a package is not necessarily installed (see Devel::Cover::Inc for an example).

Converting RGB to grayscale/intensity

is all this really necessary, human perception and CRT vs LCD will vary, but the R G B intensity does not, Why not L = (R + G + B)/3 and set the new RGB to L, L, L?

How to get element by innerText

You can use jQuery :contains() Selector

var element = $( "a:contains('SearchingText')" );

How to compare 2 dataTables

Try to make use of linq to Dataset

(from b in table1.AsEnumerable()  
    select new { id = b.Field<int>("id")}).Except(
         from a in table2.AsEnumerable() 
             select new {id = a.Field<int>("id")})

Check this article : Comparing DataSets using LINQ

How can I get a process handle by its name in C++?

OpenProcess Function

From MSDN:

To open a handle to another local process and obtain full access rights, you must enable the SeDebugPrivilege privilege.

How to replace special characters in a string?

You can get unicode for that junk character from charactermap tool in window pc and add \u e.g. \u00a9 for copyright symbol. Now you can use that string with that particular junk caharacter, don't remove any junk character but replace with proper unicode.

javascript functions to show and hide divs

You can zip the two with something like this [like jQuery does]:

function toggleMyDiv() {
 if (document.getElementById("myDiv").style.display=="block"){
  document.getElementById("myDiv").style.display="none"
  }
 else{
  document.getElementById("myDiv").style.display="block";
 }
}

..and use the same function in the two buttons - or generally in the page for both functions.

Sending data back to the Main Activity in Android

In first activity u can send intent using startActivityForResult() and then get result from second activity after it finished using setResult.

MainActivity.class

public class MainActivity extends AppCompatActivity {

    private static final int SECOND_ACTIVITY_RESULT_CODE = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    // "Go to Second Activity" button click
    public void onButtonClick(View view) {

        // Start the SecondActivity
        Intent intent = new Intent(this, SecondActivity.class);
        // send intent for result 
        startActivityForResult(intent, SECOND_ACTIVITY_RESULT_CODE);
    }

    // This method is called when the second activity finishes
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        // check that it is the SecondActivity with an OK result
        if (requestCode == SECOND_ACTIVITY_RESULT_CODE) {
            if (resultCode == RESULT_OK) {

                // get String data from Intent
                String returnString = data.getStringExtra("keyName");

                // set text view with string
                TextView textView = (TextView) findViewById(R.id.textView);
                textView.setText(returnString);
            }
        }
    }
}

SecondActivity.class

public class SecondActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_second);
    }

    // "Send text back" button click
    public void onButtonClick(View view) {

        // get the text from the EditText
        EditText editText = (EditText) findViewById(R.id.editText);
        String stringToPassBack = editText.getText().toString();

        // put the String to pass back into an Intent and close this activity
        Intent intent = new Intent();
        intent.putExtra("keyName", stringToPassBack);
        setResult(RESULT_OK, intent);
        finish();
    }
}

INSERT INTO @TABLE EXEC @query with SQL Server 2000

The documentation is misleading.
I have the following code running in production

DECLARE @table TABLE (UserID varchar(100))
DECLARE @sql varchar(1000)
SET @sql = 'spSelUserIDList'
/* Will also work
   SET @sql = 'SELECT UserID FROM UserTable'
*/

INSERT INTO @table
EXEC(@sql)

SELECT * FROM @table

delete all record from table in mysql

It’s because you tried to update a table without a WHERE that uses a KEY column.

The quick fix is to add SET SQL_SAFE_UPDATES=0; before your query :

SET SQL_SAFE_UPDATES=0; 

Or

close the safe update mode. Edit -> Preferences -> SQL Editor -> SQL Editor remove Forbid UPDATE and DELETE statements without a WHERE clause (safe updates) .

BTW you can use TRUNCATE TABLE tablename; to delete all the records .

groovy: safely find a key in a map and return its value

def mymap = [name:"Gromit", id:1234]
def x = mymap.find{ it.key == "likes" }?.value
if(x)
    println "x value: ${x}"

println x.getClass().name

?. checks for null and does not create an exception in Groovy. If the key does not exist, the result will be a org.codehaus.groovy.runtime.NullObject.

How to convert a double to long without casting?

Assuming you're happy with truncating towards zero, just cast:

double d = 1234.56;
long x = (long) d; // x = 1234

This will be faster than going via the wrapper classes - and more importantly, it's more readable. Now, if you need rounding other than "always towards zero" you'll need slightly more complicated code.

How to deal with SettingWithCopyWarning in Pandas

This should work:

quote_df.loc[:,'TVol'] = quote_df['TVol']/TVOL_SCALE

jQuery get selected option value (not the text, but the attribute 'value')

I just wanted to share my experience

For me,

$('#selectorId').val()

returned null.

I had to use

$('#selectorId option:selected').val()

How to get substring from string in c#?

Here is example of getting substring from 14 character to end of string. You can modify it to fit your needs

string text = "Retrieves a substring from this instance. The substring starts at a specified character position.";
//get substring where 14 is start index
string substring = text.Substring(14);

jQuery: Handle fallback for failed AJAX Request

Yes, it's built in to jQuery. See the docs at jquery documentation.

ajaxError may be what you want.

How to create a stacked bar chart for my DataFrame using seaborn?

You could use pandas plot as @Bharath suggest:

import seaborn as sns
sns.set()
df.set_index('App').T.plot(kind='bar', stacked=True)

Output:

enter image description here

Updated:

from matplotlib.colors import ListedColormap df.set_index('App')\ .reindex_axis(df.set_index('App').sum().sort_values().index, axis=1)\ .T.plot(kind='bar', stacked=True, colormap=ListedColormap(sns.color_palette("GnBu", 10)), figsize=(12,6))

Updated Pandas 0.21.0+ reindex_axis is deprecated, use reindex

from matplotlib.colors import ListedColormap

df.set_index('App')\
  .reindex(df.set_index('App').sum().sort_values().index, axis=1)\
  .T.plot(kind='bar', stacked=True,
          colormap=ListedColormap(sns.color_palette("GnBu", 10)), 
          figsize=(12,6))

Output:

enter image description here

intelliJ IDEA 13 error: please select Android SDK

I have same problem once.I solved this by File->Open->other project,then switch this project by this way.

How can I determine whether a specific file is open in Windows?

If you right-click on your "Computer" (or "My Computer") icon and select "Manage" from the pop-up menu, that'll take you to the Computer Management console.

In there, under System Tools\Shared Folders, you'll find "Open Files". This is probably close to what you want, but if the file is on a network share then you'd need to do the same thing on the server on which the file lives.

Byte[] to ASCII

Encoding.GetString Method (Byte[]) convert bytes to a string.

When overridden in a derived class, decodes all the bytes in the specified byte array into a string.

Namespace: System.Text
Assembly: mscorlib (in mscorlib.dll)

Syntax

public virtual string GetString(byte[] bytes)

Parameters

bytes
    Type: System.Byte[]
    The byte array containing the sequence of bytes to decode.

Return Value

Type: System.String
A String containing the results of decoding the specified sequence of bytes.

Exceptions

ArgumentException        - The byte array contains invalid Unicode code points.
ArgumentNullException    - bytes is null.
DecoderFallbackException - A fallback occurred (see Character Encoding in the .NET Framework for complete explanation) or DecoderFallback is set to DecoderExceptionFallback.

Remarks

If the data to be converted is available only in sequential blocks (such as data read from a stream) or if the amount of data is so large that it needs to be divided into smaller blocks, the application should use the Decoder or the Encoder provided by the GetDecoder method or the GetEncoder method, respectively, of a derived class.

See the Remarks under Encoding.GetChars for more discussion of decoding techniques and considerations.

Call of overloaded function is ambiguous

The literal 0 has two meanings in C++.
On the one hand, it is an integer with the value 0.
On the other hand, it is a null-pointer constant.

As your setval function can accept either an int or a char*, the compiler can not decide which overload you meant.

The easiest solution is to just cast the 0 to the right type.
Another option is to ensure the int overload is preferred, for example by making the other one a template:

class huge
{
 private:
  unsigned char data[BYTES];
 public:
  void setval(unsigned int);
  template <class T> void setval(const T *); // not implemented
  template <> void setval(const char*);
};

How to send a stacktrace to log4j?

You pass the exception directly to the logger, e.g.

try {
   ...
} catch (Exception e) {
    log.error( "failed!", e );
}

It's up to log4j to render the stack trace.

Mutex example / tutorial?

The function pthread_mutex_lock() either acquires the mutex for the calling thread or blocks the thread until the mutex can be acquired. The related pthread_mutex_unlock() releases the mutex.

Think of the mutex as a queue; every thread that attempts to acquire the mutex will be placed on the end of the queue. When a thread releases the mutex, the next thread in the queue comes off and is now running.

A critical section refers to a region of code where non-determinism is possible. Often this because multiple threads are attempting to access a shared variable. The critical section is not safe until some sort of synchronization is in place. A mutex lock is one form of synchronization.

Stacked Bar Plot in R

The dataset:

dat <- read.table(text = "A   B   C   D   E   F    G
1 480 780 431 295 670 360  190
2 720 350 377 255 340 615  345
3 460 480 179 560  60 735 1260
4 220 240 876 789 820 100   75", header = TRUE)

Now you can convert the data frame into a matrix and use the barplot function.

barplot(as.matrix(dat))

enter image description here

Calculate number of hours between 2 dates in PHP

In addition to @fyrye's very helpful answer this is an okayish workaround for the mentioned bug (this one), that DatePeriod substracts one hour when entering summertime, but doesn't add one hour when leaving summertime (and thus Europe/Berlin's March has its correct 743 hours but October has 744 instead of 745 hours):

Counting the hours of a month (or any timespan), considering DST-transitions in both directions

function getMonthHours(string $year, string $month, \DateTimeZone $timezone): int
{
    // or whatever start and end \DateTimeInterface objects you like
    $start = new \DateTimeImmutable($year . '-' . $month . '-01 00:00:00', $timezone);
    $end = new \DateTimeImmutable((new \DateTimeImmutable($year . '-' . $month . '-01 23:59:59', $timezone))->format('Y-m-t H:i:s'), $timezone);
    
    // count the hours just utilizing \DatePeriod, \DateInterval and iterator_count, hell yeah!
    $hours = iterator_count(new \DatePeriod($start, new \DateInterval('PT1H'), $end));
    
    // find transitions and check, if there is one that leads to a positive offset
    // that isn't added by \DatePeriod
    // this is the workaround for https://bugs.php.net/bug.php?id=75685
    $transitions = $timezone->getTransitions((int)$start->format('U'), (int)$end->format('U'));
    if (2 === count($transitions) && $transitions[0]['offset'] - $transitions[1]['offset'] > 0) {
        $hours += (round(($transitions[0]['offset'] - $transitions[1]['offset'])/3600));
    }
    
    return $hours;
}

$myTimezoneWithDST = new \DateTimeZone('Europe/Berlin');
var_dump(getMonthHours('2020', '01', $myTimezoneWithDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithDST)); // 743
var_dump(getMonthHours('2020', '10', $myTimezoneWithDST)); // 745, finally!

$myTimezoneWithoutDST = new \DateTimeZone('UTC');
var_dump(getMonthHours('2020', '01', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '03', $myTimezoneWithoutDST)); // 744
var_dump(getMonthHours('2020', '10', $myTimezoneWithoutDST)); // 744

P.S. If you check a (longer) timespan, which leads to more than those two transitions, my workaround won't touch the counted hours to reduce the potential of funny side effects. In such cases, a more complicated solution must be implemented. One could iterate over all found transitions and compare the current with the last and check if it is one with DST true->false.

Can't install nuget package because of "Failed to initialize the PowerShell host"

I had the same problem after upgrading to Windows 10.

This worked for me

  1. Close Visual Studio
  2. Run Powershell as admin
  3. Run Set-ExecutionPolicy Unrestricted
  4. Run Visual studio as admin
  5. Clean the project and add the nuget package

If it still doesn't work try editing devenv.exe.config

Visual Studio 2013: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\12.0

Visual Studio 2015: C:\Users\<UserName>\AppData\Local\Microsoft\VisualStudio\14.0

Add the following

    <dependentAssembly>
        <assemblyIdentity name="System.Management.Automation" publicKeyToken="31bf3856ad364e35" />
        <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Utility" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.ConsoleHost" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Management" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Security" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>
    <dependentAssembly>
      <assemblyIdentity name="Microsoft.PowerShell.Commands.Diagnostics" publicKeyToken="31bf3856ad364e35" />
      <publisherPolicy apply="no" />
    </dependentAssembly>

How can I create a Java method that accepts a variable number of arguments?

Take a look at the Java guide on varargs.

You can create a method as shown below. Simply call System.out.printf instead of System.out.println(String.format(....

public static void print(String format, Object... args) {
    System.out.printf(format, args);
}

Alternatively, you can just use a static import if you want to type as little as possible. Then you don't have to create your own method:

import static java.lang.System.out;

out.printf("Numer of apples: %d", 10);

Displaying a webcam feed using OpenCV and Python

change import cv to import cv2.cv as cv See also the post here.

"Incorrect string value" when trying to insert UTF-8 into MySQL via JDBC?

Its mostly caused due to some unicode characters. In my case it was the Rupee currency symbol.

To quickly fix this, I had to spot the character causing this error. I copy pasted the entire text in a text editor like vi and replaced the troubling character with a text one.

How to use SQL Select statement with IF EXISTS sub query?

SELECT Id, 'TRUE' AS NewFiled FROM TABEL1
INTERSECT
SELECT Id, 'TRUE' AS NewFiled FROM TABEL2
UNION
SELECT Id, 'FALSE' AS NewFiled FROM TABEL1
EXCEPT
SELECT Id, 'FALSE' AS NewFiled FROM TABEL2;

When to use async false and async true in ajax function in jquery

It's not relative to performance...

You set async to false, when you need that ajax request to be completed before the browser passes to other codes:

<script>
    // ...
    $.ajax(... async: false ...); // Hey browser! first complete this request, 
                                  // then go for other codes

    $.ajax(...); // Executed after the completion of the previous async:false request.
</script>

How to cancel a pull request on github?

Go to conversation tab then come down there is one "close pull request" button is there use that button to close pull request, Take ref of attached image

variable is not declared it may be inaccessible due to its protection level

I have found that you have to comment out the namespace wrapping the the class at time when moving between version of Visual Studio:

'Namespace FormsAuth

'End Namespace

and at other times, I have to uncomment the namespace.

This happened to me several times when other developers edited the same solution using a different version of VS and/or I moved (copied) the solution to another location

instantiate a class from a variable in PHP?

How to pass dynamic constructor parameters too

If you want to pass dynamic constructor parameters to the class, you can use this code:

$reflectionClass = new ReflectionClass($className);

$module = $reflectionClass->newInstanceArgs($arrayOfConstructorParameters);

More information on dynamic classes and parameters

PHP >= 5.6

As of PHP 5.6 you can simplify this even more by using Argument Unpacking:

// The "..." is part of the language and indicates an argument array to unpack.
$module = new $className(...$arrayOfConstructorParameters);

Thanks to DisgruntledGoat for pointing that out.

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

Researching this topic myself and having read the answers I recommend using the path.py library since it provides a context manager for changing the current working directory.

You then have something like

import path
if path.Path('../lib').isdir():
    with path.Path('..'):
        import lib

Although, you might just omit the isdir statement.

Here I'll add print statements to make it easy to follow what's happening

import path
import pandas

print(path.Path.getcwd())
print(path.Path('../lib').isdir())
if path.Path('../lib').isdir():
    with path.Path('..'):
        print(path.Path.getcwd())
        import lib
        print('Success!')
print(path.Path.getcwd())

which outputs in this example (where lib is at /home/jovyan/shared/notebooks/by-team/data-vis/demos/lib):

/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart
/home/jovyan/shared/notebooks/by-team/data-vis/demos
/home/jovyan/shared/notebooks/by-team/data-vis/demos/custom-chart

Since the solution uses a context manager, you are guaranteed to go back to your previous working directory, no matter what state your kernel was in before the cell and no matter what exceptions are thrown by importing your library code.

How to download and save an image in Android

I have a simple solution which is working perfectly. The code is not mine, I found it on this link. Here are the steps to follow:

1. Before downloading the image, let’s write a method for saving bitmap into an image file in the internal storage in android. It needs a context, better to use the pass in the application context by getApplicationContext(). This method can be dumped into your Activity class or other util classes.

public void saveImage(Context context, Bitmap b, String imageName) 
{
    FileOutputStream foStream;
    try 
    {
        foStream = context.openFileOutput(imageName, Context.MODE_PRIVATE);
        b.compress(Bitmap.CompressFormat.PNG, 100, foStream);
        foStream.close();
    } 
    catch (Exception e) 
    {
        Log.d("saveImage", "Exception 2, Something went wrong!");
        e.printStackTrace();
    }
}

2. Now we have a method to save bitmap into an image file in andorid, let’s write the AsyncTask for downloading images by url. This private class need to be placed in your Activity class as a subclass. After the image is downloaded, in the onPostExecute method, it calls the saveImage method defined above to save the image. Note, the image name is hardcoded as “my_image.png”.

private class DownloadImage extends AsyncTask<String, Void, Bitmap> {
    private String TAG = "DownloadImage";
    private Bitmap downloadImageBitmap(String sUrl) {
        Bitmap bitmap = null;
        try {
            InputStream inputStream = new URL(sUrl).openStream();   // Download Image from URL
            bitmap = BitmapFactory.decodeStream(inputStream);       // Decode Bitmap
            inputStream.close();
        } catch (Exception e) {
            Log.d(TAG, "Exception 1, Something went wrong!");
            e.printStackTrace();
        }
        return bitmap;
    }

    @Override
    protected Bitmap doInBackground(String... params) {
        return downloadImageBitmap(params[0]);
    }

    protected void onPostExecute(Bitmap result) {
        saveImage(getApplicationContext(), result, "my_image.png");
    }
}

3. The AsyncTask for downloading the image is defined, but we need to execute it in order to run that AsyncTask. To do so, write this line in your onCreate method in your Activity class, or in an onClick method of a button or other places you see fit.

new DownloadImage().execute("http://developer.android.com/images/activity_lifecycle.png");

The image should be saved in /data/data/your.app.packagename/files/my_image.jpeg, check this post for accessing this directory from your device.

IMO this solves the issue! If you want further steps such as load the image you can follow these extra steps:

4. After the image is downloaded, we need a way to load the image bitmap from the internal storage, so we can use it. Let’s write the method for loading the image bitmap. This method takes two paramethers, a context and an image file name, without the full path, the context.openFileInput(imageName) will look up the file at the save directory when this file name was saved in the above saveImage method.

public Bitmap loadImageBitmap(Context context, String imageName) {
    Bitmap bitmap = null;
    FileInputStream fiStream;
    try {
        fiStream    = context.openFileInput(imageName);
        bitmap      = BitmapFactory.decodeStream(fiStream);
        fiStream.close();
    } catch (Exception e) {
        Log.d("saveImage", "Exception 3, Something went wrong!");
        e.printStackTrace();
    }
    return bitmap;
}

5. Now we have everything we needed for setting the image of an ImageView or any other Views that you like to use the image on. When we save the image, we hardcoded the image name as “my_image.jpeg”, now we can pass this image name to the above loadImageBitmap method to get the bitmap and set it to an ImageView.

someImageView.setImageBitmap(loadImageBitmap(getApplicationContext(), "my_image.jpeg"));

6. To get the image full path by image name.

File file            = getApplicationContext().getFileStreamPath("my_image.jpeg");
String imageFullPath = file.getAbsolutePath();

7. Check if the image file exists.

File file =

getApplicationContext().getFileStreamPath("my_image.jpeg");
if (file.exists()) Log.d("file", "my_image.jpeg exists!");
  1. To delete the image file.

    File file = getApplicationContext().getFileStreamPath("my_image.jpeg"); if (file.delete()) Log.d("file", "my_image.jpeg deleted!");

R - test if first occurrence of string1 is followed by string2

I think it's worth answering the generic question "R - test if string contains string" here.

For that, use the grep function.

# example:
> if(length(grep("ab","aacd"))>0) print("found") else print("Not found")
[1] "Not found"
> if(length(grep("ab","abcd"))>0) print("found") else print("Not found")
[1] "found"

What does "res.render" do, and what does the html file look like?

Renders a view and sends the rendered HTML string to the client.

res.render('index');

Or

res.render('index', function(err, html) {
  if(err) {...}
  res.send(html);
});

DOCS HERE: https://expressjs.com/en/api.html#res.render

Compiling Java 7 code via Maven

You might be specifying a wrong version of java. java -version(in your terminal) to check the version of java you are using. Go to maven-compile-plugin for the latest maven compiler version Your plugin may appear like this if you are using java 6 and the latest version of maven compiler plugin is 3.1

<plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.1</version>
            <configuration>
                <source>1.6</source>
                <target>1.6</target>
            </configuration>
        </plugin>

Using DISTINCT along with GROUP BY in SQL Server

Use DISTINCT to remove duplicate GROUPING SETS from the GROUP BY clause

In a completely silly example using GROUPING SETS() in general (or the special grouping sets ROLLUP() or CUBE() in particular), you could use DISTINCT in order to remove the duplicate values produced by the grouping sets again:

SELECT DISTINCT actors
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY CUBE(actors, actors)

With DISTINCT:

actors
------
NULL
a
b

Without DISTINCT:

actors
------
a
b
NULL
a
b
a
b

But why, apart from making an academic point, would you do that?

Use DISTINCT to find unique aggregate function values

In a less far-fetched example, you might be interested in the DISTINCT aggregated values, such as, how many different duplicate numbers of actors are there?

SELECT DISTINCT COUNT(*)
FROM (VALUES('a'), ('a'), ('b'), ('b')) t(actors)
GROUP BY actors

Answer:

count
-----
2

Use DISTINCT to remove duplicates with more than one GROUP BY column

Another case, of course, is this one:

SELECT DISTINCT actors, COUNT(*)
FROM (VALUES('a', 1), ('a', 1), ('b', 1), ('b', 2)) t(actors, id)
GROUP BY actors, id

With DISTINCT:

actors  count
-------------
a       2
b       1

Without DISTINCT:

actors  count
-------------
a       2
b       1
b       1

For more details, I've written some blog posts, e.g. about GROUPING SETS and how they influence the GROUP BY operation, or about the logical order of SQL operations (as opposed to the lexical order of operations).

With arrays, why is it the case that a[5] == 5[a]?

A little bit of history now. Among other languages, BCPL had a fairly major influence on C's early development. If you declared an array in BCPL with something like:

let V = vec 10

that actually allocated 11 words of memory, not 10. Typically V was the first, and contained the address of the immediately following word. So unlike C, naming V went to that location and picked up the address of the zeroeth element of the array. Therefore array indirection in BCPL, expressed as

let J = V!5

really did have to do J = !(V + 5) (using BCPL syntax) since it was necessary to fetch V to get the base address of the array. Thus V!5 and 5!V were synonymous. As an anecdotal observation, WAFL (Warwick Functional Language) was written in BCPL, and to the best of my memory tended to use the latter syntax rather than the former for accessing the nodes used as data storage. Granted this is from somewhere between 35 and 40 years ago, so my memory is a little rusty. :)

The innovation of dispensing with the extra word of storage and having the compiler insert the base address of the array when it was named came later. According to the C history paper this happened at about the time structures were added to C.

Note that ! in BCPL was both a unary prefix operator and a binary infix operator, in both cases doing indirection. just that the binary form included an addition of the two operands before doing the indirection. Given the word oriented nature of BCPL (and B) this actually made a lot of sense. The restriction of "pointer and integer" was made necessary in C when it gained data types, and sizeof became a thing.

PostgreSQL: How to make "case-insensitive" query

You could also use POSIX regular expressions, like

SELECT id FROM groups where name ~* 'administrator'

SELECT 'asd' ~* 'AsD' returns t

How can you profile a Python script?

There's a lot of great answers but they either use command line or some external program for profiling and/or sorting the results.

I really missed some way I could use in my IDE (eclipse-PyDev) without touching the command line or installing anything. So here it is.

Profiling without command line

def count():
    from math import sqrt
    for x in range(10**5):
        sqrt(x)

if __name__ == '__main__':
    import cProfile, pstats
    cProfile.run("count()", "{}.profile".format(__file__))
    s = pstats.Stats("{}.profile".format(__file__))
    s.strip_dirs()
    s.sort_stats("time").print_stats(10)

See docs or other answers for more info.

How to send only one UDP packet with netcat?

I did not find the -q1 option on my netcat. Instead I used the -w1 option. Below is the bash script I did to send an udp packet to any host and port:

#!/bin/bash

def_host=localhost
def_port=43211

HOST=${2:-$def_host}
PORT=${3:-$def_port}

echo -n "$1" | nc -4u -w1 $HOST $PORT

error: ORA-65096: invalid common user or role name in oracle

I just installed oracle11g

ORA-65096: invalid common user or role name in oracle

No, you have installed Oracle 12c. That error could only be on 12c, and cannot be on 11g.

Always check your database version up to 4 decimal places:

SELECT banner FROM v$version WHERE ROWNUM = 1;

Oracle 12c multitenant container database has:

  • a root container(CDB)
  • and/or zero, one or many pluggable databases(PDB).

You must have created the database as a container database. While, you are trying to create user in the container, i.e. CDB$ROOT, however, you should create the user in the PLUGGABLE database.

You are not supposed to create application-related objects in the container, the container holds the metadata for the pluggable databases. You should use the pluggable database for you general database operations. Else, do not create it as container, and not use multi-tenancy. However, 12cR2 onward you cannot create a non-container database anyway.

And most probably, the sample schemas might have been already installed, you just need to unlock them in the pluggable database.

For example, if you created pluggable database as pdborcl:

sqlplus SYS/password@PDBORCL AS SYSDBA

SQL> ALTER USER scott ACCOUNT UNLOCK IDENTIFIED BY tiger;

sqlplus scott/tiger@pdborcl

SQL> show user;
USER is "SCOTT"

To show the PDBs and connect to a pluggable database from root container:

SQL> show con_name

CON_NAME
------------------------------
CDB$ROOT

SQL> show pdbs

    CON_ID CON_NAME                       OPEN MODE  RESTRICTED
---------- ------------------------------ ---------- ----------
         2 PDB$SEED                       READ ONLY  NO
         3 ORCLPDB                        READ WRITE NO

SQL> alter session set container = ORCLPDB;

Session altered.

SQL> show con_name;

CON_NAME
------------------------------
ORCLPDB

I suggest read, Oracle 12c Post Installation Mandatory Steps


Note: Answers suggesting to use the _ORACLE_SCRIPT hidden parameter to set to true is dangerous in a production system and might also invalidate your support contract. Beware, without consulting Oracle support DO NOT use hidden parameters.

Can not find the tag library descriptor of springframework

I know it's an old question, but the tag library http://www.springframework.org/tags is provided by spring-webmvc package. With Maven it can be added to the project with the following lines to be added in the pom.xml

<properties>
    <spring.version>3.0.6.RELEASE</spring.version>
</properties>

<dependencies>

    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>${spring.version}</version>
    </dependency>

Without Maven, just add that jar to your classpath. In any case it's not necessary to refer the tld file directly, it will be automatically found.