Programs & Examples On #Fpdi

A PHP class which allows to read pages from existing PDF and generate new files based on FPDF.

undefined reference to 'vtable for class' constructor

You're declaring a virtual function and not defining it:

virtual void calculateCredits();

Either define it or declare it as:

virtual void calculateCredits() = 0;

Or simply:

virtual void calculateCredits() { };

Read more about vftable: http://en.wikipedia.org/wiki/Virtual_method_table

Slick.js: Get current and total slides (ie. 3/5)

You need to bind init before initialization.

$('.slider-for').on('init', function(event, slick){
        $(this).append('<div class="slider-count"><p><span id="current">1</span> von <span id="total">'+slick.slideCount+'</span></p></div>');
    });
    $('.slider-for').slick({
      slidesToShow: 1,
      slidesToScroll: 1,
      arrows: true,
      fade: true
    });
    $('.slider-for')
        .on('afterChange', function(event, slick, currentSlide, nextSlide){
            // finally let's do this after changing slides
            $('.slider-count #current').html(currentSlide+1);
        });

Redirecting a page using Javascript, like PHP's Header->Location

You application of js and php in totally invalid.

You have to understand a fact that JS runs on clientside, once the page loads it does not care, whether the page was a php page or jsp or asp. It executes of DOM and is related to it only.

However you can do something like this

var newLocation = "<?php echo $newlocation; ?>";
window.location = newLocation;

You see, by the time the script is loaded, the above code renders into different form, something like this

var newLocation = "your/redirecting/page.php";
window.location = newLocation;

Like above, there are many possibilities of php and js fusions and one you are doing is not one of them.

Import numpy on pycharm

I have encountered problem installing numpy package to pycharm and finally figured out. I hope it would be helpful for someone having the same problem in installing numpy and other packages on pycharm.

Pycharm Setting : Pycharm Setting

Go to File => Setting => Project => Project Interpreter. On this window select the appropriate project interpreter. After this, a list of packages under the selected project interpreter will be shown. From the list select pip and check if the version column and the latest version column are the same. If different upgrade the version to the latest version by selecting the pip and using the upward triangle sign on the right side of the lists. Once the upgrading completed successfully, you can now add new packages from the plus sign.

enter image description here

I hope this would be clear and useful for someone.

Removing Conda environment

Environments created with the --prefix or -p flag must be removed with the -p flag (not -n).

For example: conda remove -p </filepath/myenvironment> --all, in which </filepath/myenvironment> is substituted with a complete or relative path to the environment.

Java equivalent to C# extension methods

The XTend language — which is a super-set of Java, and compiles to Java source code1 — supports this.

Convert Iterator to ArrayList

Better use a library like Guava:

import com.google.common.collect.Lists;

Iterator<Element> myIterator = ... //some iterator
List<Element> myList = Lists.newArrayList(myIterator);

Another Guava example:

ImmutableList.copyOf(myIterator);

or Apache Commons Collections:

import org.apache.commons.collections.IteratorUtils;

Iterator<Element> myIterator = ...//some iterator

List<Element> myList = IteratorUtils.toList(myIterator);       

Global variables in Java

Generally Global variable (I assume you are comparing it with C,Cpp) define as public static final

like

class GlobalConstant{
    public static final String CODE  = "cd";
}

ENUMs are also useful in such scenario :

For Example Calendar.JANUARY)

How do I format a Microsoft JSON date?

You can use this to get a date from JSON:

var date = eval(jsonDate.replace(/\/Date\((\d+)\)\//gi, "new Date($1)"));

And then you can use a JavaScript Date Format script (1.2 KB when minified and gzipped) to display it as you want.

Adding a tooltip to an input box

Apart from HTML 5 data-tip You can use css also for making a totally customizable tooltip to be used anywhere throughout your markup.

_x000D_
_x000D_
/* ToolTip classses */ _x000D_
.tooltip {_x000D_
    display: inline-block;    _x000D_
}_x000D_
.tooltip .tooltiptext {_x000D_
    margin-left:9px;_x000D_
    width : 320px;_x000D_
    visibility: hidden;_x000D_
    background-color: #FFF;_x000D_
    border-radius:4px;_x000D_
    border: 1px solid #aeaeae;_x000D_
    position: absolute;_x000D_
    z-index: 1;_x000D_
    padding: 5px;_x000D_
    margin-top : -15px; _x000D_
    opacity: 0;_x000D_
    transition: opacity 0.5s;_x000D_
}_x000D_
.tooltip .tooltiptext::after {_x000D_
    content: " ";_x000D_
    position: absolute;_x000D_
    top: 5%;_x000D_
    right: 100%;  _x000D_
    margin-top: -5px;_x000D_
    border-width: 5px;_x000D_
    border-style: solid;_x000D_
    border-color: transparent #aeaeae transparent transparent;_x000D_
}_x000D_
_x000D_
_x000D_
.tooltip:hover .tooltiptext {_x000D_
    visibility: visible;_x000D_
    opacity: 1;_x000D_
}
_x000D_
<div class="tooltip">_x000D_
  <input type="text" />_x000D_
  <span class="tooltiptext">_x000D_
Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.  </span>_x000D_
</div>
_x000D_
_x000D_
_x000D_

php Replacing multiple spaces with a single space

Use preg_replace() and instead of [ \t\n\r] use \s:

$output = preg_replace('!\s+!', ' ', $input);

From Regular Expression Basic Syntax Reference:

\d, \w and \s

Shorthand character classes matching digits, word characters (letters, digits, and underscores), and whitespace (spaces, tabs, and line breaks). Can be used inside and outside character classes.

How to solve the system.data.sqlclient.sqlexception (0x80131904) error

You also need to change the DataSource of the connection string. KELVIN-PC is the name of your local machine and the sql server is running on the default instance.

If you are sure the the server is running as the default instance, you can always use . in the DataSource, eg.

connectionString="Data Source=.;Initial Catalog=LMS;User ID=sa;Password=temperament"

otherwise, you need to specify the name of the instance of the server,

connectionString="Data Source=.\INSTANCENAME;Initial Catalog=LMS;User ID=sa;Password=temperament"

How do you check whether a number is divisible by another number (Python)?

a = 1400
a1 = 5
a2 = 3

b= str(a/a1)
b1 = str(a/a2)
c =b[(len(b)-2):len(b)]
c1 =b[(len(b1)-2):len(b1)]
if c == ".0":
    print("yeah for 5!")
if c1 == ".0":
    print("yeah for 3!")

Best way to get value from Collection by index

It would be just as convenient to simply convert your collection into a list whenever it updates. But if you are initializing, this will suffice:

for(String i : collectionlist){
    arraylist.add(i);
    whateverIntID = arraylist.indexOf(i);
}

Be open-minded.

Get random item from array

echo $items[array_rand($items)];

array_rand()

How to embed a Facebook page's feed into my website

Correct me if I am wrong, but it seems that Facebook deprecated the Activity Feed plugin. Additionally there does not seem to be any substitute plugin for activity anymore.

Here is the link: https://developers.facebook.com/docs/plugins/activity

YouTube URL in Video Tag

This will give you the answer you need. The easiest way to do it is with the youTube-provided methods. How to Embed Youtube Videos into HTML5 <video> Tag?

How do you determine the size of a file in C?

I have a function that works well with only stdio.h. I like it a lot and it works very well and is pretty concise:

size_t fsize(FILE *File) {
    size_t FSZ;
    fseek(File, 0, 2);
    FSZ = ftell(File);
    rewind(File);
    return FSZ;
}

How to get the selected date of a MonthCalendar control in C#

I just noticed that if you do:

monthCalendar1.SelectionRange.Start.ToShortDateString() 

you will get only the date (e.g. 1/25/2014) from a MonthCalendar control.

It's opposite to:

monthCalendar1.SelectionRange.Start.ToString()

//The OUTPUT will be (e.g. 1/25/2014 12:00:00 AM)

Because these MonthCalendar properties are of type DateTime. See the msdn and the methods available to convert to a String representation. Also this may help to convert from a String to a DateTime object where applicable.

What do >> and << mean in Python?

12 << 2

48

Actual binary value of 12 is "00 1100" when we execute the above statement Left shift ( 2 places shifted left) returns the value 48 its binary value is "11 0000".

48 >> 2

12

The binary value of 48 is "11 0000", after executing above statement Right shift ( 2 places shifted right) returns the value 12 its binary value is "00 1100".

How to float a div over Google Maps?

absolute positioning is evil... this solution doesn't take into account window size. If you resize the browser window, your div will be out of place!

How to exclude a directory in find . command

-prune definitely works and is the best answer because it prevents descending into the dir that you want to exclude. -not -path which still searches the excluded dir, it just doesn't print the result, which could be an issue if the excluded dir is mounted network volume or you don't permissions.

The tricky part is that find is very particular about the order of the arguments, so if you don't get them just right, your command may not work. The order of arguments is generally as such:

find {path} {options} {action}

{path}: Put all the path related arguments first, like . -path './dir1' -prune -o

{options}: I have the most success when putting -name, -iname, etc as the last option in this group. E.g. -type f -iname '*.js'

{action}: You'll want to add -print when using -prune

Here's a working example:

# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js

# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print

# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print

'printf' with leading zeros in C

Your format specifier is incorrect. From the printf() man page on my machine:

0 A zero '0' character indicating that zero-padding should be used rather than blank-padding. A '-' overrides a '0' if both are used;

Field Width: An optional digit string specifying a field width; if the output string has fewer characters than the field width it will be blank-padded on the left (or right, if the left-adjustment indicator has been given) to make up the field width (note that a leading zero is a flag, but an embedded zero is part of a field width);

Precision: An optional period, '.', followed by an optional digit string giving a precision which specifies the number of digits to appear after the decimal point, for e and f formats, or the maximum number of characters to be printed from a string; if the digit string is missing, the precision is treated as zero;

For your case, your format would be %09.3f:

#include <stdio.h>

int main(int argc, char **argv)
{
  printf("%09.3f\n", 4917.24);
  return 0;
}

Output:

$ make testapp
cc     testapp.c   -o testapp
$ ./testapp 
04917.240

Note that this answer is conditional on your embedded system having a printf() implementation that is standard-compliant for these details - many embedded environments do not have such an implementation.

How to move/rename a file using an Ansible task on a remote system

This may seem like overkill, but if you want to avoid using the command module (which I do, because it using command is not idempotent) you can use a combination of copy and unarchive.

  1. Use tar to archive the file(s) you will need. If you think ahead this actually makes sense. You may want a series of files in a given directory. Create that directory with all of the files and archive them in a tar.
  2. Use the unarchive module. When you do that, along with the destination: and remote_src: keyword, you can place copy all of your files to a temporary folder to start with and then unpack them exactly where you want to.

Test method is inconclusive: Test wasn't run. Error?

In my case, I referenced 2 projects from my unittestproject. Both referenced projects used a dll with the same name, but with a different version.

I did not notice this in Visual Studio. I noticed the error in the Eventviewer.

To solve this, I used bindingRedirect in the app.config of the unittestproject to fix the dll-version.

Downloading jQuery UI CSS from Google's CDN

jQuery now has a CDN access:

code.jquery.com/ui/[version]/themes/[theme name]/jquery-ui.css


And to make this a little more easy, Here you go:

Polling the keyboard (detect a keypress) in python

If you combine time.sleep, threading.Thread, and sys.stdin.read you can easily wait for a specified amount of time for input and then continue, also this should be cross-platform compatible.

t = threading.Thread(target=sys.stdin.read(1) args=(1,))
t.start()
time.sleep(5)
t.join()

You could also place this into a function like so

def timed_getch(self, bytes=1, timeout=1):
    t = threading.Thread(target=sys.stdin.read, args=(bytes,))
    t.start()
    time.sleep(timeout)
    t.join()
    del t

Although this will not return anything so instead you should use the multiprocessing pool module you can find that here: how to get the return value from a thread in python?

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

I use pendulum:

import pendulum


d = pendulum.now("UTC").to_iso8601_string()
print(d)

>>> 2019-10-30T00:11:21.818265Z

What's the "Content-Length" field in HTTP header?

From here:

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

   Content-Length    = "Content-Length" ":" 1*DIGIT

An example is

   Content-Length: 3495

Applications SHOULD use this field to indicate the transfer-length of the message-body, unless this is prohibited by the rules in section 4.4.

Any Content-Length greater than or equal to zero is a valid value. Section 4.4 describes how to determine the length of a message-body if a Content-Length is not given.

Note that the meaning of this field is significantly different from the corresponding definition in MIME, where it is an optional field used within the "message/external-body" content-type. In HTTP, it SHOULD be sent whenever the message's length can be determined prior to being transferred, unless this is prohibited by the rules in section 4.4.

My interpretation is that this means the length "on the wire", i.e. the length of the *encoded" content

Log record changes in SQL server in an audit table

This is the code with two bug fixes. The first bug fix was mentioned by Royi Namir in the comment on the accepted answer to this question. The bug is described on StackOverflow at Bug in Trigger Code. The second one was found by @Fandango68 and fixes columns with multiples words for their names.

ALTER TRIGGER [dbo].[TR_person_AUDIT]
ON [dbo].[person]
FOR UPDATE
AS
           DECLARE @bit            INT,
                   @field          INT,
                   @maxfield       INT,
                   @char           INT,
                   @fieldname      VARCHAR(128),
                   @TableName      VARCHAR(128),
                   @PKCols         VARCHAR(1000),
                   @sql            VARCHAR(2000),
                   @UpdateDate     VARCHAR(21),
                   @UserName       VARCHAR(128),
                   @Type           CHAR(1),
                   @PKSelect       VARCHAR(1000)


           --You will need to change @TableName to match the table to be audited.
           -- Here we made GUESTS for your example.
           SELECT @TableName = 'PERSON'

           SELECT @UserName = SYSTEM_USER,
                  @UpdateDate = CONVERT(NVARCHAR(30), GETDATE(), 126)

           -- Action
           IF EXISTS (
                  SELECT *
                  FROM   INSERTED
              )
               IF EXISTS (
                      SELECT *
                      FROM   DELETED
                  )
                   SELECT @Type = 'U'
               ELSE
                   SELECT @Type = 'I'
           ELSE
               SELECT @Type = 'D'

           -- get list of columns
           SELECT * INTO #ins
           FROM   INSERTED

           SELECT * INTO #del
           FROM   DELETED

           -- Get primary key columns for full outer join
           SELECT @PKCols = COALESCE(@PKCols + ' and', ' on') 
                  + ' i.[' + c.COLUMN_NAME + '] = d.[' + c.COLUMN_NAME + ']'
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           -- Get primary key select for insert
           SELECT @PKSelect = COALESCE(@PKSelect + '+', '') 
                  + '''<[' + COLUMN_NAME 
                  + ']=''+convert(varchar(100),
           coalesce(i.[' + COLUMN_NAME + '],d.[' + COLUMN_NAME + ']))+''>'''
           FROM   INFORMATION_SCHEMA.TABLE_CONSTRAINTS pk,
                  INFORMATION_SCHEMA.KEY_COLUMN_USAGE c
           WHERE  pk.TABLE_NAME = @TableName
                  AND CONSTRAINT_TYPE = 'PRIMARY KEY'
                  AND c.TABLE_NAME = pk.TABLE_NAME
                  AND c.CONSTRAINT_NAME = pk.CONSTRAINT_NAME

           IF @PKCols IS NULL
           BEGIN
               RAISERROR('no PK on table %s', 16, -1, @TableName)

               RETURN
           END

           SELECT @field = 0,
                  -- @maxfield = MAX(COLUMN_NAME) 
                  @maxfield = -- FROM INFORMATION_SCHEMA.COLUMNS WHERE TABLE_NAME = @TableName


                  MAX(
                      COLUMNPROPERTY(
                          OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                          COLUMN_NAME,
                          'ColumnID'
                      )
                  )
           FROM   INFORMATION_SCHEMA.COLUMNS
           WHERE  TABLE_NAME = @TableName






           WHILE @field < @maxfield
           BEGIN
               SELECT @field = MIN(
                          COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          )
                      )
               FROM   INFORMATION_SCHEMA.COLUMNS
               WHERE  TABLE_NAME = @TableName
                      AND COLUMNPROPERTY(
                              OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                              COLUMN_NAME,
                              'ColumnID'
                          ) > @field

               SELECT @bit = (@field - 1)% 8 + 1

               SELECT @bit = POWER(2, @bit - 1)

               SELECT @char = ((@field - 1) / 8) + 1





               IF SUBSTRING(COLUMNS_UPDATED(), @char, 1) & @bit > 0
                  OR @Type IN ('I', 'D')
               BEGIN
                   SELECT @fieldname = COLUMN_NAME
                   FROM   INFORMATION_SCHEMA.COLUMNS
                   WHERE  TABLE_NAME = @TableName
                          AND COLUMNPROPERTY(
                                  OBJECT_ID(TABLE_SCHEMA + '.' + @TableName),
                                  COLUMN_NAME,
                                  'ColumnID'
                              ) = @field



                   SELECT @sql = 
                          '
           insert into Audit (    Type, 
           TableName, 
           PK, 
           FieldName, 
           OldValue, 
           NewValue, 
           UpdateDate, 
           UserName)
           select ''' + @Type + ''',''' 
                          + @TableName + ''',' + @PKSelect
                          + ',''' + @fieldname + ''''
                          + ',convert(varchar(1000),d.' + @fieldname + ')'
                          + ',convert(varchar(1000),i.' + @fieldname + ')'
                          + ',''' + @UpdateDate + ''''
                          + ',''' + @UserName + ''''
                          + ' from #ins i full outer join #del d'
                          + @PKCols
                          + ' where i.' + @fieldname + ' <> d.' + @fieldname 
                          + ' or (i.' + @fieldname + ' is null and  d.'
                          + @fieldname
                          + ' is not null)' 
                          + ' or (i.' + @fieldname + ' is not null and  d.' 
                          + @fieldname
                          + ' is null)' 



                   EXEC (@sql)
               END
           END

How to ignore deprecation warnings in Python

For python 3, just write below codes to ignore all warnings.

from warnings import filterwarnings
filterwarnings("ignore")

Convert HttpPostedFileBase to byte[]

As Darin says, you can read from the input stream - but I'd avoid relying on all the data being available in a single go. If you're using .NET 4 this is simple:

MemoryStream target = new MemoryStream();
model.File.InputStream.CopyTo(target);
byte[] data = target.ToArray();

It's easy enough to write the equivalent of CopyTo in .NET 3.5 if you want. The important part is that you read from HttpPostedFileBase.InputStream.

For efficient purposes you could check whether the stream returned is already a MemoryStream:

byte[] data;
using (Stream inputStream = model.File.InputStream)
{
    MemoryStream memoryStream = inputStream as MemoryStream;
    if (memoryStream == null)
    {
        memoryStream = new MemoryStream();
        inputStream.CopyTo(memoryStream);
    }
    data = memoryStream.ToArray();
}

How do I split a string by a multi-character delimiter in C#?

Based on existing responses on this post, this simplify the implementation :)

namespace System
{
    public static class BaseTypesExtensions
    {
        /// <summary>
        /// Just a simple wrapper to simplify the process of splitting a string using another string as a separator
        /// </summary>
        /// <param name="s"></param>
        /// <param name="pattern"></param>
        /// <returns></returns>
        public static string[] Split(this string s, string separator)
        {
            return s.Split(new string[] { separator }, StringSplitOptions.None);
        }


    }
}

Number of days between two dates in Joda-Time

The accepted answer builds two LocalDate objects, which are quite expensive if you are reading lot of data. I use this:

  public static int getDaysBetween(DateTime earlier, DateTime later)
  {
    return (int) TimeUnit.MILLISECONDS.toDays(later.getMillis()- earlier.getMillis());
  }

By calling getMillis() you use already existing variables.
MILLISECONDS.toDays() then, uses a simple arithmetic calculation, does not create any object.

What's the difference between "2*2" and "2**2" in Python?

Try:

2**3*2

and

2*3*2

to see the difference.

** is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.

How do you append rows to a table using jQuery?

Try:

$("#myTable").append("<tr><%= escape_javascript( render :partial => name_of_partial ) %></tr>");

And in the partial, you should have:

<td>row1</td>
<td>row2</td>

How to assign text size in sp value using java code

semeTextView.setTextSize(TypedValue.COMPLEX_UNIT_PX, 
                       context.getResources().getDimension(R.dimen.text_size_in_dp))

How to solve maven 2.6 resource plugin dependency?

Seems your settings.xml file is missing your .m2 (local maven repo) folder.

When using eclipse navigate to Window -> Preferences -> Maven -> User Settings -> Browse to your settings.xml and click apply.

Then do maven Update Project.

enter image description here

How to get JQuery.trigger('click'); to initiate a mouse click

Technically not an answer to this, but a good use of the accepted answer (https://stackoverflow.com/a/20928975/82028) to create next and prev buttons for the tabs on jQuery ACF fields:

$('.next').click(function () {
    $('#primary li.active').next().find('.acf-tab-button')[0].click();
});

$('.prev').click(function () {
    $('#primary li.active').prev().find('.acf-tab-button')[0].click();
});

centos: Another MySQL daemon already running with the same unix socket

Just open a bug report with your OS vendor asking them to put the socket in /var/run so it automagically gets removed at reboot. It's a bug to keep this socket after an unclean reboot, /var/run is the spot for these kinds of files.

Adding a view controller as a subview in another view controller

For Add and Remove ViewController

 var secondViewController :SecondViewController?

  // Adding 
 func add_ViewController() {
    let controller  = self.storyboard?.instantiateViewController(withIdentifier: "secondViewController")as! SecondViewController
    controller.view.frame = self.view.bounds
    self.view.addSubview(controller.view)
    self.addChild(controller)
    controller.didMove(toParent: self)
    self.secondViewController = controller
}

// Removing
func remove_ViewController(secondViewController:SecondViewController?) {
    if secondViewController != nil {
        if self.view.subviews.contains(secondViewController!.view) {
             secondViewController!.view.removeFromSuperview()
        }
        
    }
}

Ruby value of a hash key?

It seems that your question is maybe a bit ambiguous.

If “values” in the first sentence means any generic value (i.e. object, since everything in Ruby can be viewed as an object), then one of the other answers probably tells you what you need to know (i.e. use Hash#[] (e.g. hash[some_key]) to find the value associated with a key).

If, however, “values” in first sentence is taken to mean the value part of the “key, value pairs” (as are stored in hashes), then your question seems like it might be about working in the other direction (key for a given value).

You can find a key that leads to a certain value with Hash#key.

ruby-1.9.2-head :001 > hash = { :a => '1', :b => :two, :c => 3, 'bee' => :two }
 => {:a=>"1", :b=>:two, :c=>3, "bee"=>:two} 
ruby-1.9.2-head :002 > a_value = :two
 => :two 
ruby-1.9.2-head :003 > hash.key(a_value)
 => :b 

If you are using a Ruby earlier than 1.9, you can use Hash#index.

When there are multiple keys with the desired value, the method will only return one of them. If you want all the keys with a given value, you may have to iterate a bit:

ruby-1.9.2-head :004 > hash[:b] == hash['bee']
 => true 
ruby-1.9.2-head :005 > keys = hash.inject([]) do # all keys with value a_value
ruby-1.9.2-head :006 >       |l,kv| kv[1] == a_value ? l << kv[0] : l
ruby-1.9.2-head :007?>   end
 => [:b, "bee"] 

Once you have a key (the keys) that lead to the value, you can compare them and act on them with if/unless/case expressions, custom methods that take blocks, et cetera. Just how you compare them depends on the kind of objects you are using for keys (people often use strings and symbols, but Ruby hashes can use any kind of object as keys (as long as they are not modified while they serve as keys)).

How do I query for all dates greater than a certain date in SQL Server?

Try enclosing your date into a character string.

 select * 
 from dbo.March2010 A
 where A.Date >= '2010-04-01';

@ViewChild in *ngIf

An alternative to overcome this is running the change detector manually.

You first inject the ChangeDetectorRef:

constructor(private changeDetector : ChangeDetectorRef) {}

Then you call it after updating the variable that controls the *ngIf

show() {
        this.display = true;
        this.changeDetector.detectChanges();
    }

How can I add 1 day to current date?

Inspired by jpmottin in this question, here's the one line code:

_x000D_
_x000D_
var dateStr = '2019-01-01';_x000D_
var days = 1;_x000D_
_x000D_
var result = new Date(new Date(dateStr).setDate(new Date(dateStr).getDate() + days));_x000D_
_x000D_
document.write('Date: ', result); // Wed Jan 02 2019 09:00:00 GMT+0900 (Japan Standard Time)_x000D_
document.write('<br />');_x000D_
document.write('Trimmed Date: ', result.toISOString().substr(0, 10)); // 2019-01-02
_x000D_
_x000D_
_x000D_

Hope this helps

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder"

According to SLF4J official documentation

Failed to load class org.slf4j.impl.StaticLoggerBinder

This warning message is reported when the org.slf4j.impl.StaticLoggerBinder class could not be loaded into memory. This happens when no appropriate SLF4J binding could be found on the class path. Placing one (and only one) of slf4j-nop.jar, slf4j-simple.jar, slf4j-log4j12.jar, slf4j-jdk14.jar or logback-classic.jar on the class path should solve the problem.

Simply add this jar along with slf4j api.jar to your classpath to get things done. Best of luck

Execute cmd command from VBScript

Can also invoke oShell.Exec in order to be able to read STDIN/STDOUT/STDERR responses. Perfect for error checking which it seems you're doing with your sanity .BAT.

What's the purpose of META-INF?

You have MANIFEST.MF file inside your META-INF folder. You can define optional or external dependencies that you must have access to.

Example:

Consider you have deployed your app and your container(at run time) found out that your app requires a newer version of a library which is not inside lib folder, in that case if you have defined the optional newer version in MANIFEST.MF then your app will refer to dependency from there (and will not crash).

Source: Head First Jsp & Servlet

How to split data into trainset and testset randomly?

To answer @desmond.carros question, I modified the best answer as follows,

 import random
 file=open("datafile.txt","r")
 data=list()
 for line in file:
    data.append(line.split(#your preferred delimiter))
 file.close()
 random.shuffle(data)
 train_data = data[:int((len(data)+1)*.80)] #Remaining 80% to training set
 test_data = data[int((len(data)+1)*.80):] #Splits 20% data to test set

The code splits the entire dataset to 80% train and 20% test data

psycopg2: insert multiple rows with one query

I built a program that inserts multiple lines to a server that was located in another city.

I found out that using this method was about 10 times faster than executemany. In my case tup is a tuple containing about 2000 rows. It took about 10 seconds when using this method:

args_str = ','.join(cur.mogrify("(%s,%s,%s,%s,%s,%s,%s,%s,%s)", x) for x in tup)
cur.execute("INSERT INTO table VALUES " + args_str) 

and 2 minutes when using this method:

cur.executemany("INSERT INTO table VALUES(%s,%s,%s,%s,%s,%s,%s,%s,%s)", tup)

In HTML5, should the main navigation be inside or outside the <header> element?

I do not like putting the nav in the header. My reasoning is:

Logic

The header contains introductory information about the document. The nav is a menu that links to other documents. To my mind this means that the content of the nav belongs to the site rather than the document. An exception would be if the NAV held forward links.

Accessibility

I like to put menus at the end of the source code rather than the start. I use CSS to send it to the top of a computer screen or leave it at the end for text-speech browsers and small screens. This avoids the need for skip-links.

What's the difference between disabled="disabled" and readonly="readonly" for HTML form input fields?

Disabled means that no data from that form element will be submitted when the form is submitted. Read-only means any data from within the element will be submitted, but it cannot be changed by the user.

For example:

<input type="text" name="yourname" value="Bob" readonly="readonly" />

This will submit the value "Bob" for the element "yourname".

<input type="text" name="yourname" value="Bob" disabled="disabled" />

This will submit nothing for the element "yourname".

Calculate last day of month in JavaScript

I recently had to do something similar, this is what I came up with:

/**
* Returns a date set to the begining of the month
* 
* @param {Date} myDate 
* @returns {Date}
*/
function beginningOfMonth(myDate){    
  let date = new Date(myDate);
  date.setDate(1)
  date.setHours(0);
  date.setMinutes(0);
  date.setSeconds(0);   
  return date;     
}

/**
 * Returns a date set to the end of the month
 * 
 * @param {Date} myDate 
 * @returns {Date}
 */
function endOfMonth(myDate){
  let date = new Date(myDate);
  date.setMonth(date.getMonth() +1)
  date.setDate(0);
  date.setHours(23);
  date.setMinutes(59);
  date.setSeconds(59);
  return date;
}

Pass it in a date, and it will return a date set to either the beginning of the month, or the end of the month.

The begninngOfMonth function is fairly self-explanatory, but what's going in in the endOfMonth function is that I'm incrementing the month to the next month, and then using setDate(0) to roll back the day to the last day of the previous month which is a part of the setDate spec:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/setDate https://www.w3schools.com/jsref/jsref_setdate.asp

I then set the hour/minutes/seconds to the end of the day, so that if you're using some kind of API that is expecting a date range you'll be able to capture the entirety of that last day. That part might go beyond what the original post is asking for but it could help someone else looking for a similar solution.

Edit: You can also go the extra mile and set milliseconds with setMilliseconds() if you want to be extra precise.

Nullable property to entity field, Entity Framework through Code First

Jon's answer didn't work for me as I got a compiler error CS0453 C# The type must be a non-nullable value type in order to use it as parameter 'T' in the generic type or method

This worked for me though:

protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
    modelBuilder.Entity<SomeObject>().HasOptional(m => m.somefield);
    base.OnModelCreating(modelBuilder);
}

Excel VBA - Delete empty rows

How about

sub foo()
  dim r As Range, rows As Long, i As Long
  Set r = ActiveSheet.Range("A1:Z50")
  rows = r.rows.Count
  For i = rows To 1 Step (-1)
    If WorksheetFunction.CountA(r.rows(i)) = 0 Then r.rows(i).Delete
  Next
End Sub

Try this

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Range("A" & i & ":" & "Z" & i)
            Else
                Set DelRange = Union(DelRange, Range("A" & i & ":" & "Z" & i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

IF you want to delete the entire row then use this code

Option Explicit

Sub Sample()
    Dim i As Long
    Dim DelRange As Range

    On Error GoTo Whoa

    Application.ScreenUpdating = False

    For i = 1 To 50
        If Application.WorksheetFunction.CountA(Range("A" & i & ":" & "Z" & i)) = 0 Then
            If DelRange Is Nothing Then
                Set DelRange = Rows(i)
            Else
                Set DelRange = Union(DelRange, Rows(i))
            End If
        End If
    Next i

    If Not DelRange Is Nothing Then DelRange.Delete shift:=xlUp
LetsContinue:
    Application.ScreenUpdating = True

    Exit Sub
Whoa:
    MsgBox Err.Description
    Resume LetsContinue
End Sub

Android - How to decode and decompile any APK file?

To decompile APK Use APKTool.
You can learn how APKTool works on http://www.decompileandroid.com/ or by reading the documentation.

How to get last inserted row ID from WordPress database?

Putting the call to mysql_insert_id() inside a transaction, should do it:

mysql_query('BEGIN');
// Whatever code that does the insert here.
$id = mysql_insert_id();
mysql_query('COMMIT');
// Stuff with $id.

How to convert NSNumber to NSString

Try:

NSString *myString = [NSNumber stringValue];

Remove excess whitespace from within a string

$str = trim(preg_replace('/\s+/',' ', $str));

The above line of code will remove extra spaces, as well as leading and trailing spaces.

Ping a site in Python?

Depending on what you want to achive, you are probably easiest calling the system ping command..

Using the subprocess module is the best way of doing this, although you have to remember the ping command is different on different operating systems!

import subprocess

host = "www.google.com"

ping = subprocess.Popen(
    ["ping", "-c", "4", host],
    stdout = subprocess.PIPE,
    stderr = subprocess.PIPE
)

out, error = ping.communicate()
print out

You don't need to worry about shell-escape characters. For example..

host = "google.com; `echo test`

..will not execute the echo command.

Now, to actually get the ping results, you could parse the out variable. Example output:

round-trip min/avg/max/stddev = 248.139/249.474/250.530/0.896 ms

Example regex:

import re
matcher = re.compile("round-trip min/avg/max/stddev = (\d+.\d+)/(\d+.\d+)/(\d+.\d+)/(\d+.\d+)")
print matcher.search(out).groups()

# ('248.139', '249.474', '250.530', '0.896')

Again, remember the output will vary depending on operating system (and even the version of ping). This isn't ideal, but it will work fine in many situations (where you know the machines the script will be running on)

Angular2 - Input Field To Accept Only Numbers

You can do this easily using a mask:

<input type='text' mask="99" formControlName="percentage" placeholder="0">

99 - optional 2 digits

Don't forget to import NgxMaskModule in your module:

imports: [
    NgxMaskModule.forRoot(),
]

Markdown to create pages and table of contents?

For me, the solution proposed by @Tum works like a charm for a table of contents with 2 levels. However, for the 3rd level it didn't work. It didn't display the link as for the first 2 levels, it displays the plain text 3.5.1. [bla bla bla](#blablabla) <br> instead.

My solution is an addition to the solution of @Tum (which is very simple) for people who need a table of contents with 3 levels or more.

On the second level, a simple tab will do the indent correctly for you. But it doesn't support 2 tabs. Instead, you have to use one tab and add as many &nbsp; as needed yourself in order to align the 3rd level correctly.

Here's an example using 4 levels (higher the levels, awful it becomes):

# Table of Contents
1. [Title](#title) <br>
    1.1. [sub-title](#sub_title) <br>
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.1.1. [sub-sub-title](#sub_sub_title)
    &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;1.1.1.1. [sub-sub-sub-title](#sub_sub_sub_title)

# Title <a name="title"></a>
Heading 1

## Sub-Title <a name="sub_title"></a>
Heading 2

### Sub-Sub-Title <a name="sub_sub_title"></a>
Heading 3

#### Sub-Sub-Sub-Title <a name="sub_sub_sub_title"></a>
Heading 4

This gives the following result where every element of the table of contents is a link to its corresponding section. Note also the <br> in order to add a new line instead of being on the same line.

Table of Contents

  1. Title
    1.1. Sub-Title
           1.1.1. Sub-Sub-Title
                     1.1.1.1. Sub-Sub-Sub-Title

Title

Heading 1

Sub-Title

Heading 2

Sub-Sub-Title

Heading 3

Sub-Sub-Sub-Title

Heading 4

Replacing &nbsp; from javascript dom text node

This is much easier than you're making it. The text node will not have the literal string "&nbsp;" in it, it'll have have the corresponding character with code 160.

function replaceNbsps(str) {
  var re = new RegExp(String.fromCharCode(160), "g");
  return str.replace(re, " ");
}

textNode.nodeValue = replaceNbsps(textNode.nodeValue);

UPDATE

Even easier:

textNode.nodeValue = textNode.nodeValue.replace(/\u00a0/g, " ");

How to find numbers from a string?

Regular expressions are built to parse. While the syntax can take a while to pick up on this approach is very efficient, and is very flexible for handling more complex string extractions/replacements

Sub Tester()
     MsgBox CleanString("3d1fgd4g1dg5d9gdg")
End Sub

Function CleanString(strIn As String) As String
    Dim objRegex
    Set objRegex = CreateObject("vbscript.regexp")
    With objRegex
     .Global = True
     .Pattern = "[^\d]+"
    CleanString = .Replace(strIn, vbNullString)
    End With
End Function

ORA-29283: invalid file operation ORA-06512: at "SYS.UTL_FILE", line 536

I had been facing this problem for two days and I found that the directory you create in Oracle also needs to created first on your physical disk.

I didn't find this point mentioned anywhere i tried to look up the solution to this.

Example

If you created a directory, let's say, 'DB_DIR'.

CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DB_WORKS';

Then you need to ensure that DB_WORKS exists in your E:\ drive and also file system level Read/Write permissions are available to the Oracle process.

My understanding of UTL_FILE from my experiences is given below for this kind of operation.

UTL_FILE is an object under SYS user. GRANT EXECUTE ON SYS.UTL_FILE TO PUBLIC; needs to given while logged in as SYS. Otherwise, it will give declaration error in procedure. Anyone can create a directory as shown:- CREATE OR REPLACE DIRECTORY DB_DIR AS 'E:\DBWORKS'; But CREATE DIRECTORY permission should be in place. This can be granted as shown:- GRANT CREATE ALL DIRECTORY TO user; while logged in as SYS user. However, if this needs to be used by another user, grants need to be given to that user otherwise it will throw error. GRANT READ, WRITE, EXECUTE ON DB_DIR TO user; while loggedin as the user who created the directory. Then, compile your package. Before executing the procedure, ensure that the Directory exists physically on your Disk. Otherwise it will throw 'Invalid File Operation' error. (V. IMPORTANT) Ensure that Filesystem level Read/Write permissions are in place for the Oracle process. This is separate from the DB level permissions granted.(V. IMPORTANT) Execute procedure. File should get populated with the result set of your query.

Excel date to Unix timestamp

If we assume the date in Excel is in A1 cell formatted as Date and the Unix timestamp should be in a A2 cell formatted as number the formula in A2 should be:

= (A1 * 86400) - 2209075200

where:

86400 is the number of seconds in the day 2209075200 is the number of seconds between 1900-01-01 and 1970-01-01 which are the base dates for Excel and Unix timestamps.

The above is true for Windows. On Mac the base date in Excel is 1904-01-01 and the seconds number should be corrected to: 2082844800

IF...THEN...ELSE using XML

<IF id='if-1'>
    <CONDITION>
        <TIME from="5pm" to="9pm" />
    </CONDITION>
    <THEN>
        <...some actions defined.../>
    </THEN>
    <ELSE>
        <...other set of actions defined here.../>
    </ELSE>
</IF>

Seems easier to read to me. There's more nesting, but if anything that helps with the readability?

Need to list all triggers in SQL Server database with table name and table's schema

this may help.

SELECT DISTINCT o.[name] AS [Table]
FROM    [sysobjects] o
JOIN    [sysobjects] tr
    ON  o.[id] = tr.[parent_obj]
WHERE   tr.[type] = 'tr'
ORDER BY [Table]

Get a list of tables and all their triggers.

SELECT DISTINCT o.[name] AS [Table], tr.[name] AS [Trigger]
FROM    [sysobjects] o
JOIN    [sysobjects] tr
    ON  o.[id] = tr.[parent_obj]
WHERE   tr.[type] = 'tr'
ORDER BY [Table], [Trigger]

AlertDialog styling - how to change style (color) of title, message, etc

I changed color programmatically in this way :

var builder = new AlertDialog.Builder (this);
...
...
...
var dialog = builder.Show ();
int textColorId = Resources.GetIdentifier ("alertTitle", "id", "android");
TextView textColor = dialog.FindViewById<TextView> (textColorId);
textColor?.SetTextColor (Color.DarkRed);

as alertTitle, you can change other data by this way (next example is for titleDivider):

int titleDividerId = Resources.GetIdentifier ("titleDivider", "id", "android");
View titleDivider = dialog.FindViewById (titleDividerId);
titleDivider?.SetBackgroundColor (Color.Red);

this is in C#, but in java it is the same.

Are complex expressions possible in ng-hide / ng-show?

Use a controller method if you need to run arbitrary JavaScript code, or you could define a filter that returned true or false.

I just tested (should have done that first), and something like ng-show="!a && b" worked as expected.

Getting the size of an array in an object

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

st.itemb.length

How to fill in proxy information in cntlm config file?

Here is a guide on how to use cntlm

What is cntlm?

cntlm is an NTLM/NTLMv2 authenticating HTTP proxy

It takes the address of your proxy and opens a listening socket, forwarding each request to the parent proxy

Why cntlm?

Using cntlm we make it possible to run tools like choro, pip3, apt-get from a command line

pip3 install requests
choco install git

The main advantage of cntlm is password protection.

With cntlm you can use password hashes.

So NO PLAINTEXT PASSWORD in %HTTP_PROXY% and %HTTPS_PROXY% environment variables

Install cntlm

You can get the latest cntlm release from sourceforge

Note! Username and domain

My username is zezulinsky

My domain is local

When I run commands I use zezulinsky@local

Place your username when you run commands

Generate password hash

Run a command

cntlm -u zezulinsky@local -H

Enter your password:

Password:

As a result you are getting hashed password:

PassLM          AB7D42F42QQQQ407552C4BCA4AEBFB11
PassNT          PE78D847E35FA7FA59710D1231AAAF99
PassNTLMv2      46738B2E607F9093296AA4C319C3A259

Verify your generated hash is valid

Run a command

cntlm -u zezulinsky@local -M http://google.com

Enter your password

Password:

The result output

Config profile  1/4... OK (HTTP code: 301)
----------------------------[ Profile  0 ]------
Auth            NTLMv2
PassNTLMv2      46738B2E607F9093296AA4C319C3A259
------------------------------------------------

Note! check that PassNTLMv2 hash is the same The resulting hash is the same for both commands

PassNTLMv2      46738B2E607F9093296AA4C319C3A259

Change configuration file

Place generated hashes into the cntlm.ini configuration file

C:\Program Files (x86)\Cntlm\cntlm.ini

Here is how your cntlm.ini should look like

Username    zezulinsky
Domain      local
PassLM      AB7D42F42QQQQ407552C4BCA4AEBFB11
PassNT      PE78D847E35FA7FA59710D1231AAAF99
PassNTLMv2  46738B2E607F9093296AA4C319C3A259

Proxy       PROXYSERVER:8080
NoProxy     localhost, 127.0.0.*
Listen      3128

Note! newline at the end of cntlm.ini

It is important to add a newline at the end of the cntlm.ini configuration file

Set your environment variables

HTTPS_PROXY=http://localhost:3128
HTTP_PROXY=http://localhost:3128

Check that your cntlm works

Stop all the processes named cntlm.exe with process explorer

Run the command

cntlm -u zezulinsky@local -H

The output looks like

cygwin warning:
  MS-DOS style path detected: C:\Program Files (x86)\Cntlm\cntlm.ini
  Preferred POSIX equivalent is: /Cntlm/cntlm.ini
  CYGWIN environment variable option "nodosfilewarning" turns off this warning.
  Consult the user's guide for more details about POSIX paths:
    http://cygwin.com/cygwin-ug-net/using.html#using-pathnames
section: local, Username = 'zezulinsky'
section: local, Domain = 'local'
section: local, PassLM = 'AB7D42F42QQQQ407552C4BCA4AEBFB11'
section: local, PassNT = 'PE78D847E35FA7FA59710D1231AAAF99'
section: local, PassNTLMv2 = '46738B2E607F9093296AA4C319C3A259'
section: local, Proxy = 'PROXYSERVER:8080'
section: local, NoProxy = 'localhost, 10.*, 127.0.0.*
section: local, Listen = '3128'
Default config file opened successfully
cntlm: Proxy listening on 127.0.0.1:3128
Adding no-proxy for: 'localhost'
Adding no-proxy for: '10.*'
Adding no-proxy for: '127.0.0.*'
cntlm: Workstation name used: MYWORKSTATION
cntlm: Using following NTLM hashes: NTLMv2(1) NT(0) LM(0)
cntlm: PID 1234: Cntlm ready, staying in the foreground

Open a new cmd and run a command:

pip3 install requests

You should have requests python package installed

Restart your machine

Congrats, now you have cntlm installed and configured

The way to check a HDFS directory's size?

Prior to 0.20.203, and officially deprecated in 2.6.0:

hadoop fs -dus [directory]

Since 0.20.203 (dead link) 1.0.4 and still compatible through 2.6.0:

hdfs dfs -du [-s] [-h] URI [URI …]

You can also run hadoop fs -help for more info and specifics.

Pointer to 2D arrays in C

Ok, this is actually four different question. I'll address them one by one:

are both equals for the compiler? (speed, perf...)

Yes. The pointer dereferenciation and decay from type int (*)[100][280] to int (*)[280] is always a noop to your CPU. I wouldn't put it past a bad compiler to generate bogus code anyways, but a good optimizing compiler should compile both examples to the exact same code.

is one of these solutions eating more memory than the other?

As a corollary to my first answer, no.

what is the more frequently used by developers?

Definitely the variant without the extra (*pointer) dereferenciation. For C programmers it is second nature to assume that any pointer may actually be a pointer to the first element of an array.

what is the best way, the 1st or the 2nd?

That depends on what you optimize for:

  • Idiomatic code uses variant 1. The declaration is missing the outer dimension, but all uses are exactly as a C programmer expects them to be.

  • If you want to make it explicit that you are pointing to an array, you can use variant 2. However, many seasoned C programmers will think that there's a third dimension hidden behind the innermost *. Having no array dimension there will feel weird to most programmers.

Lombok added but getters and setters not recognized in Intellij IDEA

Goto Setting->Plugin->Search for "Lombok Plugin" -> It will show results. Install Lombok Plugin from the list and Restart Intellij

How do I accomplish an if/else in mustache.js?

This is something you solve in the "controller", which is the point of logicless templating.

// some function that retreived data through ajax
function( view ){

   if ( !view.avatar ) {
      // DEFAULTS can be a global settings object you define elsewhere
      // so that you don't have to maintain these values all over the place
      // in your code.
      view.avatar = DEFAULTS.AVATAR;
   }

   // do template stuff here

}

This is actually a LOT better then maintaining image url's or other media that might or might not change in your templates, but takes some getting used to. The point is to unlearn template tunnel vision, an avatar img url is bound to be used in other templates, are you going to maintain that url on X templates or a single DEFAULTS settings object? ;)

Another option is to do the following:

// augment view
view.hasAvatar = !!view.avatar;
view.noAvatar = !view.avatar;

And in the template:

{{#hasAvatar}}
    SHOW AVATAR
{{/hasAvatar}}
{{#noAvatar}}
    SHOW DEFAULT
{{/noAvatar}}

But that's going against the whole meaning of logicless templating. If that's what you want to do, you want logical templating and you should not use Mustache, though do give it yourself a fair chance of learning this concept ;)

Syntax for a single-line Bash infinite while loop

For simple process watching use watch instead

warning: control reaches end of non-void function [-Wreturn-type]

You just need to return from the main function at some point. The error message says that the function is defined to return a value but you are not returning anything.

  /* .... */
  if (Date1 == Date2)  
     fprintf (stderr , "Indicating that the first date is equal to second date.\n"); 

  return 0;
}

Difference between signature versions - V1 (Jar Signature) and V2 (Full APK Signature) while generating a signed APK in Android Studio?

According to this link: signature help

APK Signature Scheme v2 offers:

  1. Faster app install times
  2. More protection against unauthorized alterations to APK files.

Android 7.0 introduces APK Signature Scheme v2, a new app-signing scheme that offers faster app install times and more protection against unauthorized alterations to APK files. By default, Android Studio 2.2 and the Android Plugin for Gradle 2.2 sign your app using both APK Signature Scheme v2 and the traditional signing scheme, which uses JAR signing.

It is recommended to use APK Signature Scheme v2 but is not mandatory.

Although we recommend applying APK Signature Scheme v2 to your app, this new scheme is not mandatory. If your app doesn't build properly when using APK Signature Scheme v2, you can disable the new scheme.

Loading DLLs at runtime in C#

foreach (var f in Directory.GetFiles(".", "*.dll"))
            Assembly.LoadFrom(f);

That loads all the DLLs present in your executable's folder.

In my case I was trying to use Reflection to find all subclasses of a class, even in other DLLs. This worked, but I'm not sure if it's the best way to do it.

EDIT: I timed it, and it only seems to load them the first time.

Stopwatch stopwatch = new Stopwatch();
for (int i = 0; i < 4; i++)
{
    stopwatch.Restart();
    foreach (var f in Directory.GetFiles(".", "*.dll"))
        Assembly.LoadFrom(f);
    stopwatch.Stop();
    Console.WriteLine(stopwatch.ElapsedMilliseconds);
}

Output: 34 0 0 0

So one could potentially run that code before any Reflection searches just in case.

Center a popup window on screen?

It works very well in Firefox.
Just change the top variable to any other name and try again

        var w = 200;
        var h = 200;
        var left = Number((screen.width/2)-(w/2));
        var tops = Number((screen.height/2)-(h/2));

window.open("templates/sales/index.php?go=new_sale", '', 'toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=no, resizable=no, copyhistory=no, width='+w+', height='+h+', top='+tops+', left='+left);

Swift Open Link in Safari

It's not "baked in to Swift", but you can use standard UIKit methods to do it. Take a look at UIApplication's openUrl(_:) (deprecated) and open(_:options:completionHandler:).

Swift 4 + Swift 5 (iOS 10 and above)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.open(url)

Swift 3 (iOS 9 and below)

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.shared.openURL(url)

Swift 2.2

guard let url = URL(string: "https://stackoverflow.com") else { return }
UIApplication.sharedApplication().openURL(url)    

Error when trying to inject a service into an angular component "EXCEPTION: Can't resolve all parameters for component", why?

_x000D_
_x000D_
import {Injector} from '@angular/core';
import {ServiceA} from './service-a';

@Component({
  // ... 
})
class MyComp {
  constructor(private injector: Injector) {
     const serviceA = injector.get(ServiceA);
  }
}
_x000D_
_x000D_
_x000D_

Is it possible to focus on a <div> using JavaScript focus() function?

Yes - this is possible. In order to do it, you need to assign a tabindex...

<div tabindex="0">Hello World</div>

A tabindex of 0 will put the tag "in the natural tab order of the page". A higher number will give it a specific order of priority, where 1 will be the first, 2 second and so on.

You can also give a tabindex of -1, which will make the div only focus-able by script, not the user.

_x000D_
_x000D_
document.getElementById('test').onclick = function () {_x000D_
    document.getElementById('scripted').focus();_x000D_
};
_x000D_
div:focus {_x000D_
    background-color: Aqua;_x000D_
}
_x000D_
<div>Element X (not focusable)</div>_x000D_
<div tabindex="0">Element Y (user or script focusable)</div>_x000D_
<div tabindex="-1" id="scripted">Element Z (script-only focusable)</div>_x000D_
<div id="test">Set Focus To Element Z</div>
_x000D_
_x000D_
_x000D_

Obviously, it is a shame to have an element you can focus by script that you can't focus by other input method (especially if a user is keyboard only or similarly constrained). There are also a whole bunch of standard elements that are focusable by default and have semantic information baked in to assist users. Use this knowledge wisely.

How can I add raw data body to an axios request?

The only solution I found that would work is the transformRequest property which allows you to override the extra data prep axios does before sending off the request.

    axios.request({
        method: 'post',
        url: 'http://foo.bar/',
        data: {},
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        transformRequest: [(data, header) => {
            data = 'grant_type=client_credentials'
            return data
        }]
    })

How to hide a navigation bar from first ViewController in Swift?

You can do it from the window controller (Swift3)

class WindowController: NSWindowController {

    override func windowDidLoad() {
        super.windowDidLoad()

        window?.titleVisibility = .hidden
    }
}

Python NoneType object is not callable (beginner)

I faced the error "TypeError: 'NoneType' object is not callable " but for a different issue. With the above clues, i was able to debug and got it right! The issue that i faced was : I had the custome Library written and my file wasnt recognizing it although i had mentioned it

example: 
Library           ../../../libraries/customlibraries/ExtendedWaitKeywords.py
the keywords from my custom library were recognized and that error  was resolved only after specifying the complete path, as it was not getting the callable function.

How can I use iptables on centos 7?

I modified the /etc/sysconfig/ip6tables-config file changing:

IP6TABLES_SAVE_ON_STOP="no"

To:

IP6TABLES_SAVE_ON_STOP="yes"

And this:

IP6TABLES_SAVE_ON_RESTART="no"

To:

IP6TABLES_SAVE_ON_RESTART="yes"

This seemed to save the changes I made using the iptables commands through a reboot.

VBA Macro to compare all cells of two Excel files

Do NOT loop through all cells!! There is a lot of overhead in communications between worksheets and VBA, for both reading and writing. Looping through all cells will be agonizingly slow. I'm talking hours.

Instead, load an entire sheet at once into a Variant array. In Excel 2003, this takes about 2 seconds (and 250 MB of RAM). Then you can loop through it in no time at all.

In Excel 2007 and later, sheets are about 1000 times larger (1048576 rows × 16384 columns = 17 billion cells, compared to 65536 rows × 256 columns = 17 million in Excel 2003). You will run into an "Out of memory" error if you try to load the whole sheet into a Variant; on my machine I can only load 32 million cells at once. So you have to limit yourself to the range you know has actual data in it, or load the sheet bit by bit, e.g. 30 columns at a time.

Option Explicit

Sub test()

    Dim varSheetA As Variant
    Dim varSheetB As Variant
    Dim strRangeToCheck As String
    Dim iRow As Long
    Dim iCol As Long

    strRangeToCheck = "A1:IV65536"
    ' If you know the data will only be in a smaller range, reduce the size of the ranges above.
    Debug.Print Now
    varSheetA = Worksheets("Sheet1").Range(strRangeToCheck)
    varSheetB = Worksheets("Sheet2").Range(strRangeToCheck) ' or whatever your other sheet is.
    Debug.Print Now

    For iRow = LBound(varSheetA, 1) To UBound(varSheetA, 1)
        For iCol = LBound(varSheetA, 2) To UBound(varSheetA, 2)
            If varSheetA(iRow, iCol) = varSheetB(iRow, iCol) Then
                ' Cells are identical.
                ' Do nothing.
            Else
                ' Cells are different.
                ' Code goes here for whatever it is you want to do.
            End If
        Next iCol
    Next iRow

End Sub

To compare to a sheet in a different workbook, open that workbook and get the sheet as follows:

Set wbkA = Workbooks.Open(filename:="C:\MyBook.xls")
Set varSheetA = wbkA.Worksheets("Sheet1") ' or whatever sheet you need

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

You can implement this way

$resource('http://localhost\\:3000/realmen/:entryId', {entryId: '@entryId'}, {
        UPDATE: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId' },
        ACTION: {method: 'PUT', url: 'http://localhost\\:3000/realmen/:entryId/action' }
    })

RealMen.query() //GET  /realmen/
RealMen.save({entryId: 1},{post data}) // POST /realmen/1
RealMen.delete({entryId: 1}) //DELETE /realmen/1

//any optional method
RealMen.UPDATE({entryId:1}, {post data}) // PUT /realmen/1

//query string
RealMen.query({name:'john'}) //GET /realmen?name=john

Documentation: https://docs.angularjs.org/api/ngResource/service/$resource

Hope it helps

Change mysql user password using command line

Your login root should be /usr/local/directadmin/conf/mysql.conf. Then try following

UPDATE mysql.user SET password=PASSWORD('$w0rdf1sh') WHERE user='tate256' AND Host='10.10.2.30';
FLUSH PRIVILEGES;

Host is your mysql host.

CSS/HTML: What is the correct way to make text italic?

HTML italic text displays the text in italic format.

<i>HTML italic text example</i>

The emphasis and strong elements can both be used to increase the importance of certain words or sentences.

<p>This is <em>emphasized </em> text format <em>example</em></p>

The emphasis tag should be used when you want to emphasize a point in your text and not necessarily when you want to italicize that text.

See this guide for more: HTML Text Formatting

Is it possible to make abstract classes in Python?

In your code snippet, you could also resolve this by providing an implementation for the __new__ method in the subclass, likewise:

def G(F):
    def __new__(cls):
        # do something here

But this is a hack and I advise you against it, unless you know what you are doing. For nearly all cases I advise you to use the abc module, that others before me have suggested.

Also when you create a new (base) class, make it subclass object, like this: class MyBaseClass(object):. I don't know if it is that much significant anymore, but it helps retain style consistency on your code

How to parse Excel (XLS) file in Javascript/HTML5

Upload an excel file here and you can get the data in JSON format in console:

_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/jszip.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.8.0/xlsx.js"></script>_x000D_
<script>_x000D_
    var ExcelToJSON = function() {_x000D_
_x000D_
      this.parseExcel = function(file) {_x000D_
        var reader = new FileReader();_x000D_
_x000D_
        reader.onload = function(e) {_x000D_
          var data = e.target.result;_x000D_
          var workbook = XLSX.read(data, {_x000D_
            type: 'binary'_x000D_
          });_x000D_
          workbook.SheetNames.forEach(function(sheetName) {_x000D_
            // Here is your object_x000D_
            var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);_x000D_
            var json_object = JSON.stringify(XL_row_object);_x000D_
            console.log(JSON.parse(json_object));_x000D_
            jQuery( '#xlx_json' ).val( json_object );_x000D_
          })_x000D_
        };_x000D_
_x000D_
        reader.onerror = function(ex) {_x000D_
          console.log(ex);_x000D_
        };_x000D_
_x000D_
        reader.readAsBinaryString(file);_x000D_
      };_x000D_
  };_x000D_
_x000D_
  function handleFileSelect(evt) {_x000D_
    _x000D_
    var files = evt.target.files; // FileList object_x000D_
    var xl2json = new ExcelToJSON();_x000D_
    xl2json.parseExcel(files[0]);_x000D_
  }_x000D_
_x000D_
_x000D_
 _x000D_
</script>_x000D_
_x000D_
<form enctype="multipart/form-data">_x000D_
    <input id="upload" type=file  name="files[]">_x000D_
</form>_x000D_
_x000D_
    <textarea class="form-control" rows=35 cols=120 id="xlx_json"></textarea>_x000D_
_x000D_
    <script>_x000D_
        document.getElementById('upload').addEventListener('change', handleFileSelect, false);_x000D_
_x000D_
    </script>
_x000D_
_x000D_
_x000D_

This is a combination of the following Stackoverflow posts:

  1. https://stackoverflow.com/a/37083658/4742733
  2. https://stackoverflow.com/a/39515846/4742733

Good Luck...

How to set max width of an image in CSS

The problem is that img tag is inline element and you can't restrict width of inline element.

So to restrict img tag width first you need to convert it into a inline-block element

img.Image{
    display: inline-block;
}

Incrementing in C++ - When to use x++ or ++x?

Just wanted to re-emphasize that ++x is expected to be faster than x++, (especially if x is an object of some arbitrary type), so unless required for logical reasons, ++x should be used.

Can (domain name) subdomains have an underscore "_" in it?

Recently the CAB-forum (*) decided that

All certificates containing an underscore character in any dNSName entry and having a validity period of more than 30 days MUST be revoked prior to January 15, 2019. https://cabforum.org/2018/11/12/ballot-sc-12-sunset-of-underscores-in-dnsnames/

This means that you are no longer allowed to use underscores in domains that will have a ssl/tls certificate.

(*) The Certification Authority Browser Forum (CA/Browser Forum) is a voluntary gathering of leading Certificate Issuers (as defined in Section 2.1(a)(1) and (2) below) and vendors of Internet browser software and other applications that use certificates (Certificate Consumers, as defined in Section 2.1(a)(3) below).

In CSS what is the difference between "." and "#" when declaring a set of styles?

Like pretty much everyone has stated already:

A period (.) indicates a class, and a hash (#) indicates an ID.

The fundamental difference between is that you can reuse a class on your page over and over, whereas an ID can be used once. That is, of course, if you are sticking to WC3 standards.

A page will still render if you have multiple elements with the same ID, but you will run into problems if/when you try to dynamically update said elements by calling them with their ID, since they are not unique.

It is also useful to note that ID properties will supersede class properties.

Why use argparse rather than optparse?

The best source for rationale for a Python addition would be its PEP: PEP 389: argparse - New Command Line Parsing Module, in particular, the section entitled, Why aren't getopt and optparse enough?

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

Try disabling Android hardware acceleration in your manifest.

android:hardwareAccelerated="false"

Subtract days from a DateTime

That error usually occurs when you try to subtract an interval from DateTime.MinValue or you want to add something to DateTime.MaxValue (or you try to instantiate a date outside this min-max interval). Are you sure you're not assigning MinValue somewhere?

Android: Create a toggle button with image and no text

create toggle_selector.xml in res/drawable

<?xml version="1.0" encoding="utf-8"?> 
<selector xmlns:android="http://schemas.android.com/apk/res/android">
  <item android:drawable="@drawable/toggle_on" android:state_checked="true"/>
  <item android:drawable="@drawable/toggle_off" android:state_checked="false"/>
</selector>

apply the selector to your toggle button

<ToggleButton
            android:id="@+id/chkState"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="@drawable/toggle_selector"
            android:textOff=""
            android:textOn=""/>

Note: for removing the text i used following in above code

textOff=""
textOn=""

Clear text from textarea with selenium

I ran into a field where .clear() did not work. Using a combination of the first two answers worked for this field.

from selenium.webdriver.common.keys import Keys

#...your code (I was using python 3)

driver.find_element_by_id('foo').send_keys(Keys.CONTROL + "a");
driver.find_element_by_id('foo').send_keys(Keys.DELETE);

Set an empty DateTime variable

This will work for null able dateTime parameter

. .

SearchUsingDate(DateTime? StartDate, DateTime? EndDate){
     DateTime LastDate;
     if (EndDate != null)
       {
          LastDate = (DateTime)EndDate;
          LastDate = LastDate.AddDays(1);
          EndDate = LastDate;
        }
}

Unable to install pyodbc on Linux

I know this is an old question, but the maintainer has a pyodbc GitHub Repo.

I also found a very good example for installing FreeTDS and setting up the config files.


Following the instructions on the GitHub docs seems to me to always be the best option. As of February, 2018, for CentOs7 (they have all flavors at the link) they say:

# Add the RHEL 6 library for Centos-7 of MSSQL driver. Centos7 uses RHEL-6 Libraries.
sudo su 
curl https://packages.microsoft.com/config/rhel/6/prod.repo > /etc/yum.repos.d/mssql-release.repo
exit

# Uninstall if already installed Unix ODBC driver
sudo yum remove unixODBC-utf16 unixODBC-utf16-devel #to avoid conflicts

# Install the  msodbcsql unixODBC-utf16 unixODBC-utf16-devel driver
sudo ACCEPT_EULA=Y yum install msodbcsql

#optional: for bcp and sqlcmd
sudo ACCEPT_EULA=Y yum install mssql-tools
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bash_profile
echo 'export PATH="$PATH:/opt/mssql-tools/bin"' >> ~/.bashrc
source ~/.bashrc

# optional: for unixODBC development headers
sudo yum install unixODBC-devel

# the Microsoft driver expects unixODBC to be here /usr/lib64/libodbc.so.1, so add soft links to the '.so.2' files
cd /usr/lib64
sudo ln -s libodbccr.so.2   libodbccr.so.1
sudo ln -s libodbcinst.so.2 libodbcinst.so.1
sudo ln -s libodbc.so.2     libodbc.so.1

# Set the path for unixODBC
export ODBCINI=/usr/local/etc/odbc.ini
export ODBCSYSINI=/usr/local/etc
source ~/.bashrc

# Prepare a temp file for defining the DSN to your database server
vi /home/user/odbcadd.txt

[MyMSSQLServer]
Driver      = ODBC Driver 13 for SQL Server
Description = My MS SQL Server
Trace       = No
Server      = 10.100.1.10

# register the SQL Server database DSN information in /etc/odbc.ini
sudo odbcinst -i -s -f /home/user/odbcadd.txt -l

# check the DSN installation with:
odbcinst -j
cat /etc/odbc.ini

# should contain a section called [MyMSSQLServer]

# install the python driver for database connection
pip install pyodbc

How to find sitemap.xml path on websites?

According to protocol documentation there are at least three options website designers can use to inform sitemap.xml location to search engines:

  • Informing each search engine of the location through their provided interface
  • Adding url to the robots.txt file
  • Submiting url to search engines through http

So, unless they have chosen to publish the sitemap location on their robots.txt file, you cannot really know where they have put their sitemap.xml files.

Slide div left/right using jQuery

$('#hello').hide('slide', {direction: 'left'}, 1000); requires the jQuery-ui library. See http://www.jqueryui.com

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

Force LF eol in git repo and working copy

Starting with git 2.10 (released 2016-09-03), it is not necessary to enumerate each text file separately. Git 2.10 fixed the behavior of text=auto together with eol=lf. Source.

.gitattributes file in the root of your git repository:

* text=auto eol=lf

Add and commit it.

Afterwards, you can do following to steps and all files are normalized now:

git rm --cached -r .  # Remove every file from git's index.
git reset --hard      # Rewrite git's index to pick up all the new line endings.

Source: Answer by kenorb.

Draw Circle using css alone

This will work in all browsers

#circle {
    background: #f00;
    width: 200px;
    height: 200px;
    border-radius: 50%;
    -moz-border-radius: 50%;
    -webkit-border-radius: 50%;
}

How can I count the number of children?

Try to get using:

var count = $("ul > li").size();
alert(count);

How can I clear an HTML file input with JavaScript?

What helped me is, I tried to fetch and upload the last selected file using a loop, instead of clearing out the queue, and it worked. Here is the code.

for (int i = 0; i <= Request.Files.Count-1; i++)
{
 HttpPostedFileBase uploadfile = files[i];
 Stream fs = uploadfile.InputStream;
 BinaryReader br = new BinaryReader(fs);
 Byte[] imageBytes = br.ReadBytes((Int32)fs.Length);
}

Hope this might help some.

Different font size of strings in the same TextView

Use a Spannable String

 String s= "Hello Everyone";
 SpannableString ss1=  new SpannableString(s);
 ss1.setSpan(new RelativeSizeSpan(2f), 0,5, 0); // set size
 ss1.setSpan(new ForegroundColorSpan(Color.RED), 0, 5, 0);// set color
 TextView tv= (TextView) findViewById(R.id.textview);
 tv.setText(ss1); 

Snap shot

enter image description here

You can split string using space and add span to the string you require.

 String s= "Hello Everyone";  
 String[] each = s.split(" ");

Now apply span to the string and add the same to textview.

Browse and display files in a git repo without cloning

The command you want is git ls-remote which allows you to get some information about remote repositories, but you cant show history or list directories or anything of that level: essentially it only lets you see the remote objects at a very high-level (you can see the current HEADs and tags for example).

The only real way to do what you want (if I understand correctly) would be to use ssh to run a remote command and return the results, for example:

ssh me@otherhost "cd repo && git log -n 10"

What you want would be lovely functionality if they could add it, but from what I read it's not very easy since getting history etc needs a lot of information to be local to git, and at that point you may as well have done a git fetch.

When to use an interface instead of an abstract class and vice versa?

When to prefer an abstract class over interface?

  1. If one plans on updating a base class throughout the life of a program/project, it is best to allow that the base class be an abstract class
  2. If one is trying to build a backbone for objects that are closely related in a hierarchy, it is highly beneficial to use an abstract class

When to prefer an interface over abstract class?

  1. If one is not dealing with a massive hierarchical type of framework, interfaces would be a great choice
  2. Because multiple inheritance is not supported with abstract classes(diamond problem), interfaces can save the day

Pass Method as Parameter using C#

If you want to pass Method as parameter, use:

using System;

public void Method1()
{
    CallingMethod(CalledMethod);
}

public void CallingMethod(Action method)
{
    method();   // This will call the method that has been passed as parameter
}

public void CalledMethod()
{
    Console.WriteLine("This method is called by passing parameter");
}

Setting the height of a DIV dynamically

Simplest I could come up...

function resizeResizeableHeight() {
    $('.resizableHeight').each( function() {
        $(this).outerHeight( $(this).parent().height() - ( $(this).offset().top - ( $(this).parent().offset().top + parseInt( $(this).parent().css('padding-top') ) ) ) )
    });
}

Now all you have to do is add the resizableHeight class to everything you want to autosize (to it's parent).

The request was rejected because no multipart boundary was found in springboot

Unchecked the content type in Postman and postman automatically detect the content type based on your input in the run time.

Sample

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

On your backEnd, you should add:

@RequestMapping(value="/blabla",  produces="text/plain" , method = RequestMethod.GET)

On the frontEnd (Service):

methodBlabla() 
{
  const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
  return this.http.get(this.url,{ headers, responseType: 'text'});
}

How to open an existing project in Eclipse?

from Eclipse main gui: select "Window->Show View->Other->General->Project Explorer" Double-clicking on "Project Explorer" brings up the "Project Explorer" window which shows every project in your workspace. That worked for me.

Good luck.

What's the difference between map() and flatMap() methods in Java 8?

Also good analogy can be with C# if you familiar with. Basically C# Select similar to java map and C# SelectMany java flatMap. Same applies to Kotlin for collections.

Generate sql insert script from excel worksheet

I have a reliable way to generate SQL inserts batly,and you can modify partial parameters in processing.It helps me a lot in my work, for example, copy one hundreds data to database with incompatible structure and fields count. IntellIJ DataGrip , the powerful tool i use. DG can batly receive data from WPS office or MS Excel by column or line. after copying, DG can export data as SQL inserts.

How to include header files in GCC search path?

The -I directive does the job:

gcc -Icore -Ianimator -Iimages -Ianother_dir -Iyet_another_dir my_file.c 

How can INSERT INTO a table 300 times within a loop in SQL?

I would prevent loops in general if i can, set approaches are much more efficient:

INSERT INTO tblFoo
  SELECT TOP (300) n = ROW_NUMBER()OVER (ORDER BY [object_id]) 
  FROM sys.all_objects ORDER BY n;

Demo

Generate a set or sequence without loops

What is the difference between baud rate and bit rate?

The bit rate is a measure of the number of bits that are transmitted per unit of time.

The baud rate, which is also known as symbol rate, measures the number of symbols that are transmitted per unit of time. A symbol typically consists of a fixed number of bits depending on what the symbol is defined as(for example 8bit or 9bit data). The baud rate is measured in symbols per second.

Take an example, where an ascii character 'R' is transmitted over a serial channel every one second.

The binary equivalent is 01010010.

So in this case, the baud rate is 1(one symbol transmitted per second) and the bit rate is 8 (eight bits are transmitted per second).

Appending items to a list of lists in python

Python lists are mutable objects and here:

plot_data = [[]] * len(positions) 

you are repeating the same list len(positions) times.

>>> plot_data = [[]] * 3
>>> plot_data
[[], [], []]
>>> plot_data[0].append(1)
>>> plot_data
[[1], [1], [1]]
>>> 

Each list in your list is a reference to the same object. You modify one, you see the modification in all of them.

If you want different lists, you can do this way:

plot_data = [[] for _ in positions]

for example:

>>> pd = [[] for _ in range(3)]
>>> pd
[[], [], []]
>>> pd[0].append(1)
>>> pd
[[1], [], []]

Override and reset CSS style: auto or none don't work

"none" does not do what you assume it does. In order to "clear" a CSS property, you must set it back to its default, which is defined by the CSS standard. Thus you should look up the defaults in your favorite reference.

table.other {
    width: auto;
    min-width: 0;
    display:table;
}

Does reading an entire file leave the file handle open?

Instead of retrieving the file content as a single string, it can be handy to store the content as a list of all lines the file comprises:

with open('Path/to/file', 'r') as content_file:
    content_list = content_file.read().strip().split("\n")

As can be seen, one needs to add the concatenated methods .strip().split("\n") to the main answer in this thread.

Here, .strip() just removes whitespace and newline characters at the endings of the entire file string, and .split("\n") produces the actual list via splitting the entire file string at every newline character \n.

Moreover, this way the entire file content can be stored in a variable, which might be desired in some cases, instead of looping over the file line by line as pointed out in this previous answer.

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

What is private bytes, virtual bytes, working set?

The definition of the perfmon counters has been broken since the beginning and for some reason appears to be too hard to correct.

A good overview of Windows memory management is available in the video "Mysteries of Memory Management Revealed" on MSDN: It covers more topics than needed to track memory leaks (eg working set management) but gives enough detail in the relevant topics.


To give you a hint of the problem with the perfmon counter descriptions, here is the inside story about private bytes from "Private Bytes Performance Counter -- Beware!" on MSDN:

Q: When is a Private Byte not a Private Byte?

A: When it isn't resident.

The Private Bytes counter reports the commit charge of the process. That is to say, the amount of space that has been allocated in the swap file to hold the contents of the private memory in the event that it is swapped out. Note: I'm avoiding the word "reserved" because of possible confusion with virtual memory in the reserved state which is not committed.


From "Performance Planning" on MSDN:

3.3 Private Bytes

3.3.1 Description

Private memory, is defined as memory allocated for a process which cannot be shared by other processes. This memory is more expensive than shared memory when multiple such processes execute on a machine. Private memory in (traditional) unmanaged dlls usually constitutes of C++ statics and is of the order of 5% of the total working set of the dll.

Specified cast is not valid?

Try this:

public void LoadData()
        {
            SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Stocks;Integrated Security=True;Pooling=False");
            SqlDataAdapter sda = new SqlDataAdapter("Select * From [Stocks].[dbo].[product]", con);
            DataTable dt = new DataTable();
            sda.Fill(dt);
            DataGridView1.Rows.Clear();

        foreach (DataRow item in dt.Rows)
        {
            int n = DataGridView1.Rows.Add();
            DataGridView1.Rows[n].Cells[0].Value = item["ProductCode"].ToString();
            DataGridView1.Rows[n].Cells[1].Value = item["Productname"].ToString();
            DataGridView1.Rows[n].Cells[2].Value = item["qty"].ToString();                
            if ((bool)item["productstatus"])
            {
                DataGridView1.Rows[n].Cells[3].Value = "Active";
            }
            else
            {
                DataGridView1.Rows[n].Cells[3].Value = "Deactive";
            }

Is there a good jQuery Drag-and-drop file upload plugin?

http://blueimp.github.com/jQuery-File-Upload/ = great solution

According to their docs, the following browsers support drag & drop:

  • Firefox 4+
  • Safari 5+
  • Google Chrome
  • Microsoft Internet Explorer 10.0+

Get file from project folder java

These lines worked in my case,

ClassLoader classLoader = getClass().getClassLoader();
File fi = new File(classLoader.getResource("test.txt").getFile());

provided test.txt file inside src

Calculate text width with JavaScript

In case anyone else got here looking both for a way to measure the width of a string and a way to know what's the largest font size that will fit in a particular width, here is a function that builds on @Domi's solution with a binary search:

/**
 * Find the largest font size (in pixels) that allows the string to fit in the given width.
 * 
 * @param {String} text - The text to be rendered.
 * @param {String} font - The css font descriptor that text is to be rendered with (e.g. "bold ?px verdana") -- note the use of ? in place of the font size.
 * @param {Number} width - The width in pixels the string must fit in
 * @param {Number} minFontPx - The smallest acceptable font size in pixels
 * @param {Number} maxFontPx - The largest acceptable font size in pixels
 **/
function GetTextSizeForWidth(text, font, width, minFontPx, maxFontPx) {
  for (;;) {
    var s = font.replace("?", maxFontPx);
    var w = GetTextWidth(text, s);
    if (w <= width) {
      return maxFontPx;
    }

    var g = (minFontPx + maxFontPx) / 2;

    if (Math.round(g) == Math.round(minFontPx) || Math.round(g) == Math.round(maxFontPx)) {
      return g;
    }

    s = font.replace("?", g);
    w = GetTextWidth(text, s);
    if (w >= width) {
      maxFontPx = g;
    } else {
      minFontPx = g;
    }
  }
}

Execute combine multiple Linux commands in one line

If you want to execute all the commands, whether the previous one executes or not, you can use semicolon (;) to separate the commands.

cd /my_folder; rm *.jar; svn co path to repo; mvn compile package install

If you want to execute the next command only if the previous command succeeds, then you can use && to separate the commands.

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

In your case, the execution of consecutive commands seems to depend upon the previous commands, so use the second example i.e. use && to join the commands.

ClassCastException, casting Integer to Double

Changing an integer to a double

int abc=12; //setting up integer "abc"

System.out.println((double)abc); 

The code will output integer "abc" as a double, which means that it will display as "12.0". Notice how there is a decimal place, indicating that this precision digit has been stored.

Same with double if you want to change it back,

double number=13.94;

System.out.println((int)number); 

This code will print on one line, "number" as an integer. The output will be "13". Notice that the value has not been rounded up, the data has actually been omitted.

grep without showing path/file:line

From the man page:

-h, --no-filename
    Suppress the prefixing of file names on output. This is the default when there
    is only one file (or only standard input) to search.

jQuery scroll to element

If you are only handling scrolling to an input element, you can use focus(). For example, if you wanted to scroll to the first visible input:

$(':input:visible').first().focus();

Or the first visible input in an container with class .error:

$('.error :input:visible').first().focus();

Thanks to Tricia Ball for pointing this out!

How to enable bulk permission in SQL Server

Try this:

USE master;

GO;
 
GRANT ADMINISTER BULK OPERATIONS TO shira;

Insert json file into mongodb

This worked for me - ( from mongo shell )

var file = cat('./new.json');     # file name
use testdb                        # db name
var o = JSON.parse(file);         # convert string to JSON
db.forms.insert(o)                # collection name

How to clear variables in ipython?

An quit option in the Console Panel will also clear all variables in variable explorer

*** Note that you will be loosing all the code which you have run in Console Panel

Access-Control-Allow-Origin and Angular.js $http

Writing this middleware might help !

app.use(function(req, res, next) {
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "Origin, X-Requested-With,     Content-Type, Accept");
next();
});

for details visit http://enable-cors.org/server_expressjs.html

How to install numpy on windows using pip install?

Frustratingly the Numpy package published to PyPI won't install on most Windows computers https://github.com/numpy/numpy/issues/5479

Instead:

  1. Download the Numpy wheel for your Python version from http://www.lfd.uci.edu/~gohlke/pythonlibs/#numpy
  2. Install it from the command line pip install numpy-1.10.2+mkl-cp35-none-win_amd64.whl

Generate unique random numbers between 1 and 100

var bombout=0;
var checkArr=[];
var arr=[];
while(arr.length < 8 && bombout<100){
  bombout++;
  var randomNumber=Math.ceil(Math.random()*100);
  if(typeof checkArr[randomNumber] == "undefined"){
    checkArr[randomNumber]=1;
    arr.push(randomNumber);
  }
}?

// untested - hence bombout

How does the JPA @SequenceGenerator annotation work

Now, back to your questions:

Q1. Does this sequence generator make use of the database's increasing numeric value generating capability or generates the number on its own?

By using the GenerationType.SEQUENCE strategy on the @GeneratedValue annotation, the JPA provider will try to use a database sequence object of the underlying database that supports this feature (e.g., Oracle, SQL Server, PostgreSQL, MariaDB).

If you are using MySQL, which doesn't support database sequence objects, then Hibernate is going to fall back to using the GenerationType.TABLE instead, which is undesirable since the TABLE generation performs badly.

So, don't use the GenerationType.SEQUENCE strategy with MySQL.

Q2. If JPA uses a database auto-increment feature, then will it work with datastores that don't have auto-increment feature?

I assume you are talking about the GenerationType.IDENTITY when you say database auto-increment feature.

To use an AUTO_INCREMENT or IDENTITY column, you need to use the GenerationType.IDENTITYstrategy on the @GeneratedValue annotation.

Q3. If JPA generates numeric value on its own, then how does the JPA implementation know which value to generate next? Does it consult with the database first to see what value was stored last in order to generate the value (last + 1)?

The only time when the JPA provider generates values on its own is when you are using the sequence-based optimizers, like:

These optimizers are meat to reduce the number of database sequence calls, so they multiply the number of identifier values that can be generated using a single database sequence call.

To avoid conflicts between Hibernate identifier optimizers and other 3rd-party clients, you should use pooled or pooled-lo instead of hi/lo. Even if you are using a legacy application that was designed to use hi/lo, you can migrate to the pooled or pooled-lo optimizers.

Q4. Please also shed some light on sequenceName and allocationSize properties of @SequenceGenerator annotation.

The sequenceName attribute defines the database sequence object to be used to generate the identifier values. IT's the object you created using the CREATE SEQUENCE DDL statement.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post"
)
private Long id;

Hibernate is going to use the seq_post database object to generate the identifier values:

SELECT nextval('hibernate_sequence')

The allocationSize defines the identifier value multiplier, and if you provide a value that's greater than 1, then Hibernate is going to use the pooled optimizer, to reduce the number of database sequence calls.

So, if you provide this mapping:

@Id
@GeneratedValue(
    strategy = GenerationType.SEQUENCE,
    generator = "seq_post"
)
@SequenceGenerator(
    name = "seq_post",
    allocationSize = 5
)
private Long id;

Then, when you persist 5 entities:

for (int i = 1; i <= 5; i++) {
    entityManager.persist(
        new Post().setTitle(
            String.format(
                "High-Performance Java Persistence, Part %d",
                i
            )
        )
    );
}

Only 2 database sequence calls will be executed, instead of 5:

SELECT nextval('hibernate_sequence')
SELECT nextval('hibernate_sequence')
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 1', 1)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 2', 2)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 3', 3)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 4', 4)
 
INSERT INTO post (title, id)
VALUES ('High-Performance Java Persistence, Part 5', 5)

Java ArrayList of Arrays?

Since the size of your string array is fixed at compile time, you'd be better off using a structure (like Pair) that mandates exactly two fields, and thus avoid the runtime errors possible with the array approach.

Code:

Since Java doesn't supply a Pair class, you'll need to define your own.

class Pair<A, B> {
  public final A first;
  public final B second;

  public Pair(final A first, final B second) {
    this.first = first;
    this.second = second;
  }

  //
  // Override 'equals', 'hashcode' and 'toString'
  //
}

and then use it as:

List<Pair<String, String>> action = new ArrayList<Pair<String, String>>();

[ Here I used List because it's considered a good practice to program to interfaces. ]

What are the differences between type() and isinstance()?

For the real differences, we can find it in code, but I can't find the implement of the default behavior of the isinstance().

However we can get the similar one abc.__instancecheck__ according to __instancecheck__.

From above abc.__instancecheck__, after using test below:

# file tree
# /test/__init__.py
# /test/aaa/__init__.py
# /test/aaa/aa.py
class b():
pass

# /test/aaa/a.py
import sys
sys.path.append('/test')

from aaa.aa import b
from aa import b as c

d = b()

print(b, c, d.__class__)
for i in [b, c, object]:
    print(i, '__subclasses__',  i.__subclasses__())
    print(i, '__mro__', i.__mro__)
    print(i, '__subclasshook__', i.__subclasshook__(d.__class__))
    print(i, '__subclasshook__', i.__subclasshook__(type(d)))
print(isinstance(d, b))
print(isinstance(d, c))

<class 'aaa.aa.b'> <class 'aa.b'> <class 'aaa.aa.b'>
<class 'aaa.aa.b'> __subclasses__ []
<class 'aaa.aa.b'> __mro__ (<class 'aaa.aa.b'>, <class 'object'>)
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aaa.aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasses__ []
<class 'aa.b'> __mro__ (<class 'aa.b'>, <class 'object'>)
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'aa.b'> __subclasshook__ NotImplemented
<class 'object'> __subclasses__ [..., <class 'aaa.aa.b'>, <class 'aa.b'>]
<class 'object'> __mro__ (<class 'object'>,)
<class 'object'> __subclasshook__ NotImplemented
<class 'object'> __subclasshook__ NotImplemented
True
False

I get this conclusion, For type:

# according to `abc.__instancecheck__`, they are maybe different! I have not found negative one 
type(INSTANCE) ~= INSTANCE.__class__
type(CLASS) ~= CLASS.__class__

For isinstance:

# guess from `abc.__instancecheck__`
return any(c in cls.__mro__ or c in cls.__subclasses__ or cls.__subclasshook__(c) for c in {INSTANCE.__class__, type(INSTANCE)})

BTW: better not to mix use relative and absolutely import, use absolutely import from project_dir( added by sys.path)

Django database query: How to get object by id?

I got here for the same problem, but for a different reason:

Class.objects.get(id=1)

This code was raising an ImportError exception. What was confusing me was that the code below executed fine and returned a result set as expected:

Class.objects.all()

Tail of the traceback for the get() method:

File "django/db/models/loading.py", line 197, in get_models
    self._populate()
File "django/db/models/loading.py", line 72, in _populate
    self.load_app(app_name, True)
File "django/db/models/loading.py", line 94, in load_app
    app_module = import_module(app_name)
File "django/utils/importlib.py", line 35, in import_module
    __import__(name)
ImportError: No module named myapp

Reading the code inside Django's loading.py, I came to the conclusion that my settings.py had a bad path to my app which contains my Class model definition. All I had to do was correct the path to the app and the get() method executed fine.

Here is my settings.py with the corrected path:

INSTALLED_APPS = (
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.sites',
    # ...
    'mywebproject.myapp',

)

All the confusion was caused because I am using Django's ORM as a standalone, so the namespace had to reflect that.

GitHub relative link in Markdown file

Just wanted to add this because none of the above solutions worked if target link is directory with spaces in it's name. If target link is a directory and it has space then even escaping space with \ doesn't render the link on Github. Only solution worked for me is using %20 for each space.

e.g.: if directory structure is this

Top_dir
|-----README.md
|-----Cur_dir1
      |----Dir A
           |----README.md
      |----Dir B
           |----README.md

To make link to Dir A in README.md present in Top_dir you can do this:

[Dir 1](Cur_dir1/Dir%20A)

Set Canvas size using javascript

You can set the width like this :

function draw() {
  var ctx = (a canvas context);
  ctx.canvas.width  = window.innerWidth;
  ctx.canvas.height = window.innerHeight;
  //...drawing code...
}

Check if table exists and if it doesn't exist, create it in SQL Server 2008

EDITED

You can look into sys.tables for checking existence desired table:

IF  NOT EXISTS (SELECT * FROM sys.tables
WHERE name = N'YourTable' AND type = 'U')

BEGIN
CREATE TABLE [SchemaName].[YourTable](
    ....
    ....
    ....
) 

END

SQL ROWNUM how to return rows between a specific range

select * 
from emp 
where rownum <= &upperlimit 
minus 
select * 
from emp 
where rownum <= &lower limit ;

What is the difference between private and protected members of C++ classes?

Since no public member function is needed to fetch and update protected members in the derived class, this increases the efficiency of code and reduces the amount of code we need to write. However, programmer of the derived class is supposed to be aware of what he is doing.

Java method to sum any number of ints

public int sumAll(int... nums) { //var-args to let the caller pass an arbitrary number of int
    int sum = 0; //start with 0
    for(int n : nums) { //this won't execute if no argument is passed
        sum += n; // this will repeat for all the arguments
    }
    return sum; //return the sum
} 

What is a good pattern for using a Global Mutex in C#?

A global Mutex is not only to ensure to have only one instance of an application. I personally prefer using Microsoft.VisualBasic to ensure single instance application like described in What is the correct way to create a single-instance WPF application? (Dale Ragan answer)... I found that's easier to pass arguments received on new application startup to the initial single instance application.

But regarding some previous code in this thread, I would prefer to not create a Mutex each time I want to have a lock on it. It could be fine for a single instance application but in other usage it appears to me has overkill.

That's why I suggest this implementation instead:

Usage:

static MutexGlobal _globalMutex = null;
static MutexGlobal GlobalMutexAccessEMTP
{
    get
    {
        if (_globalMutex == null)
        {
            _globalMutex = new MutexGlobal();
        }
        return _globalMutex;
    }
}

using (GlobalMutexAccessEMTP.GetAwaiter())
{
    ...
}   

Mutex Global Wrapper:

using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Security.AccessControl;
using System.Security.Principal;
using System.Threading;

namespace HQ.Util.General.Threading
{
    public class MutexGlobal : IDisposable
    {
        // ************************************************************************
        public string Name { get; private set; }
        internal Mutex Mutex { get; private set; }
        public int DefaultTimeOut { get; set; }
        public Func<int, bool> FuncTimeOutRetry { get; set; }

        // ************************************************************************
        public static MutexGlobal GetApplicationMutex(int defaultTimeOut = Timeout.Infinite)
        {
            return new MutexGlobal(defaultTimeOut, ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value);
        }

        // ************************************************************************
        public MutexGlobal(int defaultTimeOut = Timeout.Infinite, string specificName = null)
        {
            try
            {
                if (string.IsNullOrEmpty(specificName))
                {
                    Name = Guid.NewGuid().ToString();
                }
                else
                {
                    Name = specificName;
                }

                Name = string.Format("Global\\{{{0}}}", Name);

                DefaultTimeOut = defaultTimeOut;

                FuncTimeOutRetry = DefaultFuncTimeOutRetry;

                var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
                var securitySettings = new MutexSecurity();
                securitySettings.AddAccessRule(allowEveryoneRule);

                Mutex = new Mutex(false, Name, out bool createdNew, securitySettings);

                if (Mutex == null)
                {
                    throw new Exception($"Unable to create mutex: {Name}");
                }
            }
            catch (Exception ex)
            {
                Log.Log.Instance.AddEntry(Log.LogType.LogException, $"Unable to create Mutex: {Name}", ex);
                throw;
            }
        }

        // ************************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public MutexGlobalAwaiter GetAwaiter(int timeOut)
        {
            return new MutexGlobalAwaiter(this, timeOut);
        }

        // ************************************************************************
        /// <summary>
        /// 
        /// </summary>
        /// <param name="timeOut"></param>
        /// <returns></returns>
        public MutexGlobalAwaiter GetAwaiter()
        {
            return new MutexGlobalAwaiter(this, DefaultTimeOut);
        }

        // ************************************************************************
        /// <summary>
        /// This method could either throw any user specific exception or return 
        /// true to retry. Otherwise, retruning false will let the thread continue
        /// and you should verify the state of MutexGlobalAwaiter.HasTimedOut to 
        /// take proper action depending on timeout or not. 
        /// </summary>
        /// <param name="timeOutUsed"></param>
        /// <returns></returns>
        private bool DefaultFuncTimeOutRetry(int timeOutUsed)
        {
            // throw new TimeoutException($"Mutex {Name} timed out {timeOutUsed}.");

            Log.Log.Instance.AddEntry(Log.LogType.LogWarning, $"Mutex {Name} timeout: {timeOutUsed}.");
            return true; // retry
        }

        // ************************************************************************
        public void Dispose()
        {
            if (Mutex != null)
            {
                Mutex.ReleaseMutex();
                Mutex.Close();
            }
        }

        // ************************************************************************

    }
}

Awaiter

using System;

namespace HQ.Util.General.Threading
{
    public class MutexGlobalAwaiter : IDisposable
    {
        MutexGlobal _mutexGlobal = null;

        public bool HasTimedOut { get; set; } = false;

        internal MutexGlobalAwaiter(MutexGlobal mutexEx, int timeOut)
        {
            _mutexGlobal = mutexEx;

            do
            {
                HasTimedOut = !_mutexGlobal.Mutex.WaitOne(timeOut, false);
                if (! HasTimedOut) // Signal received
                {
                    return;
                }
            } while (_mutexGlobal.FuncTimeOutRetry(timeOut));
        }

        #region IDisposable Support
        private bool disposedValue = false; // To detect redundant calls

        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    _mutexGlobal.Mutex.ReleaseMutex();
                }

                // TODO: free unmanaged resources (unmanaged objects) and override a finalizer below.
                // TODO: set large fields to null.

                disposedValue = true;
            }
        }
        // TODO: override a finalizer only if Dispose(bool disposing) above has code to free unmanaged resources.
        // ~MutexExAwaiter()
        // {
        //   // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
        //   Dispose(false);
        // }

        // This code added to correctly implement the disposable pattern.
        public void Dispose()
        {
            // Do not change this code. Put cleanup code in Dispose(bool disposing) above.
            Dispose(true);
            // TODO: uncomment the following line if the finalizer is overridden above.
            // GC.SuppressFinalize(this);
        }
        #endregion
    }
}

exec failed because the name not a valid identifier?

Try this instead in the end:

exec (@query)

If you do not have the brackets, SQL Server assumes the value of the variable to be a stored procedure name.

OR

EXECUTE sp_executesql @query

And it should not be because of FULL JOIN.
But I hope you have already created the temp tables: #TrafficFinal, #TrafficFinal2, #TrafficFinal3 before this.


Please note that there are performance considerations between using EXEC and sp_executesql. Because sp_executesql uses forced statement caching like an sp.
More details here.


On another note, is there a reason why you are using dynamic sql for this case, when you can use the query as is, considering you are not doing any query manipulations and executing it the way it is?

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

phpMyAdmin ERROR: mysqli_real_connect(): (HY000/1045): Access denied for user 'pma'@'localhost' (using password: NO)

I just finished setting up my XAMPP on the MAC and had the same trouble. I just fixed it. It is not quite clear what OS you're using but you need to run the XAMPP security. You indicate you've done that, but here it is anyway for the MAC

sudo /Applications/XAMPP/xamppfiles/xampp security 

Set your password on the questions you get.

In you're phpmyadmin import the "create_tables.sql" .. Which can be found in the ./phpmyadmin/sql folder.

Next open the config.inc.php file inside the ./phpmyadmin folder.

$cfg['Servers'][$i]['controluser'] = 'pma';
$cfg['Servers'][$i]['controlpass'] = 'you_password';

Make sure to log out and log in to reflect the changes within phpmyadmin

Google MAP API Uncaught TypeError: Cannot read property 'offsetWidth' of null

add async defer at the begining of map api key call.

cast a List to a Collection

Not knowing your code, it's a bit hard to answer your question, but based on all the info here, I believe the issue is you're trying to use Collections.sort passing in an object defined as Collection, and sort doesn't support that.

First question. Why is client defined so generically? Why isn't it a List, Map, Set or something a little more specific?

If client was defined as a List, Map or Set, you wouldn't have this issue, as then you'd be able to directly use Collections.sort(client).

HTH

Can I store images in MySQL

You will need to store the image in the database as a BLOB.

you will want to create a column called PHOTO in your table and set it as a mediumblob.

Then you will want to get it from the form like so:

    $data = file_get_contents($_FILES['photo']['tmp_name']);

and then set the column to the value in $data.

Of course, this is bad practice and you would probably want to store the file on the system with a name that corresponds to the users account.

'dict' object has no attribute 'has_key'

has_key has been deprecated in Python 3.0. Alternatively you can use 'in'

graph={'A':['B','C'],
   'B':['C','D']}

print('A' in graph)
>> True

print('E' in graph)
>> False

Setting the MySQL root user password on OS X

Try the command FLUSH PRIVILEGES when you log into the MySQL terminal. If that doesn't work, try the following set of commands while in the MySQL terminal

$ mysql -u root
mysql> USE mysql;
mysql> UPDATE user SET password=PASSWORD("NEWPASSWORD") WHERE User='root';
mysql> FLUSH PRIVILEGES;
mysql> quit

Change out NEWPASSWORD with whatever password you want. Should be all set!

Update: As of MySQL 5.7, the password field has been renamed authentication_string. When changing the password, use the following query to change the password. All other commands remain the same:

mysql> UPDATE user SET authentication_string=PASSWORD("NEWPASSWORD") WHERE User='root';

Update: On 8.0.15 (maybe already before that version) the PASSWORD() function does not work, as mentioned in the comments below. You have to use:

UPDATE mysql.user SET authentication_string='password' WHERE User='root';

How does Java handle integer underflows and overflows and how would you check for it?

There are libraries that provide safe arithmetic operations, which check integer overflow/underflow . For example, Guava's IntMath.checkedAdd(int a, int b) returns the sum of a and b, provided it does not overflow, and throws ArithmeticException if a + b overflows in signed int arithmetic.

A fatal error occurred while creating a TLS client credential. The internal error state is 10013

I found this here: https://port135.com/schannel-the-internal-error-state-is-10013-solved/

"Correct file permissions Correct the permissions on the c:\ProgramData\Microsoft\Crypto\RSA\MachineKeys folder:

Everyone Access: Special Applies to 'This folder only' Network Service Access: Read & Execute Applies to 'This folder, subfolders and files' Administrators Access: Full Control Applies to 'This folder, subfolder and files' System Access: Full control Applies to 'This folder, subfolder and Files' IUSR Access: Full Control Applies to 'This folder, subfolder and files' The internal error state is 10013 After these changes, restart the server. The 10013 errors should disappear."

Excel VBA: Copying multiple sheets into new workbook

Rethink your approach. Why would you copy only part of the sheet? You are referring to a named range "WholePrintArea" which doesn't exist. Also you should never use activate, select, copy or paste in your script. These make the "script" vulnerable to user actions and other simultaneous executions. In worst case scenario data ends up in wrong hands.

ng-repeat :filter by single field

If you want to filter on a grandchild (or deeper) of the given object, you can continue to build out your object hierarchy. For example, if you want to filter on 'thing.properties.title', you can do the following:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter } }">

You can also filter on multiple properties of an object just by adding them to your filter object:

<div ng-repeat="thing in things | filter: { properties: { title: title_filter, id: id_filter } }">

Get exit code for command in bash/ksh

Below is the fixed code:

#!/bin/ksh
safeRunCommand() {
  typeset cmnd="$*"
  typeset ret_code

  echo cmnd=$cmnd
  eval $cmnd
  ret_code=$?
  if [ $ret_code != 0 ]; then
    printf "Error : [%d] when executing command: '$cmnd'" $ret_code
    exit $ret_code
  fi
}

command="ls -l | grep p"
safeRunCommand "$command"

Now if you look into this code few things that I changed are:

  • use of typeset is not necessary but a good practice. It make cmnd and ret_code local to safeRunCommand
  • use of ret_code is not necessary but a good practice to store return code in some variable (and store it ASAP) so that you can use it later like I did in printf "Error : [%d] when executing command: '$command'" $ret_code
  • pass the command with quotes surrounding the command like safeRunCommand "$command". If you dont then cmnd will get only the value ls and not ls -l. And it is even more important if your command contains pipes.
  • you can use typeset cmnd="$*" instead of typeset cmnd="$1" if you want to keep the spaces. You can try with both depending upon how complex is your command argument.
  • eval is used to evaluate so that command containing pipes can work fine

NOTE: Do remember some commands give 1 as return code even though there is no error like grep. If grep found something it will return 0 else 1.

I had tested with KSH/BASH. And it worked fine. Let me know if u face issues running this.

How to create and add users to a group in Jenkins for authentication?

You could use Role Strategy plugin for that purpose. It works like a charm, just setup some roles and assign them. Even on project-specific level.

How to trigger a phone call when clicking a link in a web page on mobile phone

Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a> and you should be good to go.

If you want to use it for an image, the <a> tag can handle the <img/> placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>

Is it possible to remove the hand cursor that appears when hovering over a link? (or keep it set as the normal pointer)

<style>
a{
cursor: default;
}
</style>

In the above code [cursor:default] is used. Default is the usual arrow cursor that appears.

And if you use [cursor: pointer] then you can access to the hand like cursor that appears when you hover over a link.

To know more about cursors and their appearance click the below link: https://www.w3schools.com/cssref/pr_class_cursor.asp

How to style the menu items on an Android action bar

BottomNavigationView navigation = (BottomNavigationView) findViewById(R.id.navigation);

    TextView textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.smallLabel);
    textView.setTypeface(Typeface.DEFAULT_BOLD);
    textView = (TextView) navigation.findViewById(R.id.navigation_home).findViewById(R.id.largeLabel);
    textView.setTypeface(Typeface.DEFAULT_BOLD);

What does Java option -Xmx stand for?

C:\java -X

    -Xmixed           mixed mode execution (default)
    -Xint             interpreted mode execution only
    -Xbootclasspath:<directories and zip/jar files separated by ;>
                      set search path for bootstrap classes and resources
    -Xbootclasspath/a:<directories and zip/jar files separated by ;>
                      append to end of bootstrap class path
    -Xbootclasspath/p:<directories and zip/jar files separated by ;>
                      prepend in front of bootstrap class path
    -Xnoclassgc       disable class garbage collection
    -Xincgc           enable incremental garbage collection
    -Xloggc:<file>    log GC status to a file with time stamps
    -Xbatch           disable background compilation
    -Xms<size>        set initial Java heap size
    -Xmx<size>        set maximum Java heap size
    -Xss<size>        set java thread stack size
    -Xprof            output cpu profiling data
    -Xfuture          enable strictest checks, anticipating future default
    -Xrs              reduce use of OS signals by Java/VM (see documentation)
    -Xcheck:jni       perform additional checks for JNI functions
    -Xshare:off       do not attempt to use shared class data
    -Xshare:auto      use shared class data if possible (default)
    -Xshare:on        require using shared class data, otherwise fail.

The -X options are non-standard and subject to change without notice.

Daemon Threads Explanation

Some threads do background tasks, like sending keepalive packets, or performing periodic garbage collection, or whatever. These are only useful when the main program is running, and it's okay to kill them off once the other, non-daemon, threads have exited.

Without daemon threads, you'd have to keep track of them, and tell them to exit, before your program can completely quit. By setting them as daemon threads, you can let them run and forget about them, and when your program quits, any daemon threads are killed automatically.

Implementing SearchView in action bar

SearchDialog or SearchWidget ?

When it comes to implement a search functionality there are two suggested approach by official Android Developer Documentation.
You can either use a SearchDialog or a SearchWidget.
I am going to explain the implementation of Search functionality using SearchWidget.

How to do it with Search widget ?

I will explain search functionality in a RecyclerView using SearchWidget. It's pretty straightforward.

Just follow these 5 Simple steps

1) Add searchView item in the menu

You can add SearchView can be added as actionView in menu using

app:useActionClass = "android.support.v7.widget.SearchView" .

<menu xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools"
   tools:context="rohksin.com.searchviewdemo.MainActivity">
   <item
       android:id="@+id/searchBar"
       app:showAsAction="always"
       app:actionViewClass="android.support.v7.widget.SearchView"
   />
</menu>

2) Set up SerchView Hint text, listener etc

You should initialize SearchView in the onCreateOptionsMenu(Menu menu) method.

  @Override
  public boolean onCreateOptionsMenu(Menu menu) {
     // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);

        MenuItem searchItem = menu.findItem(R.id.searchBar);

        SearchView searchView = (SearchView) searchItem.getActionView();
        searchView.setQueryHint("Search People");
        searchView.setOnQueryTextListener(this);
        searchView.setIconified(false);

        return true;
   }

3) Implement SearchView.OnQueryTextListener in your Activity

OnQueryTextListener has two abstract methods

  1. onQueryTextSubmit(String query)
  2. onQueryTextChange(String newText

So your Activity skeleton would look like this

YourActivity extends AppCompatActivity implements SearchView.OnQueryTextListener{

     public boolean onQueryTextSubmit(String query)

     public boolean onQueryTextChange(String newText) 

}

4) Implement SearchView.OnQueryTextListener

You can provide the implementation for the abstract methods like this

public boolean onQueryTextSubmit(String query) {

    // This method can be used when a query is submitted eg. creating search history using SQLite DB

    Toast.makeText(this, "Query Inserted", Toast.LENGTH_SHORT).show();
    return true;
}

@Override
public boolean onQueryTextChange(String newText) {

    adapter.filter(newText);
    return true;
}

5) Write a filter method in your RecyclerView Adapter.

Most important part. You can write your own logic to perform search.
Here is mine. This snippet shows the list of Name which contains the text typed in the SearchView

public void filter(String queryText)
{
    list.clear();

    if(queryText.isEmpty())
    {
       list.addAll(copyList);
    }
    else
    {

       for(String name: copyList)
       {
           if(name.toLowerCase().contains(queryText.toLowerCase()))
           {
              list.add(name);
           }
       }

    }

   notifyDataSetChanged();
}

Relevant link:

Full working code on SearchView with an SQLite database in this Music App

Direct casting vs 'as' operator?

Use direct cast string s = (string) o; if in the logical context of your app string is the only valid type. With this approach, you will get InvalidCastException and implement the principle of Fail-fast. Your logic will be protected from passing the invalid type further or get NullReferenceException if used as operator.

If the logic expects several different types cast string s = o as string; and check it on null or use is operator.

New cool feature have appeared in C# 7.0 to simplify cast and check is a Pattern matching:

if(o is string s)
{
  // Use string variable s
}

or

switch (o)
{
  case int i:
     // Use int variable i
     break;
  case string s:
     // Use string variable s
     break;
 }

Store an array in HashMap

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

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

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

In Visual Basic how do you create a block comment

In Visual Studio .NET you can do Ctrl + K then C to comment, Crtl + K then U to uncomment a block.

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

As a side-note...this can also happen when there is a problem with (internal) data-mapping from SQL Objects.

For instance...

I created a SQL Scalar Function that accidentally returned a VARCHAR...and then...used it to generate a column in a VIEW. The VIEW was correctly mapped in the DbContext...so Linq was calling it just fine. However, the Entity expected DateTime? and the VIEW was returning String.

Which ODDLY throws...

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

It was hard to figure out...but after I corrected the return parameters...all was well

How can I get the current directory name in Javascript?

window.location.pathname will get you the directory, as well as the page name. You could then use .substring() to get the directory:

var loc = window.location.pathname;
var dir = loc.substring(0, loc.lastIndexOf('/'));

Hope this helps!

In c++ what does a tilde "~" before a function name signify?

It's the destructor, it destroys the instance, frees up memory, etc. etc.

Here's a description from ibm.com:

Destructors are usually used to deallocate memory and do other cleanup for a class object and its class members when the object is destroyed. A destructor is called for a class object when that object passes out of scope or is explicitly deleted.

See https://www.ibm.com/support/knowledgecenter/en/ssw_ibm_i_74/rzarg/cplr380.htm

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

How to print Boolean flag in NSLog?

We can check by Four ways

The first way is

BOOL flagWayOne = TRUE; 
NSLog(@"The flagWayOne result is - %@",flagWayOne ? @"TRUE":@"FALSE");

The second way is

BOOL flagWayTwo = YES; 
NSLog(@"The flagWayTwo result is - %@",flagWayTwo ? @"YES":@"NO");

The third way is

BOOL flagWayThree = 1;
NSLog(@"The flagWayThree result is - %d",flagWayThree ? 1:0);

The fourth way is

BOOL flagWayFour = FALSE; // You can set YES or NO here.Because TRUE = YES,FALSE = NO and also 1 is equal to YES,TRUE and 0 is equal to FALSE,NO whatever you want set here.
NSLog(@"The flagWayFour result is - %s",flagWayFour ? YES:NO);

Removing Data From ElasticSearch

You can delete the index by Kibana Console:

Console Icon

To get all index:

GET /_cat/indices?v

To delete a specific index:

DELETE /INDEX_NAME_TO_DELETE

What is the best way to add options to a select from a JavaScript object with jQuery?

If you don't have to support old IE versions, using the Option constructor is clearly the way to go, a readable and efficient solution:

$(new Option('myText', 'val')).appendTo('#mySelect');

It's equivalent in functionality to, but cleaner than:

$("<option></option>").attr("value", "val").text("myText")).appendTo('#mySelect');

IntelliJ IDEA shows errors when using Spring's @Autowired annotation

Make sure that your IntelliJ Idea (IDE) is aware of all the necessary spring configurations that your module is being inspected against.

You can check this under

File > Project Structure > Modules > [your project name in the right panel] > Spring

Sometimes, we need to explicitly tell the IDE that the spring configuration is coming from a dependency (a jar present in your project classpath)

How can I find the dimensions of a matrix in Python?

If you are using NumPy arrays, shape can be used. For example

  >>> a = numpy.array([[[1,2,3],[1,2,3]],[[12,3,4],[2,1,3]]])
  >>> a
  array([[[ 1,  2,  3],
         [ 1,  2,  3]],

         [[12,  3,  4],
         [ 2,  1,  3]]])
 >>> a.shape
 (2, 2, 3)

Unclosed Character Literal error

Character only takes one value dude! like: char y = 'h'; and maybe you typed like char y = 'hello'; or smthg. good luck. for the question asked above the answer is pretty simple u have to use DOUBLE QUOTES to give a string value. easy enough;)

My C# application is returning 0xE0434352 to Windows Task Scheduler but it is not crashing

In case it helps others, I got this error when the service the task was running at didn't have write permission to the executable location. It was attempting to write a log file there.

How do I read a resource file from a Java jar file?

You don't say if this is a desktop or web app. I would use the getResourceAsStream() method from an appropriate ClassLoader if it's a desktop or the Context if it's a web app.

Comparing double values in C#

You need a combination of Math.Abs on X-Y and a value to compare with.

You can use following Extension method approach

public static class DoubleExtensions
    {
        const double _3 = 0.001;
        const double _4 = 0.0001;
        const double _5 = 0.00001;
        const double _6 = 0.000001;
        const double _7 = 0.0000001;

        public static bool Equals3DigitPrecision(this double left, double right)
        {
            return Math.Abs(left - right) < _3;
        }

        public static bool Equals4DigitPrecision(this double left, double right)
        {
            return Math.Abs(left - right) < _4;
        }

        ...

Since you rarely call methods on double except ToString I believe its pretty safe extension.

Then you can compare x and y like

if(x.Equals4DigitPrecision(y))

MySQL FULL JOIN?

Various types of joins, for illustration

There are a couple of methods for full mysql FULL [OUTER] JOIN.

  1. UNION a left join and right join. UNION will remove duplicates by performing an ORDER BY operation. So depending on your data, it may not be performant.

     SELECT * FROM A 
       LEFT JOIN B ON A.key = B.key 
    
     UNION 
    
     SELECT * FROM A 
       RIGHT JOIN B ON A.key = B.key
    
  2. UNION ALL a left join and right EXCLUDING join (that's the lower right figure in the diagram). UNION ALL will not remove duplicates. Sometimes this might be the behaviour that you want. You also want to use RIGHT EXCLUDING to avoid duplicating common records from selection A and selection B - i.e Left join has already included common records from selection B, lets not repeat that again with the right join.

     SELECT * FROM A 
       LEFT JOIN B ON A.key = B.key 
    
     UNION ALL
    
     SELECT * FROM A 
       RIGHT JOIN B ON A.key = B.key
       WHERE A.key IS NULL
    

FIFO based Queue implementations?

A LinkedList can be used as a Queue - but you need to use it right. Here is an example code :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.add(1);
    queue.add(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

1
2

Remember, if you use push instead of add ( which you will very likely do intuitively ), this will add element at the front of the list, making it behave like a stack.

So this is a Queue only if used in conjunction with add.

Try this :

@Test
public void testQueue() {
    LinkedList<Integer> queue = new LinkedList<>();
    queue.push(1);
    queue.push(2);
    System.out.println(queue.pop());
    System.out.println(queue.pop());
}

Output :

2
1

Technically what is the main difference between Oracle JDK and OpenJDK?

OpenJDK is a reference model and open source, while Oracle JDK is an implementation of the OpenJDK and is not open source. Oracle JDK is more stable than OpenJDK.

OpenJDK is released under GPL v2 license whereas Oracle JDK is licensed under Oracle Binary Code License Agreement.

OpenJDK and Oracle JDK have almost the same code, but Oracle JDK has more classes and some bugs fixed.

So if you want to develop enterprise/commercial software I would suggest to go for Oracle JDK, as it is thoroughly tested and stable.

I have faced lot of problems with application crashes using OpenJDK, which are fixed just by switching to Oracle JDK

How to use a SQL SELECT statement with Access VBA

Here is another way to use SQL SELECT statement in VBA:

 sSQL = "SELECT Variable FROM GroupTable WHERE VariableCode = '" & Me.comboBox & "'" 
 Set rs = CurrentDb.OpenRecordset(sSQL)
 On Error GoTo resultsetError 
 dbValue = rs!Variable
 MsgBox dbValue, vbOKOnly, "RS VALUE"
resultsetError:
 MsgBox "Error Retrieving value from database",VbOkOnly,"Database Error"

Darkening an image with CSS (In any shape)

You could always change the opacity of the image, given the difficulty of any alternatives this might be the best approach.

CSS:

.tinted { opacity: 0.8; }

If you're interested in better browser compatability, I suggest reading this:

http://css-tricks.com/css-transparency-settings-for-all-broswers/

If you're determined enough you can get this working as far back as IE7 (who knew!)

Note: As JGonzalezD points out below, this only actually darkens the image if the background colour is generally darker than the image itself. Although this technique may still be useful if you don't specifically want to darken the image, but instead want to highlight it on hover/focus/other state for whatever reason.

Using group by and having clause

What type of sql database are using (MSSQL, Oracle etc)? I believe what you have written is correct.

You could also write the first query like this:

SELECT s.sid, s.name
FROM Supplier s
WHERE (SELECT COUNT(DISTINCT pr.jid)
       FROM Supplies su, Projects pr
       WHERE su.sid = s.sid 
           AND pr.jid = su.jid) >= 2

It's a little more readable, and less mind-bending than trying to do it with GROUP BY. Performance may differ though.