Programs & Examples On #Jsdt

JSDT known as Javascript Development Tools is a part of the Web Tools Platform in the Eclipse IDE.

Python safe method to get value of nested dictionary

A solution I've used that is similar to the double get but with the additional ability to avoid a TypeError using if else logic:

    value = example_dict['key1']['key2'] if example_dict.get('key1') and example_dict['key1'].get('key2') else default_value

However, the more nested the dictionary the more cumbersome this becomes.

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).

Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to use build:

  • job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
    • Use a simple name if the job is in the same folder as this upstream Pipeline job;
    • You can instead use relative paths like ../sister-folder/downstream
    • Or you can use absolute paths like /top-level-folder/nested-folder/downstream

Trigger another job using a branch as a param

At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).

In this example we're using relative paths

    stage('Trigger Branch Build') {
        steps {
            script {
                    echo "Triggering job for branch ${env.BRANCH_NAME}"
                    BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
                    build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
            }
        }
    }

Trigger another job using build number as a param

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

Trigger many jobs in parallel

Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel

    stage ('Trigger Builds In Parallel') {
        steps {
            // Freestyle build trigger calls a list of jobs
            // Pipeline build() step only calls one job
            // To run all three jobs in parallel, we use "parallel" step
            // https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
            parallel (
                linux: {
                    build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                mac: {
                    build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                windows: {
                    build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                failFast: false)
        }
    }

Or alternatively:

    stage('Build A and B') {
            failFast true
            parallel {
                stage('Build A') {
                    steps {
                            build job: "/project/A/${env.BRANCH}", wait: true
                    }
                }
                stage('Build B') {
                    steps {
                            build job: "/project/B/${env.BRANCH}", wait: true
                    }
                }
            }
    }

Setting mime type for excel document

You should always use below MIME type if you want to serve excel file in xlsx format

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet 

Removing page title and date when printing web page (with CSS?)

A possible workaround for the page title:

  • Provide a print button,
  • catch the onclick event,
  • use javascript to change the page title,
  • then execute the print command via javascript as well.

document.title = "Print page title"; window.print();

This should work in every browser.

ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean

Case 1:

@SpringBootApplication annotation missing in your spring boot starter class.

Case 2:

For non web application, disable web application type in properties file:

In application.properties:

spring.main.web-application-type=none

If you use application.yml then add:

  spring:
    main:
      web-application-type: none

For web applications, extends *SpringBootServletInitializer* in main class.

@SpringBootApplication
public class YourAppliationName extends SpringBootServletInitializer{
    public static void main(String[] args) {
        SpringApplication.run(YourAppliationName.class, args);
    }
}

Case 3:

If you use spring-boot-starter-webflux then also add spring-boot-starter-web as dependency.

Excel VBA Run-time error '424': Object Required when trying to copy TextBox

I think the reason that this is happening could be because TextBox1 is scoping to the VBA module and its associated sheet, while Range is scoping to the "Active Sheet".

EDIT

It looks like you may be able to use the GetObject function to pull the textbox from the workbook.

iterating over each character of a String in ruby 1.8.6 (each_char)

I have the same problem. I usually resort to String#split:

"ABCDEFG".split("").each do |i|
  puts i
end

I guess you could also implement it yourself like this:

class String
  def each_char
    self.split("").each { |i| yield i }
  end
end

Edit: yet another alternative is String#each_byte, available in Ruby 1.8.6, which returns the ASCII value of each char in an ASCII string:

"ABCDEFG".each_byte do |i|
  puts i.chr # Fixnum#chr converts any number to the ASCII char it represents
end

ArrayList filter

I agree with a previous answer that Google Guava is probably helping a lot here, readability-wise:

final Iterables.removeIf(list, new Predicate<String>() {
    @Override
    public boolean apply(String input) {
        if(input.contains("How")) { //or more complex pattern matching
            return true;
        }
        return false;
    }
}); 

Please note that this is basically a duplicate of Guava - How to remove from a list, based on a predicate, keeping track of what was removed?

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Switch case with conditions

What you are doing is to look for (0) or (1) results.

(cnt >= 10 && cnt <= 20) returns either true or false.

--edit-- you can't use case with boolean (logic) experessions. The statement cnt >= 10 returns zero for false or one for true. Hence, it will we case(1) or case(0) which will never match to the length. --edit--

Eliminating duplicate values based on only one column of the table

I solve such queries using this pattern:

SELECT *
FROM t
WHERE t.field=(
  SELECT MAX(t.field) 
  FROM t AS t0 
  WHERE t.group_column1=t0.group_column1
    AND t.group_column2=t0.group_column2 ...)

That is it will select records where the value of a field is at its max value. To apply it to your query I used the common table expression so that I don't have to repeat the JOIN twice:

WITH site_history AS (
  SELECT sites.siteName, sites.siteIP, history.date
  FROM sites
  JOIN history USING (siteName)
)
SELECT *
FROM site_history h
WHERE date=(
  SELECT MAX(date) 
  FROM site_history h0 
  WHERE h.siteName=h0.siteName)
ORDER BY siteName

It's important to note that it works only if the field we're calculating the maximum for is unique. In your example the date field should be unique for each siteName, that is if the IP can't be changed multiple times per millisecond. In my experience this is commonly the case otherwise you don't know which record is the newest anyway. If the history table has an unique index for (site, date), this query is also very fast, index range scan on the history table scanning just the first item can be used.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

php variable in html no other way than: <?php echo $var; ?>

I'd advise against using shorttags, see Are PHP short tags acceptable to use? for more information on why.

Personally I don't mind mixing HTML and PHP like so

<a href="<?php echo $link;?>">link description</a>

As long as I have a code-editor with good syntax highlighting, I think this is pretty readable. If you start echoing HTML with PHP then you lose all the advantages of syntax highlighting your HTML. Another disadvantage of echoing HTML is the stuff with the quotes, the following is a lot less readable IMHO.

echo '<a href="'.$link.'">link description</a>';

The biggest advantage for me with simple echoing and simple looping in PHP and doing the rest in HTML is that indentation is consistent, which in the end improves readability/scannability.

SQL Server 2008 Row Insert and Update timestamps

try

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    [CreateTS] [smalldatetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [smalldatetime] NOT NULL

)

PS I think a smalldatetime is good enough. You may decide differently.

Can you not do this at the "moment of impact" ?

In Sql Server, this is common:

Update dbo.MyTable 
Set 

ColA = @SomeValue , 
UpdateDS = CURRENT_TIMESTAMP
Where...........

Sql Server has a "timestamp" datatype.

But it may not be what you think.

Here is a reference:

http://msdn.microsoft.com/en-us/library/ms182776(v=sql.90).aspx

Here is a little RowVersion (synonym for timestamp) example:

CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)


INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Maybe a complete working example:

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER INSERT, UPDATE
AS

BEGIN

Update dbo.Names Set UpdateTS = CURRENT_TIMESTAMP from dbo.Names myAlias , inserted triggerInsertedTable where 
triggerInsertedTable.Name = myAlias.Name

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Matching on the "Name" value is probably not wise.

Try this more mainstream example with a SurrogateKey

DROP TABLE [dbo].[Names]
GO


CREATE TABLE [dbo].[Names]
(
    SurrogateKey int not null Primary Key Identity (1001,1),
    [Name] [nvarchar](64) NOT NULL,
    RowVers rowversion ,
    [CreateTS] [datetime] NOT NULL CONSTRAINT CreateTS_DF DEFAULT CURRENT_TIMESTAMP,
    [UpdateTS] [datetime] NOT NULL

)

GO

CREATE TRIGGER dbo.trgKeepUpdateDateInSync_ByeByeBye ON dbo.Names
AFTER UPDATE
AS

BEGIN

   UPDATE dbo.Names
    SET UpdateTS = CURRENT_TIMESTAMP
    From  dbo.Names myAlias
    WHERE exists ( select null from inserted triggerInsertedTable where myAlias.SurrogateKey = triggerInsertedTable.SurrogateKey)

END


GO






INSERT INTO dbo.Names (Name,UpdateTS)
select 'John' , CURRENT_TIMESTAMP
UNION ALL select 'Mary' , CURRENT_TIMESTAMP
UNION ALL select 'Paul' , CURRENT_TIMESTAMP

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Update dbo.Names Set Name = Name , UpdateTS = '03/03/2003' /* notice that even though I set it to 2003, the trigger takes over */

select *  ,  ConvertedRowVers = CONVERT(bigint,RowVers) from [dbo].[Names]

Java parsing XML document gives "Content not allowed in prolog." error

I think this is also a solution of this problem.

Change your document type from 'Encode in UTF-8' To 'Encode in UTF-8 without BOM'

I got resolved my problem by doing same changes.

How to create own dynamic type or dynamic object in C#?

 var data = new { studentId = 1, StudentName = "abc" };  

Or value is present

  var data = new { studentId, StudentName };

100% width table overflowing div container

Try adding to td:

display: -webkit-box; // to make td as block
word-break: break-word; // to make content justify

overflowed tds will align with new row.

JAX-RS — How to return JSON and HTTP status code together?

The answer by hisdrewness will work, but it modifies the whole approach to letting a provider such as Jackson+JAXB automatically convert your returned object to some output format such as JSON. Inspired by an Apache CXF post (which uses a CXF-specific class) I've found one way to set the response code that should work in any JAX-RS implementation: inject an HttpServletResponse context and manually set the response code. For example, here is how to set the response code to CREATED when appropriate.

@Path("/foos/{fooId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Foo setFoo(@PathParam("fooID") final String fooID, final Foo foo, @Context final HttpServletResponse response)
{
  //TODO store foo in persistent storage
  if(itemDidNotExistBefore) //return 201 only if new object; TODO app-specific logic
  {
    response.setStatus(Response.Status.CREATED.getStatusCode());
  }
  return foo;  //TODO get latest foo from storage if needed
}

Improvement: After finding another related answer, I learned that one can inject the HttpServletResponse as a member variable, even for singleton service class (at least in RESTEasy)!! This is a much better approach than polluting the API with implementation details. It would look like this:

@Context  //injected response proxy supporting multiple threads
private HttpServletResponse response;

@Path("/foos/{fooId}")
@PUT
@Consumes("application/json")
@Produces("application/json")
public Foo setFoo(@PathParam("fooID") final String fooID, final Foo foo)
{
  //TODO store foo in persistent storage
  if(itemDidNotExistBefore) //return 201 only if new object; TODO app-specific logic
  {
    response.setStatus(Response.Status.CREATED.getStatusCode());
  }
  return foo;  //TODO get latest foo from storage if needed
}

Conditional Formatting (IF not empty)

An equivalent result, "other things being equal", would be to format all cells grey and then use Go To Special to select the blank cells prior to removing their grey highlighting.

WiX tricks and tips

Setting the IIS enable32BitAppOnWin64 flag http://trycatchfail.com/blog/post/WiX-Snippet-change-enable32BitAppOnWin64.aspx

<InstallExecuteSequence>
   <RemoveExistingProducts After="InstallFinalize" />
   <Custom Action="ConfigureAppPool" After="InstallFinalize" >
     <![CDATA[NOT Installed AND VersionNT64 >= 600]]>         
   </Custom>
</InstallExecuteSequence>

<CustomAction Id="ConfigureAppPool" Return="check" Directory="TARGETDIR" ExeCommand="[SystemFolder]inetsrv\appcmd set apppool /apppool.name:[APPPOOLNAME] /enable32BitAppOnWin64:false" />

How to remove the last character from a string?

A one-liner answer (just a funny alternative - do not try this at home, and great answers already given):

public String removeLastChar(String s){return (s != null && s.length() != 0) ? s.substring(0, s.length() - 1): s;}

Convert Word doc, docx and Excel xls, xlsx to PDF with PHP

I successfully put a portable version of libreoffice on my host's webserver, which I call with PHP to do a commandline conversion from .docx, etc. to pdf. on the fly. I do not have admin rights on my host's webserver. Here is my blog post of what I did:

http://geekswithblogs.net/robertphyatt/archive/2011/11/19/converting-.docx-to-pdf-or-.doc-to-pdf-or-.doc.aspx

Yay! Convert directly from .docx or .odt to .pdf using PHP with LibreOffice (OpenOffice's successor)!

How to add elements of a Java8 stream into an existing List

You just have to refer your original list to be the one that the Collectors.toList() returns.

Here's a demo:

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class Reference {

  public static void main(String[] args) {
    List<Integer> list = Arrays.asList(1, 2, 3, 4, 5);
    System.out.println(list);

    // Just collect even numbers and start referring the new list as the original one.
    list = list.stream()
               .filter(n -> n % 2 == 0)
               .collect(Collectors.toList());
    System.out.println(list);
  }
}

And here's how you can add the newly created elements to your original list in just one line.

List<Integer> list = ...;
// add even numbers from the list to the list again.
list.addAll(list.stream()
                .filter(n -> n % 2 == 0)
                .collect(Collectors.toList())
);

That's what this Functional Programming Paradigm provides.

How to retrieve current workspace using Jenkins Pipeline Groovy script?

I think you can also execute the pwd() function on the particular node:

node {
    def PWD = pwd();
    ...
}

How do I write a "tab" in Python?

Assume I have a variable named file that contains a file. Then I could use file.write("hello\talex").

  1. file.write("hello means I'm starting to write to this file.
  2. \t means a tab
  3. alex") is the rest I'm writing

What does cv::normalize(_src, dst, 0, 255, NORM_MINMAX, CV_8UC1);

When the normType is NORM_MINMAX, cv::normalize normalizes _src in such a way that the min value of dst is alpha and max value of dst is beta. cv::normalize does its magic using only scales and shifts (i.e. adding constants and multiplying by constants).

CV_8UC1 says how many channels dst has.

The documentation here is pretty clear: http://docs.opencv.org/modules/core/doc/operations_on_arrays.html#normalize

How to use the 'og' (Open Graph) meta tag for Facebook share

Facebook uses what's called the Open Graph Protocol to decide what things to display when you share a link. The OGP looks at your page and tries to decide what content to show. We can lend a hand and actually tell Facebook what to take from our page.

The way we do that is with og:meta tags.

The tags look something like this -

  <meta property="og:title" content="Stuffed Cookies" />
  <meta property="og:image" content="http://fbwerks.com:8000/zhen/cookie.jpg" />
  <meta property="og:description" content="The Turducken of Cookies" />
  <meta property="og:url" content="http://fbwerks.com:8000/zhen/cookie.html">

You'll need to place these or similar meta tags in the <head> of your HTML file. Don't forget to substitute the values for your own!

For more information you can read all about how Facebook uses these meta tags in their documentation. Here is one of the tutorials from there - https://developers.facebook.com/docs/opengraph/tutorial/


Facebook gives us a great little tool to help us when dealing with these meta tags - you can use the Debugger to see how Facebook sees your URL, and it'll even tell you if there are problems with it.

One thing to note here is that every time you make a change to the meta tags, you'll need to feed the URL through the Debugger again so that Facebook will clear all the data that is cached on their servers about your URL.

Getting data posted in between two dates

This worked for me:

$this->db->where('RecordDate >=', '2018-08-17 00:00:00');
$this->db->where('RecordDate <=', '2018-10-04 05:32:56');

creating charts with angularjs

AngularJS charting plugin along with FusionCharts library to add interactive JavaScript graphs and charts to your web/mobile applications - with just a single directive. Link: http://www.fusioncharts.com/angularjs-charts/#/demos/ex1

Can you delete data from influxdb?

This is for InfluxDB shell version: 1.8.2

Delete works without time field too. As you can see from the series of screen shots:

  1. I create a DB and and add start using it.

InfluxDB create DB and use it

  1. Add some rows in it.Verify if they are added.

Add rows in influxdb and print

  1. Delete all with tag 'Dev1' and verify the same.

Delete all rows for tag from influxdb

Note: The tag name has to be in single quotes only. Not double.

Dump a list in a pickle file and retrieve it back later

Pickling will serialize your list (convert it, and it's entries to a unique byte string), so you can save it to disk. You can also use pickle to retrieve your original list, loading from the saved file.

So, first build a list, then use pickle.dump to send it to a file...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> mylist = ['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>> 
>>> import pickle
>>> 
>>> with open('parrot.pkl', 'wb') as f:
...   pickle.dump(mylist, f)
... 
>>> 

Then quit and come back later… and open with pickle.load...

Python 3.4.1 (default, May 21 2014, 12:39:51) 
[GCC 4.2.1 Compatible Apple LLVM 5.0 (clang-500.2.79)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('parrot.pkl', 'rb') as f:
...   mynewlist = pickle.load(f)
... 
>>> mynewlist
['I wish to complain about this parrot what I purchased not half an hour ago from this very boutique.', "Oh yes, the, uh, the Norwegian Blue...What's,uh...What's wrong with it?", "I'll tell you what's wrong with it, my lad. 'E's dead, that's what's wrong with it!", "No, no, 'e's uh,...he's resting."]
>>>

Open links in new window using AngularJS

I have gone through many links but this answer helped me alot:

$scope.redirectPage = function (data) { $window.open(data, "popup", "width=1000,height=700,left=300,top=200"); };

** data will be absolute url which you are hitting.

jquery function val() is not equivalent to "$(this).value="?

One thing you can do is this:

$(this)[0].value = "Something";

This allows jQuery to return the javascript object for that element, and you can bypass jQuery Functions.

Calculating moving average

Here is a simple function with filter demonstrating one way to take care of beginning and ending NAs with padding, and computing a weighted average (supported by filter) using custom weights:

wma <- function(x) { 
  wts <- c(seq(0.5, 4, 0.5), seq(3.5, 0.5, -0.5))
  nside <- (length(wts)-1)/2
  # pad x with begin and end values for filter to avoid NAs
  xp <- c(rep(first(x), nside), x, rep(last(x), nside)) 
  z <- stats::filter(xp, wts/sum(wts), sides = 2) %>% as.vector 
  z[(nside+1):(nside+length(x))]
}

Protecting cells in Excel but allow these to be modified by VBA script

Try using

Worksheet.Protect "Password", UserInterfaceOnly := True

If the UserInterfaceOnly parameter is set to true, VBA code can modify protected cells.

What is the proper declaration of main in C++?

The exact wording of the latest published standard (C++14) is:

An implementation shall allow both

  • a function of () returning int and

  • a function of (int, pointer to pointer to char) returning int

as the type of main.

This makes it clear that alternative spellings are permitted so long as the type of main is the type int() or int(int, char**). So the following are also permitted:

  • int main(void)
  • auto main() -> int
  • int main ( )
  • signed int main()
  • typedef char **a; typedef int b, e; e main(b d, a c)

What is the Java equivalent of PHP var_dump?

In my experience, var_dump is typically used for debugging PHP in place of a step-though debugger. In Java, you can of course use your IDE's debugger to see a visual representation of an object's contents.

Histogram Matplotlib

This might be useful for someone.

Numpy's histogram function returns the edges of each bin, rather than the value of the bin. This makes sense for floating-point numbers, which can lie within an interval, but may not be the desired result when dealing with discrete values or integers (0, 1, 2, etc). In particular, the length of bins returned from np.histogram is not equal to the length of the counts / density.

To get around this, I used np.digitize to quantize the input, and count the fraction of counts for each bin. You could easily edit to get the integer number of counts.

def compute_PMF(data):
    import numpy as np
    from collections import Counter
    _, bins = np.histogram(data, bins='auto', range=(data.min(), data.max()), density=False)
    h = Counter(np.digitize(data,bins) - 1)
    weights = np.asarray(list(h.values())) 
    weights = weights / weights.sum()
    values = np.asarray(list(h.keys()))
    return weights, values
####

Refs:

[1] https://docs.scipy.org/doc/numpy/reference/generated/numpy.histogram.html

[2] https://docs.scipy.org/doc/numpy/reference/generated/numpy.digitize.html

jQuery UI Alert Dialog as a replacement for alert()

I took @EkoJR's answer, and added an additional parameter to pass in with a callback function to occur when the user closes the dialog.

function jqAlert(outputMsg, titleMsg, onCloseCallback) {
    if (!titleMsg)
        titleMsg = 'Alert';

    if (!outputMsg)
        outputMsg = 'No Message to Display.';

    $("<div></div>").html(outputMsg).dialog({
        title: titleMsg,
        resizable: false,
        modal: true,
        buttons: {
            "OK": function () {
                $(this).dialog("close");
            }
        },
        close: onCloseCallback
    });
}

You can then call it and pass it a function, that will occur when the user closes the dialog, as so:

jqAlert('Your payment maintenance has been saved.', 
        'Processing Complete', 
        function(){ window.location = 'search.aspx' })

How to uninstall jupyter

If you installed Jupiter notebook through anaconda, this may help you:

conda uninstall jupyter notebook

How can I initialize base class member variables in derived class constructor?

Why can't you do it? Because the language doesn't allow you to initializa a base class' members in the derived class' initializer list.

How can you get this done? Like this:

class A
{
public:
    A(int a, int b) : a_(a), b_(b) {};
    int a_, b_;
};

class B : public A
{
public:
    B() : A(0,0) 
    {
    }
};

How to compile and run C files from within Notepad++ using NppExec plugin?

Here's a procedure for Perl, just adapt it for C. Hope it helps.

  • Open Notepad++
  • Type F6 to open the execute window
  • Write the following commands:
    • npp_save <-- Saves the current document
    • CD $(CURRENT_DIRECTORY) <-- Moves to the current directory
    • perl.exe -c -w "$(FILE_NAME)" <-- executes the command perl.exe -c -w , example: perl.exe -c -w test.pl (-c = compile -w = warnings)
  • Click on Save
  • Type a name to save the script (e.g. "Perl Compile")
  • Go to Menu Plugins -> Nppexec -> advanced options -> Menu Item (Note: this is right BELOW 'Menu Items *')
  • In the combobox titled 'Associated Script' select the script recently created in its dropdown menu, select Add/Modify and click OK -> OK
  • Restart Notepad++
  • Go to Settings -> Shortcut mapper -> Plugins -> search for the script name
  • Select the shortcut to use (ie Ctrl + 1), click OK
  • Verify that you can now run the script created with the shortcut selected.

Press any key to continue

Check out the ReadKey() method on the System.Console .NET class. I think that will do what you're looking for.

http://msdn.microsoft.com/en-us/library/system.console.readkey(v=vs.110).aspx

Example:

Write-Host -Object ('The key that was pressed was: {0}' -f [System.Console]::ReadKey().Key.ToString());

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

I've used them a few times (in particular for building massive objects splitting the data over many files (e.g. AST nodes)), in order to build them I made a tiny script (which I've just added to npm so everyone else can use it).

Usage (currently you'll need to use babel to use the export file):

$ npm install -g folder-module
$ folder-module my-cool-module/

Generates a file containing:

export {default as foo} from "./module/foo.js"
export {default as default} from "./module/default.js"
export {default as bar} from "./module/bar.js"
...etc

Then you can just consume the file:

import * as myCoolModule from "my-cool-module.js"
myCoolModule.foo()

How to downgrade php from 5.5 to 5.3

I did this in my local environment. Wasn't difficult but obviously it was done in "unsupported" way.

To do the downgrade you need just to download php 5.3 from http://php.net/releases/ (zip archive), than go to xampp folder and copy subfolder "php" to e.g. php5.5 (just for backup). Than remove content of the folder php and unzip content of zip archive downloaded from php.net. The next step is to adjust configuration (php.ini) - you can refer to your backed-up version from php 5.5. After that just run xampp control utility - everything should work (at least worked in my local environment). I didn't found any problem with such installation, although I didn't tested this too intensively.

What is PECS (Producer Extends Consumer Super)?

public class Test {

    public class A {}

    public class B extends A {}

    public class C extends B {}

    public void testCoVariance(List<? extends B> myBlist) {
        B b = new B();
        C c = new C();
        myBlist.add(b); // does not compile
        myBlist.add(c); // does not compile
        A a = myBlist.get(0); 
    }

    public void testContraVariance(List<? super B> myBlist) {
        B b = new B();
        C c = new C();
        myBlist.add(b);
        myBlist.add(c);
        A a = myBlist.get(0); // does not compile
    }
}

limit text length in php and provide 'Read more' link

This worked for me.

// strip tags to avoid breaking any html
$string = strip_tags($string);
if (strlen($string) > 500) {

    // truncate string
    $stringCut = substr($string, 0, 500);
    $endPoint = strrpos($stringCut, ' ');

    //if the string doesn't contain any space then it will cut without word basis.
    $string = $endPoint? substr($stringCut, 0, $endPoint) : substr($stringCut, 0);
    $string .= '... <a href="/this/story">Read More</a>';
}
echo $string;

Thanks @webbiedave

GROUP_CONCAT comma separator - MySQL

Looks like you're missing the SEPARATOR keyword in the GROUP_CONCAT function.

GROUP_CONCAT(artists.artistname SEPARATOR '----')

The way you've written it, you're concatenating artists.artistname with the '----' string using the default comma separator.

Android Lint contentDescription warning

If you want to suppress this warning in elegant way (because you are sure that accessibility is not needed for this particular ImageView), you can use special attribute:

android:importantForAccessibility="no"

Fastest way to Remove Duplicate Value from a list<> by lambda

In-place:

    public static void DistinctValues<T>(List<T> list)
    {
        list.Sort();

        int src = 0;
        int dst = 0;
        while (src < list.Count)
        {
            var val = list[src];
            list[dst] = val;

            ++dst;
            while (++src < list.Count && list[src].Equals(val)) ;
        }
        if (dst < list.Count)
        {
            list.RemoveRange(dst, list.Count - dst);
        }
    }

Interpreting segfault messages

Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.

"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.

"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.

What's the "average" requests per second for a production web application?

Note that hit-rate graphs will be sinusoidal patterns with 'peak hours' maybe 2x or 3x the rate that you get while users are sleeping. (Can be useful when you're scheduling the daily batch-processing stuff to happen on servers)

You can see the effect even on 'international' (multilingual, localised) sites like wikipedia

Cannot read property 'map' of undefined

I considered giving a comment under the answer by taggon to this very question, but well, i felt it owed more explanation for those interested in details.

Uncaught TypeError: Cannot read property 'value' of undefined is strictly a JavaScript error.
(Note that value can be anything, but for this question value is 'map')

It's critical to understand that point, just so you avoid endless debugging cycles.
This error is common especially if just starting out in JavaScript (and it's libraries/frameworks).
For React, this has a lot to do with understanding the component lifecycle methods.

// Follow this example to get the context
// Ignore any complexity, focus on how 'props' are passed down to children

import React, { useEffect } from 'react'

// Main component
const ShowList = () => {
  // Similar to componentDidMount and componentDidUpdate
  useEffect(() => {// dispatch call to fetch items, populate the redux-store})

  return <div><MyItems items={movies} /></div>
}

// other component
const MyItems = props =>
  <ul>
    {props.items.map((item, i) => <li key={i}>item</li>)}
  </ul>


/**
  The above code should work fine, except for one problem.
  When compiling <ShowList/>,
  React-DOM renders <MyItems> before useEffect (or componentDid...) is called.
  And since `items={movies}`, 'props.items' is 'undefined' at that point.
  Thus the error message 'Cannot read property map of undefined'
 */

As a way to tackle this problem, @taggon gave a solution (see first anwser or link).

Solution: Set an initial/default value.
In our example, we can avoid items being 'undefined' by declaring a default value of an empty array.

Why? This allows React-DOM to render an empty list initially.
And when the useEffect or componentDid... method is executed, the component is re-rendered with a populated list of items.

// Let's update our 'other' component
// destructure the `items` and initialize it as an array

const MyItems = ({items = []}) =>
  <ul>
    {items.map((item, i) => <li key={i}>item</li>)}
  </ul>

Chrome DevTools Devices does not detect device when plugged in

Had a nightmare with this today Samsung Galaxy Note 9 and a Windows 10 Laptop without Android Studio. Here are working steps to get debugging.

1) Enable developer mode on the phone in the usual manner and turn on "USB Debugging".

2) On your computer install the Samsung USB Drivers for Windows https://developer.samsung.com/galaxy/others/android-usb-driver-for-windows

3) Open Chrome on your Computer - bring up Remote Devices in dev console (at the moment it will say no devices detected).

4) Connect your phone to your computer via USB cable.

5) Accept any prompts for authorisation and wait until the computer says "your device is ready.." etc.

6) On your phone, swipe down the top menu and tap "P Android system" - select "MIDI" under "Use USB for".

7) Various setup notifications will appear on your PC, when they are finished you will get the authorisation prompt for debugging on your phone. Accept it! Wait a few more second and you will find the phone now appears in Chrome Dev tools on the computer, and will be connected in a few more seconds.

You're welcome.

How to deal with page breaks when printing a large HTML table

The accepted answer did not work for me in all browsers, but following css did work for me:

tr    
{ 
  display: table-row-group;
  page-break-inside:avoid; 
  page-break-after:auto;
}

The html structure was:

<table>
  <thead>
    <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
    <tr></tr>
    ...
  </tbody>
</table>

In my case, there were some additional issues with the thead tr, but this resolved the original issue of keeping the table rows from breaking.

Because of the header issues, I ultimately ended up with:

#theTable td *
{
  page-break-inside:avoid;
}

This didn't prevent rows from breaking; just each cell's content.

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

I had the same problem but was resolved. I realized branch name is case sensitive. The main branch in GitHub is 'master', while in my gitbash command it's 'Master'. I renamed Master in local repository to master and it worked!

fatal: git-write-tree: error building trees

Use:

git reset --mixed

instead of git reset --hard. You will not lose any changes.

Get the full URL in PHP

Simply use:

$uri = $_SERVER['REQUEST_SCHEME'] . '://' . $_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI']

How to update SQLAlchemy row entry?

user.no_of_logins += 1
session.commit()

Floating point comparison functions for C#

static class FloatUtil {

    static bool IsEqual(float a, float b, float tolerance = 0.001f) {
      return Math.Abs(a - b) < tolerance;
    }

    static bool IsGreater(float a, float b) {
      return a > b;
    }

    static bool IsLess(float a, float b) {
      return a < b;
    }
}

The value of tolerance that is passed into IsEqual is something that the client could decide.

IsEqual(1.002, 1.001);          -->   False
IsEqual(1.002, 1.001, 0.01);    -->   True

configuring project ':app' failed to find Build Tools revision

I found out that it also happens if you uninstalled some packages from your react-native project and there is still packages in your build gradle dependencies in the bottom of page like:

{
 project(':react-native-sound-player')
}

How can I login to a website with Python?

Web page automation ? Definitely "webbot"

webbot even works web pages which have dynamically changing id and classnames and has more methods and features than selenium or mechanize.

Here's a snippet :)

from webbot import Browser 
web = Browser()
web.go_to('google.com') 
web.click('Sign in')
web.type('[email protected]' , into='Email')
web.click('NEXT' , tag='span')
web.type('mypassword' , into='Password' , id='passwordFieldId') # specific selection
web.click('NEXT' , tag='span') # you are logged in ^_^

The docs are also pretty straight forward and simple to use : https://webbot.readthedocs.io

Numpy: Creating a complex array from 2 real ones?

That worked for me:

input:

[complex(a,b) for a,b in zip([1,2,3],[1,2,3])]

output:

[(1+4j), (2+5j), (3+6j)]

Validating parameters to a Bash script

The sh solution by Brian Campbell, while noble and well executed, has a few problems, so I thought I'd provide my own bash solution.

The problems with the sh one:

  • The tilde in ~/foo doesn't expand to your homedirectory inside heredocs. And neither when it's read by the read statement or quoted in the rm statement. Which means you'll get No such file or directory errors.
  • Forking off grep and such for basic operations is daft. Especially when you're using a crappy shell to avoid the "heavy" weight of bash.
  • I also noticed a few quoting issues, for instance around a parameter expansion in his echo.
  • While rare, the solution cannot cope with filenames that contain newlines. (Almost no solution in sh can cope with them - which is why I almost always prefer bash, it's far more bulletproof & harder to exploit when used well).

While, yes, using /bin/sh for your hashbang means you must avoid bashisms at all costs, you can use all the bashisms you like, even on Ubuntu or whatnot when you're honest and put #!/bin/bash at the top.

So, here's a bash solution that's smaller, cleaner, more transparent, probably "faster", and more bulletproof.

[[ -d $1 && $1 != *[^0-9]* ]] || { echo "Invalid input." >&2; exit 1; }
rm -rf ~/foo/"$1"/bar ...
  1. Notice the quotes around $1 in the rm statement!
  2. The -d check will also fail if $1 is empty, so that's two checks in one.
  3. I avoided regular expressions for a reason. If you must use =~ in bash, you should be putting the regular expression in a variable. In any case, globs like mine are always preferable and supported in far more bash versions.

Extract / Identify Tables from PDF python

You should definitely have a look at this answer of mine:

and also have a look at all the links included therein.

Tabula/TabulaPDF is currently the best table extraction tool that is available for PDF scraping.

How to create our own Listener interface in android?

I have done it something like below for sending my model class from the Second Activity to First Activity. I used LiveData to achieve this, with the help of answers from Rupesh and TheCodeFather.

Second Activity

public static MutableLiveData<AudioListModel> getLiveSong() {
        MutableLiveData<AudioListModel> result = new MutableLiveData<>();
        result.setValue(liveSong);
        return result;
    }

"liveSong" is AudioListModel declared globally

Call this method in the First Activity

PlayerActivity.getLiveSong().observe(this, new Observer<AudioListModel>() {
            @Override
            public void onChanged(AudioListModel audioListModel) {
                if (PlayerActivity.mediaPlayer != null && PlayerActivity.mediaPlayer.isPlaying()) {
                    Log.d("LiveSong--->Changes-->", audioListModel.getSongName());
                }
            }
        });

May this help for new explorers like me.

How to set input type date's default value to today?

<input id="datePicker" type="date" />

_x000D_
_x000D_
$(document).ready( function() {_x000D_
    var now = new Date();_x000D_
 _x000D_
    var day = ("0" + now.getDate()).slice(-2);_x000D_
    var month = ("0" + (now.getMonth() + 1)).slice(-2);_x000D_
_x000D_
    var today = now.getFullYear()+"-"+(month)+"-"+(day) ;_x000D_
_x000D_
_x000D_
   $('#datePicker').val(today);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input id="datePicker" type="date" />
_x000D_
_x000D_
_x000D_

Changing image size in Markdown

The accepted answer here isn't working with any Markdown editor available in the apps I have used till date like Ghost, Stackedit.io or even in the StackOverflow editor. I found a workaround here in the StackEdit.io issue tracker.

The solution is to directly use HTML syntax, and it works perfectly:

<img src="http://....jpg" width="200" height="200" />

Default values in a C Struct

How about something like:

struct foo bar;
update(init_id(42, init_dont_care(&bar)));

with:

struct foo* init_dont_care(struct foo* bar) {
  bar->id = dont_care;
  bar->route = dont_care;
  bar->backup_route = dont_care;
  bar->current_route = dont_care;
  return bar;
}

and:

struct foo* init_id(int id, struct foo* bar) {
  bar->id = id;
  return bar;
}

and correspondingly:

struct foo* init_route(int route, struct foo* bar);
struct foo* init_backup_route(int backup_route, struct foo* bar);
struct foo* init_current_route(int current_route, struct foo* bar);

In C++, a similar pattern has a name which I don't remember just now.

EDIT: It's called the Named Parameter Idiom.

Password Strength Meter

Here's a collection of scripts: http://webtecker.com/2008/03/26/collection-of-password-strength-scripts/

I think both of them rate the password and don't use jQuery... but I don't know if they have native support for disabling the form?

Convert seconds to hh:mm:ss in Python

I can't believe any of the many answers gives what I'd consider the "one obvious way to do it" (and I'm not even Dutch...!-) -- up to just below 24 hours' worth of seconds (86399 seconds, specifically):

>>> import time
>>> time.strftime('%H:%M:%S', time.gmtime(12345))
'03:25:45'

Doing it in a Django template's more finicky, since the time filter supports a funky time-formatting syntax (inspired, I believe, from PHP), and also needs the datetime module, and a timezone implementation such as pytz, to prep the data. For example:

>>> from django import template as tt
>>> import pytz
>>> import datetime
>>> tt.Template('{{ x|time:"H:i:s" }}').render(
...     tt.Context({'x': datetime.datetime.fromtimestamp(12345, pytz.utc)}))
u'03:25:45'

Depending on your exact needs, it might be more convenient to define a custom filter for this formatting task in your app.

HTTP POST with URL query parameters -- good idea or not?

The REST camp have some guiding principles that we can use to standardize the way we use HTTP verbs. This is helpful when building RESTful API's as you are doing.

In a nutshell: GET should be Read Only i.e. have no effect on server state. POST is used to create a resource on the server. PUT is used to update or create a resource. DELETE is used to delete a resource.

In other words, if your API action changes the server state, REST advises us to use POST/PUT/DELETE, but not GET.

User agents usually understand that doing multiple POSTs is bad and will warn against it, because the intent of POST is to alter server state (eg. pay for goods at checkout), and you probably don't want to do that twice!

Compare to a GET which you can do an often as you like (idempotent).

Concatenating Column Values into a Comma-Separated List

Please try this with the following code:

DECLARE @listStr VARCHAR(MAX)
SELECT @listStr = COALESCE(@listStr+',' , '') + CarName
FROM Cars
SELECT @listStr

Read a local text file using Javascript

Please find below the code that generates automatically the content of the txt local file and display it html. Good luck!

<html>
<head>
  <meta charset="utf-8">
  <script type="text/javascript">

  var x;
  if(navigator.appName.search('Microsoft')>-1) { x = new ActiveXObject('MSXML2.XMLHTTP'); }
  else { x = new XMLHttpRequest(); }

  function getdata() {
    x.open('get', 'data1.txt', true); 
    x.onreadystatechange= showdata;
    x.send(null);
  }

  function showdata() {
    if(x.readyState==4) {
      var el = document.getElementById('content');
      el.innerHTML = x.responseText;
    }
  }

  </script>
</head>
<body onload="getdata();showdata();">

  <div id="content"></div>

</body>
</html>

How to place the ~/.composer/vendor/bin directory in your PATH?

this is what I added in my .bashrc file and worked.

export PATH="$PATH:/home/myUsername/.composer/vendor/bin"

Constraint Layout Vertical Align Center

 <TextView
        android:id="@+id/tvName"
        style="@style/textViewBoldLarge"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="Welcome"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintBottom_toBottomOf="parent"/>

Java; String replace (using regular expressions)?

You'll want to look into capturing in regex to handle wrapping the 3 in ^3.

Hex to ascii string conversion

If I understand correctly, you want to know how to convert bytes encoded as a hex string to its form as an ASCII text, like "537461636B" would be converted to "Stack", in such case then the following code should solve your problem.

Have not run any benchmarks but I assume it is not the peak of efficiency.

static char ByteToAscii(const char *input) {
  char singleChar, out;
  memcpy(&singleChar, input, 2);
  sprintf(&out, "%c", (int)strtol(&singleChar, NULL, 16));
  return out;
}

int HexStringToAscii(const char *input, unsigned int length,
                            char **output) {
  int mIndex, sIndex = 0;
  char buffer[length];
  for (mIndex = 0; mIndex < length; mIndex++) {
    sIndex = mIndex * 2;
    char b = ByteToAscii(&input[sIndex]);
    memcpy(&buffer[mIndex], &b, 1);
  }
  *output = strdup(buffer);
  return 0;
}

How can I get a resource content from a static context?

Shortcut

I use App.getRes() instead of App.getContext().getResources() (as @Cristian answered)

It is very simple to use anywhere in your code!

So here is a unique solution by which you can access resources from anywhere like Util class .

(1) Create or Edit your Application class.

import android.app.Application;
import android.content.res.Resources;

public class App extends Application {
    private static App mInstance;
    private static Resources res;


    @Override
    public void onCreate() {
        super.onCreate();
        mInstance = this;
        res = getResources();
    }

    public static App getInstance() {
        return mInstance;
    }

    public static Resources getRes() {
        return res;
    }

}

(2) Add name field to your manifest.xml <application tag. (or Skip this if already there)

<application
        android:name=".App"
        ...
        >
        ...
    </application>

Now you are good to go.

Use App.getRes().getString(R.string.some_id) anywhere in code.

Does my application "contain encryption"?

@hisnameisjimmy is correct: You will notice (at least as of today, Dec 1st 2016) when you go to submit your app for review and reach the Export Compliance walkthrough, you'll notice the menu now states that HTTPS is an exempt version of encryption (if you use it for every call):

enter image description here

enter image description here

How do I make the method return type generic?

What you're looking for here is abstraction. Code against interfaces more and you should have to do less casting.

The example below is in C# but the concept remains the same.

using System;
using System.Collections.Generic;
using System.Reflection;

namespace GenericsTest
{
class MainClass
{
    public static void Main (string[] args)
    {
        _HasFriends jerry = new Mouse();
        jerry.AddFriend("spike", new Dog());
        jerry.AddFriend("quacker", new Duck());

        jerry.CallFriend<_Animal>("spike").Speak();
        jerry.CallFriend<_Animal>("quacker").Speak();
    }
}

interface _HasFriends
{
    void AddFriend(string name, _Animal animal);

    T CallFriend<T>(string name) where T : _Animal;
}

interface _Animal
{
    void Speak();
}

abstract class AnimalBase : _Animal, _HasFriends
{
    private Dictionary<string, _Animal> friends = new Dictionary<string, _Animal>();


    public abstract void Speak();

    public void AddFriend(string name, _Animal animal)
    {
        friends.Add(name, animal);
    }   

    public T CallFriend<T>(string name) where T : _Animal
    {
        return (T) friends[name];
    }
}

class Mouse : AnimalBase
{
    public override void Speak() { Squeek(); }

    private void Squeek()
    {
        Console.WriteLine ("Squeek! Squeek!");
    }
}

class Dog : AnimalBase
{
    public override void Speak() { Bark(); }

    private void Bark()
    {
        Console.WriteLine ("Woof!");
    }
}

class Duck : AnimalBase
{
    public override void Speak() { Quack(); }

    private void Quack()
    {
        Console.WriteLine ("Quack! Quack!");
    }
}
}

How to change maven java home

Even if you install the Oracle JDK, your $JAVA_HOME variable should refer to the path of the JRE that is inside the JDK root. You can refer to my other answer to a similar question for more details.

Using git commit -a with vim

  1. In vim, you save a file with :wEnter while in the normal mode (you get to the normal mode by pressing Esc).
  2. You close your file with :q while in the normal mode.

You can combine both these actions and do Esc:wqEnter to save the commit and quit vim.

As an alternate to the above, you can also press ZZ while in the normal mode, which will save the file and exit vim. This is also easier for some people as it's the same key pressed twice.

Is it possible to apply CSS to half of a character?

Closest I can get:

_x000D_
_x000D_
$(function(){_x000D_
  $('span').width($('span').width()/2);_x000D_
  $('span:nth-child(2)').css('text-indent', -$('span').width());_x000D_
});
_x000D_
body{_x000D_
  font-family: arial;_x000D_
}_x000D_
span{_x000D_
  display: inline-block;_x000D_
  overflow: hidden;_x000D_
}_x000D_
span:nth-child(2){_x000D_
  color: red;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<span>X</span><span>X</span>
_x000D_
_x000D_
_x000D_

Demo: http://jsfiddle.net/9wxfY/2/

Heres a version that just uses one span: http://jsfiddle.net/9wxfY/4/

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Order of items in classes: Fields, Properties, Constructors, Methods

the only coding guidelines I've seen suggested for this is to put fields at the top of the class definition.

i tend to put constructors next.

my general comment would be that you should stick to one class per file and if the class is big enough that the organization of properties versus methods is a big concern, how big is the class and should you be refactoring it anyway? does it represent multiple concerns?

Using XAMPP, how do I swap out PHP 5.3 for PHP 5.2?

I couldn't get this working. Started with PHP 5.3, then tried to switch to PHP 5.28 from xampp-win32-1.7.0.zip. Couldn't get it to work. Then, I got smart and figured out i was working with XAMPP and you can install it wherever you want, so I did a fresh install from scratch with xampp-win32-1.7.0.zip. The whole point of working with XAMPP is so you don't have to fuss with the sysadmin stuff. Using it in that context got me up and running in no time.

Does Python have an ordered set?

The answer is no, but you can use collections.OrderedDict from the Python standard library with just keys (and values as None) for the same purpose.

Update: As of Python 3.7 (and CPython 3.6), standard dict is guaranteed to preserve order and is more performant than OrderedDict. (For backward compatibility and especially readability, however, you may wish to continue using OrderedDict.)

Here's an example of how to use dict as an ordered set to filter out duplicate items while preserving order, thereby emulating an ordered set. Use the dict class method fromkeys() to create a dict, then simply ask for the keys() back.

>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']

>>> list(dict.fromkeys(keywords))
['foo', 'bar', 'baz']

Concat all strings inside a List<string> using LINQ

This is for a string array:

string.Join(delimiter, array);

This is for a List<string>:

string.Join(delimiter, list.ToArray());

And this is for a list of custom objects:

string.Join(delimiter, list.Select(i => i.Boo).ToArray());

sizing div based on window width

Live Demo

Here is an actual implementation of what you described. I rewrote your code a bit using the latest best practices to actualize is. If you resize your browser windows under 1000px, the image's left and right side will be cropped using negative margins and it will be 300px narrower.

<style>
   .container {
      position: relative;
      width: 100%;
   }

   .bg {
      position:relative;
      z-index: 1;
      height: 100%;
      min-width: 1000px;
      max-width: 1500px;
      margin: 0 auto;
   }

   .nebula {
      width: 100%;
   }

   @media screen and (max-width: 1000px) {
      .nebula {
         width: 100%;
         overflow: hidden;
         margin: 0 -150px 0 -150px;
      }
   }
</style>

<div class="container">
   <div class="bg">
      <img src="http://i.stack.imgur.com/tFshX.jpg" class="nebula">
   </div>
</div>

@import vs #import - iOS 7

It currently only works for the built in system frameworks. If you use #import like apple still do importing the UIKit framework in the app delegate it is replaced (if modules is on and its recognised as a system framework) and the compiler will remap it to be a module import and not an import of the header files anyway. So leaving the #import will be just the same as its converted to a module import where possible anyway

OpenCV error: the function is not implemented

If you installed OpenCV using the opencv-python pip package at any point in time, be aware of the following note, taken from https://pypi.python.org/pypi/opencv-python

IMPORTANT NOTE MacOS and Linux wheels have currently some limitations:

  • video related functionality is not supported (not compiled with FFmpeg)
  • for example cv2.imshow() will not work (not compiled with GTK+ 2.x or Carbon support)

Also note that to install from another source, first you must remove the opencv-python package

Insert into a MySQL table or update if exists

Try this:

INSERT INTO table (id,name,age) VALUES('1','Mohammad','21') ON DUPLICATE KEY UPDATE name='Mohammad',age='21'

Note:
Here if id is the primary key then after first insertion with id='1' every time attempt to insert id='1' will update name and age and previous name age will change.

How do I assign a null value to a variable in PowerShell?

Use $dec = $null

From the documentation:

$null is an automatic variable that contains a NULL or empty value. You can use this variable to represent an absent or undefined value in commands and scripts.

PowerShell treats $null as an object with a value, that is, as an explicit placeholder, so you can use $null to represent an empty value in a series of values.

Return anonymous type results?

You can not return anonymous types directly, but you can loop them through your generic method. So do most of LINQ extension methods. There is no magic in there, while it looks like it they would return anonymous types. If parameter is anonymous result can also be anonymous.

var result = Repeat(new { Name = "Foo Bar", Age = 100 }, 10);

private static IEnumerable<TResult> Repeat<TResult>(TResult element, int count)
{
    for(int i=0; i<count; i++)
    {
        yield return element;
    }
}

Below an example based on code from original question:

var result = GetDogsWithBreedNames((Name, BreedName) => new {Name, BreedName });


public static IQueryable<TResult> GetDogsWithBreedNames<TResult>(Func<object, object, TResult> creator)
{
    var db = new DogDataContext(ConnectString);
    var result = from d in db.Dogs
                    join b in db.Breeds on d.BreedId equals b.BreedId
                    select creator(d.Name, b.BreedName);
    return result;
}

How to concatenate multiple column values into a single column in Panda dataframe

The answer given by @allen is reasonably generic but can lack in performance for larger dataframes:

Reduce does a lot better:

from functools import reduce

import pandas as pd

# make data
df = pd.DataFrame(index=range(1_000_000))
df['1'] = 'CO'
df['2'] = 'BOB'
df['3'] = '01'
df['4'] = 'BILL'


def reduce_join(df, columns):
    assert len(columns) > 1
    slist = [df[x].astype(str) for x in columns]
    return reduce(lambda x, y: x + '_' + y, slist[1:], slist[0])


def apply_join(df, columns):
    assert len(columns) > 1
    return df[columns].apply(lambda row:'_'.join(row.values.astype(str)), axis=1)

# ensure outputs are equal
df1 = reduce_join(df, list('1234'))
df2 = apply_join(df, list('1234'))
assert df1.equals(df2)

# profile
%timeit df1 = reduce_join(df, list('1234'))  # 733 ms
%timeit df2 = apply_join(df, list('1234'))   # 8.84 s

Flex-box: Align last row to grid

As other posters have mentioned - there's no clean way to left-align the last row with flexbox (at least as per the current spec)

However, for what it's worth: With the CSS Grid Layout Module this is surprisingly easy to produce:

Basically the relevant code boils down to this:

ul {
  display: grid; /* 1 */
  grid-template-columns: repeat(auto-fill, 100px); /* 2 */
  grid-gap: 1rem; /* 3 */
  justify-content: space-between; /* 4 */
}

1) Make the container element a grid container

2) Set the grid with auto columns of width 100px. (Note the use of auto-fill (as apposed to auto-fit - which (for a 1-row layout) collapses empty tracks to 0 - causing the items to expand to take up the remaining space. This would result in a justified 'space-between' layout when grid has only one row which in our case is not what we want. (check out this demo to see the difference between them)).

3) Set gaps/gutters for the grid rows and columns - here, since want a 'space-between' layout - the gap will actually be a minimum gap because it will grow as necessary.

4) Similar to flexbox.

_x000D_
_x000D_
ul {_x000D_
  display: grid;_x000D_
  grid-template-columns: repeat(auto-fill, 100px);_x000D_
  grid-gap: 1rem;_x000D_
  justify-content: space-between;_x000D_
  _x000D_
  /* boring properties */_x000D_
  list-style: none;_x000D_
  background: wheat;_x000D_
  padding: 2rem;_x000D_
  width: 80vw;_x000D_
  margin: 0 auto;_x000D_
}_x000D_
_x000D_
li {_x000D_
  height: 50px;_x000D_
  border: 1px solid green;_x000D_
}
_x000D_
<ul>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
  <li></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Codepen Demo (Resize to see the effect)

How do I get the information from a meta tag with JavaScript?

function getDescription() {
    var info = document.getElementsByTagName('meta');
    return [].filter.call(info, function (val) {
        if(val.name === 'description') return val;
    })[0].content;
}

update version:

function getDesc() {
    var desc = document.head.querySelector('meta[name=description]');
    return desc ? desc.content : undefined;
}

Extract filename and extension in Bash

I use the following script

$ echo "foo.tar.gz"|rev|cut -d"." -f3-|rev
foo

android - How to get view from context?

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);

How to fix error ::Format of the initialization string does not conform to specification starting at index 0::

I had this in VS2015 and my fix was to change the first line in my WebConfig from

<?xml version="1.0" encoding="utf-8"?>

to

<?xml version="1.0"?>

Curious.

How do I get only directories using Get-ChildItem?

Use:

dir -Directory -Recurse | Select FullName

This will give you an output of the root structure with the folder name for directories only.

Authorize attribute in ASP.NET MVC

Using [Authorize] attributes can help prevent security holes in your application. The way that MVC handles URL's (i.e. routing them to a controller rather than to an actual file) makes it difficult to actually secure everything via the web.config file.

Read more here: http://blogs.msdn.com/b/rickandy/archive/2012/03/23/securing-your-asp-net-mvc-4-app-and-the-new-allowanonymous-attribute.aspx (via archive.org)

What is the difference between json.load() and json.loads() functions

The json.load() method (without "s" in "load") can read a file directly:

import json
with open('strings.json') as f:
    d = json.load(f)
    print(d)

json.loads() method, which is used for string arguments only.

import json

person = '{"name": "Bob", "languages": ["English", "Fench"]}'
print(type(person))
# Output : <type 'str'>

person_dict = json.loads(person)
print( person_dict)
# Output: {'name': 'Bob', 'languages': ['English', 'Fench']}

print(type(person_dict))
# Output : <type 'dict'>

Here , we can see after using loads() takes a string ( type(str) ) as a input and return dictionary.

Angular2 dynamic change CSS property

I did this plunker to explore one way to do what you want.

Here I get mystyle from the parent component but you can get it from a service.

import {Component, View} from 'angular2/angular2'

@Component({
  selector: '[my-person]',
  inputs: [
    'name',
    'mystyle: customstyle'
  ],
  host: {
    '[style.backgroundColor]': 'mystyle.backgroundColor'
  }
})
@View({
  template: `My Person Component: {{ name }}`
})
export class Person {}

Configure Log4Net in web application

often this is due to missing permissions. The windows account the local IIS Application Pool is running with may not have the permission to write to the applications directory. You could create a directory somewhere, give everyone permission to write in it and point your log4net config to that directory. If then a log file is created there, you can modify the permissions for your desired log directory so that the app pool can write to it.

Another reason could be an uninitialized log4net. In a winforms app, you usually configure log4net upon application start. In a web app, you can do this either dynamically (in your logging component, check if you can create a specific Ilog logger using its name, if not -> call configure()) or again upon application start in global.asax.cs.

Does IE9 support console.log, and is it a real function?

How about...

console = { log : function(text) { alert(text); } }

Automatically size JPanel inside JFrame

You need to set a layout manager for the JFrame to use - This deals with how components are positioned. A useful one is the BorderLayout manager.

Simply adding the following line of code should fix your problems:

mainFrame.setLayout(new BorderLayout());

(Do this before adding components to the JFrame)

Traverse all the Nodes of a JSON Object Tree with JavaScript

You can get all keys / values and preserve the hierarchy with this

// get keys of an object or array
function getkeys(z){
  var out=[]; 
  for(var i in z){out.push(i)};
  return out;
}

// print all inside an object
function allInternalObjs(data, name) {
  name = name || 'data';
  return getkeys(data).reduce(function(olist, k){
    var v = data[k];
    if(typeof v === 'object') { olist.push.apply(olist, allInternalObjs(v, name + '.' + k)); }
    else { olist.push(name + '.' + k + ' = ' + v); }
    return olist;
  }, []);
}

// run with this
allInternalObjs({'a':[{'b':'c'},{'d':{'e':5}}],'f':{'g':'h'}}, 'ob')

This is a modification on (https://stackoverflow.com/a/25063574/1484447)

How to define Gradle's home in IDEA?

AFAIK it is GRADLE_HOME not GRADLE_USER_HOME (see gradle installation http://www.gradle.org/installation).

On the other hand I played a bit with Gradle support in Idea 13 Cardea and I think the gradle home is not automatically discover by Idea. If so you can file a issue in youtrack.

Also, if you use gradle 1.6+ you can use the Graldle support for setting the build and wrapper. I think idea automatically discover the wrapper based gradle project.

$ gradle setupBuild --type java-library

$ gradle wrapper

Note: Supported library types: basic, maven, java

Regards

Add CSS to iFrame

Based on solution You've already found How to apply CSS to iframe?:

var cssLink = document.createElement("link") 
cssLink.href = "file://path/to/style.css"; 
cssLink .rel = "stylesheet"; 
cssLink .type = "text/css"; 
frames['iframe'].document.body.appendChild(cssLink);

or more jqueryish (from Append a stylesheet to an iframe with jQuery):

var $head = $("iframe").contents().find("head");                
$head.append($("<link/>", 
    { rel: "stylesheet", href: "file://path/to/style.css", type: "text/css" }));

as for security issues: Disabling same-origin policy in Safari

Log4j: How to configure simplest possible file logging?

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/" debug="false">

   <appender name="fileAppender" class="org.apache.log4j.RollingFileAppender">
      <param name="Threshold" value="INFO" />
      <param name="File" value="sample.log"/>
      <layout class="org.apache.log4j.PatternLayout">
         <param name="ConversionPattern" value="%d %-5p  [%c{1}] %m %n" />
      </layout>
   </appender>

  <root> 
    <priority value ="debug" /> 
    <appender-ref ref="fileAppender" /> 
  </root> 

</log4j:configuration>

Log4j can be a bit confusing. So lets try to understand what is going on in this file: In log4j you have two basic constructs appenders and loggers.

Appenders define how and where things are appended. Will it be logged to a file, to the console, to a database, etc.? In this case you are specifying that log statements directed to fileAppender will be put in the file sample.log using the pattern specified in the layout tags. You could just as easily create a appender for the console or the database. Where the console appender would specify things like the layout on the screen and the database appender would have connection details and table names.

Loggers respond to logging events as they bubble up. If an event catches the interest of a specific logger it will invoke its attached appenders. In the example below you have only one logger the root logger - which responds to all logging events by default. In addition to the root logger you can specify more specific loggers that respond to events from specific packages. These loggers can have their own appenders specified using the appender-ref tags or will otherwise inherit the appenders from the root logger. Using more specific loggers allows you to fine tune the logging level on specific packages or to direct certain packages to other appenders.

So what this file is saying is:

  1. Create a fileAppender that logs to file sample.log
  2. Attach that appender to the root logger.
  3. The root logger will respond to any events at least as detailed as 'debug' level
  4. The appender is configured to only log events that are at least as detailed as 'info'

The net out is that if you have a logger.debug("blah blah") in your code it will get ignored. A logger.info("Blah blah"); will output to sample.log.

The snippet below could be added to the file above with the log4j tags. This logger would inherit the appenders from <root> but would limit the all logging events from the package org.springframework to those logged at level info or above.

  <!-- Example Package level Logger -->
    <logger name="org.springframework">
        <level value="info"/>
    </logger>   

Set margins in a LinearLayout programmatically

Try this:

MarginLayoutParams params = (MarginLayoutParams) view.getLayoutParams();
params.width = 250;
params.leftMargin = 50;
params.topMargin = 50;

Converting an integer to a hexadecimal string in Ruby

You can give to_s a base other than 10:

10.to_s(16)  #=> "a"

Note that in ruby 2.4 FixNum and BigNum were unified in the Integer class. If you are using an older ruby check the documentation of FixNum#to_s and BigNum#to_s

Backup a single table with its data from a database in sql server 2008

This query run for me ( for MySQL). mytable_backup must be present before this query run.

insert into mytable_backup select * from mytable

Detect & Record Audio in Python

The pyaudio website has many examples that are pretty short and clear: http://people.csail.mit.edu/hubert/pyaudio/

Update 14th of December 2019 - Main example from the above linked website from 2017:


"""PyAudio Example: Play a WAVE file."""

import pyaudio
import wave
import sys

CHUNK = 1024

if len(sys.argv) < 2:
    print("Plays a wave file.\n\nUsage: %s filename.wav" % sys.argv[0])
    sys.exit(-1)

wf = wave.open(sys.argv[1], 'rb')

p = pyaudio.PyAudio()

stream = p.open(format=p.get_format_from_width(wf.getsampwidth()),
                channels=wf.getnchannels(),
                rate=wf.getframerate(),
                output=True)

data = wf.readframes(CHUNK)

while data != '':
    stream.write(data)
    data = wf.readframes(CHUNK)

stream.stop_stream()
stream.close()

p.terminate()

How to make a <ul> display in a horizontal row

#ul_top_hypers li {
  display: flex;
}

Combine GET and POST request methods in Spring

@RequestMapping(value = "/testonly", method = { RequestMethod.GET, RequestMethod.POST })
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter,
        @RequestParam(required = false) String parameter1,
        @RequestParam(required = false) String parameter2, 
        BindingResult result, HttpServletRequest request) 
        throws ParseException {

    LONG CODE and SAME LONG CODE with a minor difference
}

if @RequestParam(required = true) then you must pass parameter1,parameter2

Use BindingResult and request them based on your conditions.

The Other way

@RequestMapping(value = "/books", method = RequestMethod.GET)
public ModelAndView listBooks(@ModelAttribute("booksFilter") BooksFilter filter,  
    two @RequestParam parameters, HttpServletRequest request) throws ParseException {

    myMethod();

}


@RequestMapping(value = "/books", method = RequestMethod.POST)
public ModelAndView listBooksPOST(@ModelAttribute("booksFilter") BooksFilter filter, 
        BindingResult result) throws ParseException {

    myMethod();

    do here your minor difference
}

private returntype myMethod(){
    LONG CODE
}

ImportError: No Module named simplejson

On Ubuntu/Debian, you can install it with apt-get install python-simplejson

Map<String, String>, how to print both the "key string" and "value string" together

Inside of your loop, you have the key, which you can use to retrieve the value from the Map:

for (String key: mss1.keySet()) {
    System.out.println(key + ": " + mss1.get(key));
}

__init__ and arguments in Python

If you print(type(Num.getone)) you will get <class 'function'>.

It is just a plain function, and be called as usual (with no arguments):

Num.getone() # returns 1  as expected

but if you print print(type(myObj.getone)) you will get <class 'method'>.

So when you call getone() from an instance of the class, Python automatically "transforms" the function defined in a class into a method.

An instance method requires the first argument to be the instance object. You can think myObj.getone() as syntactic sugar for

Num.getone(myObj) # this explains the Error 'getone()' takes no arguments (1 given).

For example:

class Num:
    def __init__(self,num):
        self.n = num
    def getid(self):
        return id(self)

myObj=Num(3)

Now if you

print(id(myObj) == myObj.getid())    
# returns True

As you can see self and myObj are the same object

How to add url parameters to Django template url tag?

I found the answer here: Is it possible to pass query parameters via Django's {% url %} template tag?

Simply add them to the end:

<a href="{% url myview %}?office=foobar">
For Django 1.5+

<a href="{% url 'myview' %}?office=foobar">

[there is nothing else to improve but I'm getting a stupid error when I fix the code ticks]

TCPDF output without saving file

It works with I for inline as stated, but also with O.

$pdf->Output('name.pdf', 'O');

It is perhaps easier to remember (O for Open).

using extern template (C++11)

You should only use extern template to force the compiler to not instantiate a template when you know that it will be instantiated somewhere else. It is used to reduce compile time and object file size.

For example:

// header.h

template<typename T>
void ReallyBigFunction()
{
    // Body
}

// source1.cpp

#include "header.h"
void something1()
{
    ReallyBigFunction<int>();
}

// source2.cpp

#include "header.h"
void something2()
{
    ReallyBigFunction<int>();
}

This will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>()    // Compiled first time

source2.o
    void something2()
    void ReallyBigFunction<int>()    // Compiled second time

If both files are linked together, one void ReallyBigFunction<int>() will be discarded, resulting in wasted compile time and object file size.

To not waste compile time and object file size, there is an extern keyword which makes the compiler not compile a template function. You should use this if and only if you know it is used in the same binary somewhere else.

Changing source2.cpp to:

// source2.cpp

#include "header.h"
extern template void ReallyBigFunction<int>();
void something2()
{
    ReallyBigFunction<int>();
}

Will result in the following object files:

source1.o
    void something1()
    void ReallyBigFunction<int>() // compiled just one time

source2.o
    void something2()
    // No ReallyBigFunction<int> here because of the extern

When both of these will be linked together, the second object file will just use the symbol from the first object file. No need for discard and no wasted compile time and object file size.

This should only be used within a project, like in times when you use a template like vector<int> multiple times, you should use extern in all but one source file.

This also applies to classes and function as one, and even template member functions.

How can I set the Secure flag on an ASP.NET Session Cookie?

In the <system.web> element, add the following element:

<httpCookies requireSSL="true" />

However, if you have a <forms> element in your system.web\authentication block, then this will override the setting in httpCookies, setting it back to the default false.

In that case, you need to add the requireSSL="true" attribute to the forms element as well.

So you will end up with:

<system.web>
    <authentication mode="Forms">
        <forms requireSSL="true">
            <!-- forms content -->
        </forms>
    </authentication>
</system.web>

See here and here for MSDN documentation of these elements.

How to compile without warnings being treated as errors?

-Wall and -Werror compiler options can cause it, please check if those are used in compiler settings.

How to mock a final class with mockito

Mocking final classes is not supported for mockito-android as per this GitHub issue. You should use Mockk instead for this.

For both unit test and ui test, you can use Mockk with no problem.

Volley - POST/GET parameters

This helper class manages parameters for GET and POST requests:

import java.io.UnsupportedEncodingException;
import java.util.Iterator;
import java.util.Map;    

import org.json.JSONException;
import org.json.JSONObject;

import com.android.volley.NetworkResponse;
import com.android.volley.ParseError;
import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.toolbox.HttpHeaderParser;

public class CustomRequest extends Request<JSONObject> {
    private int mMethod;
    private String mUrl;
    private Map<String, String> mParams;
    private Listener<JSONObject> mListener;

    public CustomRequest(int method, String url, Map<String, String> params,
            Listener<JSONObject> reponseListener, ErrorListener errorListener) {
        super(method, url, errorListener);
        this.mMethod = method;
        this.mUrl = url;
        this.mParams = params;
        this.mListener = reponseListener;
    }

@Override
public String getUrl() {
    if(mMethod == Request.Method.GET) {
        if(mParams != null) {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            Iterator<Map.Entry<String, String>> iterator = mParams.entrySet().iterator();
            int i = 1;
            while (iterator.hasNext()) {
                Map.Entry<String, String> entry = iterator.next();
                if (i == 1) {
                    stringBuilder.append("?" + entry.getKey() + "=" + entry.getValue());
                } else {
                    stringBuilder.append("&" + entry.getKey() + "=" + entry.getValue());
                }
                iterator.remove(); // avoids a ConcurrentModificationException
                i++;
            }
            mUrl = stringBuilder.toString();
        }
    }
    return mUrl;
}

    @Override
    protected Map<String, String> getParams()
            throws com.android.volley.AuthFailureError {
        return mParams;
    };

    @Override
    protected Response<JSONObject> parseNetworkResponse(NetworkResponse response) {
        try {
            String jsonString = new String(response.data,
                    HttpHeaderParser.parseCharset(response.headers));
            return Response.success(new JSONObject(jsonString),
                    HttpHeaderParser.parseCacheHeaders(response));
        } catch (UnsupportedEncodingException e) {
            return Response.error(new ParseError(e));
        } catch (JSONException je) {
            return Response.error(new ParseError(je));
        }
    }

    @Override
    protected void deliverResponse(JSONObject response) {
        // TODO Auto-generated method stub
        mListener.onResponse(response);
    }
}

How do I debug Windows services in Visual Studio?

Unfortunately, if you're trying to debug something at the very start of a Windows Service operation, "attaching" to the running process won't work. I tried using Debugger.Break() within the OnStart procecdure, but with a 64-bit, Visual Studio 2010 compiled application, the break command just throws an error like this:

System error 1067 has occurred.

At that point, you need to set up an "Image File Execution" option in your registry for your executable. It takes five minutes to set up, and it works very well. Here's a Microsoft article where the details are:

How to: Launch the Debugger Automatically

Installing Node.js (and npm) on Windows 10

go to http://nodejs.org/

and hit the button that says "Download For ..."

This'll download the .msi (or .pkg for mac) which will do all the installation and paths for you, unlike the selected answer.

Selecting a Record With MAX Value

What do you mean costs too much? Too much what?

SELECT MAX(Balance) AS MaxBalance, CustomerID FROM CUSTOMERS GROUP BY CustomerID

If your table is properly indexed (Balance) and there has got to be an index on the PK than I am not sure what you mean about costs too much or seems unreliable? There is nothing unreliable about an aggregate that you are using and telling it to do. In this case, MAX() does exactly what you tell it to do - there's nothing magical about it.

Take a look at MAX() and if you want to filter it use the HAVING clause.

How to check ASP.NET Version loaded on a system?

Alternatively, you can create a button on your webpage and in the Page_Load type;

Trace.IsEnabled = True

And in the button click event type;

Response.Write(Trace)

This will bring up all the trace information and you will find your ASP.NET version in the "Response Headers Collection" under "X-ASPNet-Version".

What are the differences between Abstract Factory and Factory design patterns?

A lot of the previous answers do not provide code comparisons between Abstract Factory and Factory Method pattern. The following is my attempt at explaining it via Java. I hope it helps someone in need of a simple explanation.

As GoF aptly says: Abstract Factory provides an interface for creating families of related or dependent objects without specifying their concrete classes.

public class Client {
    public static void main(String[] args) {
        ZooFactory zooFactory = new HerbivoreZooFactory();
        Animal animal1 = zooFactory.animal1();
        Animal animal2 = zooFactory.animal2();
        animal1.sound();
        animal2.sound();

        System.out.println();

        AnimalFactory animalFactory = new CowAnimalFactory();
        Animal animal = animalFactory.createAnimal();
        animal.sound();
    }
}

public interface Animal {
    public void sound();
}

public class Cow implements Animal {

    @Override
    public void sound() {
        System.out.println("Cow moos");
    }
}

public class Deer implements Animal {

    @Override
    public void sound() {
        System.out.println("Deer grunts");
    }

}

public class Hyena implements Animal {

    @Override
    public void sound() {
        System.out.println("Hyena.java");
    }

}

public class Lion implements Animal {

    @Override
    public void sound() {
        System.out.println("Lion roars");
    }

}

public interface ZooFactory {
    Animal animal1();

    Animal animal2();
}

public class CarnivoreZooFactory implements ZooFactory {

    @Override
    public Animal animal1() {
        return new Lion();
    }

    @Override
    public Animal animal2() {
        return new Hyena();
    }

}

public class HerbivoreZooFactory implements ZooFactory {

    @Override
    public Animal animal1() {
        return new Cow();
    }

    @Override
    public Animal animal2() {
        return new Deer();
    }

}

public interface AnimalFactory {
    public Animal createAnimal();
}

public class CowAnimalFactory implements AnimalFactory {

    @Override
    public Animal createAnimal() {
        return new Cow();
    }

}

public class DeerAnimalFactory implements AnimalFactory {

    @Override
    public Animal createAnimal() {
        return new Deer();
    }

}

public class HyenaAnimalFactory implements AnimalFactory {

    @Override
    public Animal createAnimal() {
        return new Hyena();
    }

}

public class LionAnimalFactory implements AnimalFactory {

    @Override
    public Animal createAnimal() {
        return new Lion();
    }

}

What is the best way to update the entity in JPA

That depends on what you want to do, but as you said, getting an entity reference using find() and then just updating that entity is the easiest way to do that.

I'd not bother about performance differences of the various methods unless you have strong indications that this really matters.

How do I get git to default to ssh and not https for new repositories

Set up a repository's origin branch to be SSH

The GitHub repository setup page is just a suggested list of commands (and GitHub now suggests using the HTTPS protocol). Unless you have administrative access to GitHub's site, I don't know of any way to change their suggested commands.

If you'd rather use the SSH protocol, simply add a remote branch like so (i.e. use this command in place of GitHub's suggested command). To modify an existing branch, see the next section.

$ git remote add origin [email protected]:nikhilbhardwaj/abc.git

Modify a pre-existing repository

As you already know, to switch a pre-existing repository to use SSH instead of HTTPS, you can change the remote url within your .git/config file.

[remote "origin"]
    fetch = +refs/heads/*:refs/remotes/origin/*
    -url = https://github.com/nikhilbhardwaj/abc.git
    +url = [email protected]:nikhilbhardwaj/abc.git

A shortcut is to use the set-url command:

$ git remote set-url origin [email protected]:nikhilbhardwaj/abc.git

More information about the SSH-HTTPS switch

How to include *.so library in Android Studio?

I have solved a similar problem using external native lib dependencies that are packaged inside of jar files. Sometimes these architecture dependend libraries are packaged alltogether inside one jar, sometimes they are split up into several jar files. so i wrote some buildscript to scan the jar dependencies for native libs and sort them into the correct android lib folders. Additionally this also provides a way to download dependencies that not found in maven repos which is currently usefull to get JNA working on android because not all native jars are published in public maven repos.

android {
    compileSdkVersion 23
    buildToolsVersion '24.0.0'

    lintOptions {
        abortOnError false
    }


    defaultConfig {
        applicationId "myappid"
        minSdkVersion 17
        targetSdkVersion 23
        versionCode 1
        versionName "1.0.0"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }

    sourceSets {
        main {
            jniLibs.srcDirs = ["src/main/jniLibs", "$buildDir/native-libs"]
        }
    }
}

def urlFile = { url, name ->
    File file = new File("$buildDir/download/${name}.jar")
    file.parentFile.mkdirs()
    if (!file.exists()) {
        new URL(url).withInputStream { downloadStream ->
            file.withOutputStream { fileOut ->
                fileOut << downloadStream
            }
        }
    }
    files(file.absolutePath)
}
dependencies {
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:appcompat-v7:23.3.0'
    compile 'com.android.support:design:23.3.0'
    compile 'net.java.dev.jna:jna:4.2.0'
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-arm.jar?raw=true', 'jna-android-arm')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-armv7.jar?raw=true', 'jna-android-armv7')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-aarch64.jar?raw=true', 'jna-android-aarch64')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86.jar?raw=true', 'jna-android-x86')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-x86-64.jar?raw=true', 'jna-android-x86_64')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips.jar?raw=true', 'jna-android-mips')
    compile urlFile('https://github.com/java-native-access/jna/blob/4.2.2/lib/native/android-mips64.jar?raw=true', 'jna-android-mips64')
}
def safeCopy = { src, dst ->
    File fdst = new File(dst)
    fdst.parentFile.mkdirs()
    fdst.bytes = new File(src).bytes

}

def archFromName = { name ->
    switch (name) {
        case ~/.*android-(x86-64|x86_64|amd64).*/:
            return "x86_64"
        case ~/.*android-(i386|i686|x86).*/:
            return "x86"
        case ~/.*android-(arm64|aarch64).*/:
            return "arm64-v8a"
        case ~/.*android-(armhf|armv7|arm-v7|armeabi-v7).*/:
            return "armeabi-v7a"
        case ~/.*android-(arm).*/:
            return "armeabi"
        case ~/.*android-(mips).*/:
            return "mips"
        case ~/.*android-(mips64).*/:
            return "mips64"
        default:
            return null
    }
}

task extractNatives << {
    project.configurations.compile.each { dep ->
        println "Scanning ${dep.name} for native libs"
        if (!dep.name.endsWith(".jar"))
            return
        zipTree(dep).visit { zDetail ->
            if (!zDetail.name.endsWith(".so"))
                return
            print "\tFound ${zDetail.name}"
            String arch = archFromName(zDetail.toString())
            if(arch != null){
                println " -> $arch"
                safeCopy(zDetail.file.absolutePath,
                        "$buildDir/native-libs/$arch/${zDetail.file.name}")
            } else {
                println " -> No valid arch"
            }
        }
    }
}

preBuild.dependsOn(['extractNatives'])

D3 transform scale and translate

The transforms are SVG transforms (for details, have a look at the standard; here are some examples). Basically, scale and translate apply the respective transformations to the coordinate system, which should work as expected in most cases. You can apply more than one transform however (e.g. first scale and then translate) and then the result might not be what you expect.

When working with the transforms, keep in mind that they transform the coordinate system. In principle, what you say is true -- if you apply a scale > 1 to an object, it will look bigger and a translate will move it to a different position relative to the other objects.

How can I convert a series of images to a PDF from the command line on linux?

Use convert from http://www.imagemagick.org. (Readily supplied as a package in most Linux distributions.)

Import-CSV and Foreach

You can create the headers on the fly (no need to specify delimiter when the delimiter is a comma):

Import-CSV $filepath -Header IP1,IP2,IP3,IP4 | Foreach-Object{
   Write-Host $_.IP1
   Write-Host $_.IP2
   ...
}

Convert a number range to another range, maintaining ratio

List comprehension one liner solution

color_array_new = [int((((x - min(node_sizes)) * 99) / (max(node_sizes) - min(node_sizes))) + 1) for x in node_sizes]

Longer version

def colour_specter(waste_amount):
color_array = []
OldRange = max(waste_amount) - min(waste_amount)
NewRange = 99
for number_value in waste_amount:
    NewValue = int((((number_value - min(waste_amount)) * NewRange) / OldRange) + 1)
    color_array.append(NewValue)
print(color_array)
return color_array

What is the difference between a database and a data warehouse?

A data warehouse is a TYPE of database.

In addition to what folks have already said, data warehouses tend to be OLAP, with indexes, etc. tuned for reading, not writing, and the data is de-normalized / transformed into forms that are easier to read & analyze.

Some folks have said "databases" are the same as OLTP -- this isn't true. OLTP, again, is a TYPE of database.

Other types of "databases": Text files, XML, Excel, CSV..., Flat Files :-)

NameError: name 'datetime' is not defined

It can also be used as below:

from datetime import datetime
start_date = datetime(2016,3,1)
end_date = datetime(2016,3,10)

Error: "setFile(null,false) call failed" when using log4j

this error is coming because of appender file location you have provided is not reachable with current user access.

Quick Solution, change the log4j.appender.FILE.File setting to point to file using absolute path which location is reachable to the current user you have logged in, for example /tmp/myapp.log. Now You should not get an error.

C compile : collect2: error: ld returned 1 exit status

I got this problem, and tried many ways to solve it. Finally, it turned out that make clean and make again solved it. The reason is: I got the source code together with object files compiled previously with an old gcc version. When my newer gcc version wants to link that old object files, it can't resolve some function in there. It happens to me several times that the source code distributors do not clean up before packing, so a make clean saved the day.

image processing to improve tesseract OCR accuracy

Text Recognition depends on a variety of factors to produce a good quality output. OCR output highly depends on the quality of input image. This is why every OCR engine provides guidelines regarding the quality of input image and its size. These guidelines help OCR engine to produce accurate results.

I have written a detailed article on image processing in python. Kindly follow the link below for more explanation. Also added the python source code to implement those process.

Please write a comment if you have a suggestion or better idea on this topic to improve it.

https://medium.com/cashify-engineering/improve-accuracy-of-ocr-using-image-preprocessing-8df29ec3a033

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

You can use native JS so you don't have to rely on external libraries.

(I will use some ES2015 syntax, a.k.a ES6, modern javascript) What is ES2015?

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    });

You can also capture errors if any:

fetch('/api/rest/abc')
    .then(response => response.json())
    .then(data => {
        // Do what you want with your data
    })
    .catch(err => {
        console.error('An error ocurred', err);
    });

By default it uses GET and you don't have to specify headers, but you can do all that if you want. For further reference: Fetch API reference

How to check if input date is equal to today's date?

for completeness, taken from this solution:

You could use toDateString:

var today = new Date();
var isToday = (today.toDateString() == otherDate.toDateString());

no library dependencies, and looking cleaner than the 'setHours()' approach shown in a previous answer, imho

How to change or add theme to Android Studio?

You can change or import a theme by using the icon that the "Duplicate Theme" arrow is pointing to in the photo.

Every one sees color differently. Most times a small change in contrast is all you need. Removing the hase from Dracula by changing the Background color to 242527 was perfect for me.

enter image description here

React JS Error: is not defined react/jsx-no-undef

Here you have not specified class name to be imported from Map.js file. If Map is class exportable class name exist in the Map.js file, your code should be as follow.

import React, { Component } from 'react';
import Map from  './Map';
class App extends Component {
   render() {
     return (
         <div className="App">
            <Map/>
         </div>
     );
   }
}
export default App;

How to remove numbers from a string?

Very close, try:

questionText = questionText.replace(/[0-9]/g, '');

replace doesn't work on the existing string, it returns a new one. If you want to use it, you need to keep it!
Similarly, you can use a new variable:

var withNoDigits = questionText.replace(/[0-9]/g, '');

One last trick to remove whole blocks of digits at once, but that one may go too far:

questionText = questionText.replace(/\d+/g, '');

Where does PHP store the error log? (php5, apache, fastcgi, cpanel)

cPanel Error logs are located in:

/usr/local/cpanel/logs/

/usr/local/apache/logs/

By default Apche logs are located inside:

/var/log/apache

or

/var/log/apache2

If anyone is using custom log location then you can check it by running this command:

cat /etc/apache2/conf/httpd.conf | grep ErrorLog

If you are getting error that apache2 directory does not exist then you can run this command to find correct location by:

whereis apache

or

whereis apache2

Spring MVC Multipart Request with JSON

This must work!

client (angular):

$scope.saveForm = function () {
      var formData = new FormData();
      var file = $scope.myFile;
      var json = $scope.myJson;
      formData.append("file", file);
      formData.append("ad",JSON.stringify(json));//important: convert to JSON!
      var req = {
        url: '/upload',
        method: 'POST',
        headers: {'Content-Type': undefined},
        data: formData,
        transformRequest: function (data, headersGetterFunction) {
          return data;
        }
      };

Backend-Spring Boot:

@RequestMapping(value = "/upload", method = RequestMethod.POST)
    public @ResponseBody
    Advertisement storeAd(@RequestPart("ad") String adString, @RequestPart("file") MultipartFile file) throws IOException {

        Advertisement jsonAd = new ObjectMapper().readValue(adString, Advertisement.class);
//do whatever you want with your file and jsonAd

How to increase scrollback buffer size in tmux?

Open tmux configuration file with the following command:

vim ~/.tmux.conf

In the configuration file add the following line:

set -g history-limit 5000

Log out and log in again, start a new tmux windows and your limit is 5000 now.

Combine two tables that have no common fields

Very hard when you have to do this with three select statments

I tried all proposed techniques up there but it's in-vain

Please see below script. please advice if you have alternative solution

   select distinct x.best_Achiver_ever,y.Today_best_Achiver ,z.Most_Violator from 

    (SELECT  Top(4) ROW_NUMBER() over (order by tl.username)  AS conj, tl. 
     [username] + '-->' + str(count(*)) as best_Achiver_ever 
    FROM[TiketFollowup].[dbo].N_FCR_Tikect_Log_Archive tl
     group by tl.username
     order by count(*) desc) x
      left outer join 

(SELECT 
Top(4) ROW_NUMBER() over (order by tl.username)  as conj, tl.[username] + '-->' + str(count(*)) as Today_best_Achiver
FROM[TiketFollowup].[dbo].[N_FCR_Tikect_Log] tl
where convert(date, tl.stamp, 121) = convert(date,GETDATE(),121)
group by tl.username
order by count(*) desc) y 
on x.conj=y.conj

 left outer join 

(
select  ROW_NUMBER() over (order by count(*)) as conj,username+ '--> ' + str( count(dbo.IsViolated(stamp))) as Most_Violator from N_FCR_Ticket
where dbo.IsViolated(stamp) = 'violated' and  convert(date,stamp, 121) < convert(date,GETDATE(),121)
group by username
order by count(*) desc) z
on x.conj = z.conj

extract digits in a simple way from a python string

>>> x='$120'
>>> import string
>>> a=string.maketrans('','')
>>> ch=a.translate(a, string.digits)
>>> int(x.translate(a, ch))
120

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

SQLMenace said money is inexact. But you don't multiply/divide money by money! How much is 3 dollars times 50 cents? 150 dollarcents? You multiply/divide money by scalars, which should be decimal.

DECLARE
@mon1 MONEY,
@mon4 MONEY,
@num1 DECIMAL(19,4),
@num2 DECIMAL(19,4),
@num3 DECIMAL(19,4),
@num4 DECIMAL(19,4)

SELECT
@mon1 = 100,
@num1 = 100, @num2 = 339, @num3 = 10000

SET @mon4 = @mon1/@num2*@num3
SET @num4 = @num1/@num2*@num3

SELECT @mon4 AS moneyresult,
@num4 AS numericresult

Results in the correct result:

moneyresult           numericresult
--------------------- ---------------------------------------
2949.8525             2949.8525

money is good as long as you don't need more than 4 decimal digits, and you make sure your scalars - which do not represent money - are decimals.

How can I lock a file using java (if possible)

This may not be what you are looking for, but in the interest of coming at a problem from another angle....

Are these two Java processes that might want to access the same file in the same application? Perhaps you can just filter all access to the file through a single, synchronized method (or, even better, using JSR-166)? That way, you can control access to the file, and perhaps even queue access requests.

Reading HTTP headers in a Spring REST controller

Instead of taking the HttpServletRequest object in every method, keep in controllers' context by auto-wiring via the constructor. Then you can access from all methods of the controller.

public class OAuth2ClientController {
    @Autowired
    private OAuth2ClientService oAuth2ClientService;

    private HttpServletRequest request;

    @Autowired
    public OAuth2ClientController(HttpServletRequest request) {
        this.request = request;
    }

    @RequestMapping(method = RequestMethod.POST)
    public ResponseEntity<String> createClient(@RequestBody OAuth2Client client) {
        System.out.println(request.getRequestURI());
        System.out.println(request.getHeader("Content-Type"));

        return ResponseEntity.ok();
    }
}

Sending command line arguments to npm script

jakub.g's answer is correct, however an example using grunt seems a bit complex.

So my simpler answer:

- Sending a command line argument to an npm script

Syntax for sending command line arguments to an npm script:

npm run [command] [-- <args>]

Imagine we have an npm start task in our package.json to kick off webpack dev server:

"scripts": {
  "start": "webpack-dev-server --port 5000"
},

We run this from the command line with npm start

Now if we want to pass in a port to the npm script:

"scripts": {
  "start": "webpack-dev-server --port process.env.port || 8080"
},

running this and passing the port e.g. 5000 via command line would be as follows:

npm start --port:5000

- Using package.json config:

As mentioned by jakub.g, you can alternatively set params in the config of your package.json

"config": {
  "myPort": "5000"
}

"scripts": {
  "start": "webpack-dev-server --port process.env.npm_package_config_myPort || 8080"
},

npm start will use the port specified in your config, or alternatively you can override it

npm config set myPackage:myPort 3000

- Setting a param in your npm script

An example of reading a variable set in your npm script. In this example NODE_ENV

"scripts": {
  "start:prod": "NODE_ENV=prod node server.js",
  "start:dev": "NODE_ENV=dev node server.js"
},

read NODE_ENV in server.js either prod or dev

var env = process.env.NODE_ENV || 'prod'

if(env === 'dev'){
    var app = require("./serverDev.js");
} else {
    var app = require("./serverProd.js");
}

jQuery Uncaught TypeError: Cannot read property 'fn' of undefined (anonymous function)

Import the jquery CDN as a first

(e.g)

<script
  src="https://code.jquery.com/jquery-3.3.1.min.js"
  integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
  crossorigin="anonymous"></script>

Opening PDF String in new window with javascript

This one worked for me.

window.open("data:application/octet-stream;charset=utf-16le;base64,"+data64);

This one worked too

 let a = document.createElement("a");
 a.href = "data:application/octet-stream;base64,"+data64;
 a.download = "documentName.pdf"
 a.click();

How To Save Canvas As An Image With canvas.toDataURL()?

This solution allows you to change the name of the downloaded file:

HTML:

<a id="link"></a>

JAVASCRIPT:

  var link = document.getElementById('link');
  link.setAttribute('download', 'MintyPaper.png');
  link.setAttribute('href', canvas.toDataURL("image/png").replace("image/png", "image/octet-stream"));
  link.click();

Remove CSS class from element with JavaScript (no jQuery)

function hasClass(ele,cls) {
    return ele.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)'));
}

function removeClass(ele,cls) {
        if (hasClass(ele,cls)) {
            var reg = new RegExp('(\\s|^)'+cls+'(\\s|$)');
            ele.className=ele.className.replace(reg,' ');
        }
    }

How do I convert an interval into a number of hours with postgres?

         select date 'now()' - date '1955-12-15';

Here is the simple query which calculates total no of days.

SQL Sum Multiple rows into one

You're grouping with BillDate, but the bill dates are different for each account so your rows are not being grouped. If you think about it, that doesn't even make sense - they are different bills, and have different dates. The same goes for the Bill - you're attempting to sum bills for an account, why would you group by that?

If you leave BillDate and Bill off of the select and group by clauses you'll get the correct results.

SELECT AccountNumber, SUM(Bill)
FROM Table1
GROUP BY AccountNumber

installing python packages without internet and using source code as .tar.gz and .whl

If you want to install a bunch of dependencies from, say a requirements.txt, you would do:

mkdir dependencies
pip download -r requirements.txt -d "./dependencies"
tar cvfz dependencies.tar.gz dependencies

And, once you transfer the dependencies.tar.gz to the machine which does not have internet you would do:

tar zxvf dependencies.tar.gz
cd dependencies
pip install * -f ./ --no-index

Best way to create a temp table with same columns and type as a permanent table

Sortest one...

select top 0 * into #temptable from mytable

Note : This creates an empty copy of temp, But it doesn't create a primary key

Draw in Canvas by finger, Android

I think it's important to add a thing, if you use the layout inflation that constructor in the drawview is not correct, add these constructors in the class:

public DrawingView(Context c, AttributeSet attrs) {
    super(c, attrs);
    ...
}

public DrawingView(Context c, AttributeSet attrs, int defStyle) {
    super(c, attrs, defStyle);
    ...
}

or the android system fails to inflate the layout file. I hope this could to help.

Uncaught ReferenceError: <function> is not defined at HTMLButtonElement.onclick

Place your script inside the body tag

<body>
  // Rest of html
  <script>
  function hideButton() {
    $(".loading").hide();
  }
function showButton() {
  $(".loading").show();
}
</script> 
< /body>

If you check this JSFIDDLE and click on javascript, you will see the load Type body is selected

Pure Javascript listen to input value change

Actually, the ticked answer is exactly right, but the answer can be in ES6 shape:

HTMLInputElementObject.oninput = () => {
  console.log('run'); // Do something
}

Or can be written like below:

HTMLInputElementObject.addEventListener('input', (evt) => {
  console.log('run'); // Do something
});

Fill remaining vertical space with CSS using display:flex

Use the flex-grow property to the main content div and give the dispaly: flex; to its parent;

_x000D_
_x000D_
body {_x000D_
    height: 100%;_x000D_
    position: absolute;_x000D_
    margin: 0;_x000D_
}_x000D_
section {_x000D_
  height: 100%;_x000D_
  display: flex;_x000D_
  flex-direction : column;_x000D_
}_x000D_
header {_x000D_
  background: tomato;_x000D_
}_x000D_
div {_x000D_
  flex: 1; /* or flex-grow: 1  */;_x000D_
  overflow-x: auto;_x000D_
  background: gold;_x000D_
}_x000D_
footer {_x000D_
  background: lightgreen;_x000D_
  min-height: 60px;_x000D_
}
_x000D_
<section>_x000D_
  <header>_x000D_
    header: sized to content_x000D_
    <br>(but is it really?)_x000D_
  </header>_x000D_
  <div>_x000D_
    main content: fills remaining space<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
    x<br>x<br>x<br>x<br>x<br>x<br>x<br>x<br>_x000D_
  </div>_x000D_
  <footer>_x000D_
    footer: fixed height in px_x000D_
  </footer>_x000D_
</section>
_x000D_
_x000D_
_x000D_

Interpreting "condition has length > 1" warning from `if` function

if statement is not vectorized. For vectorized if statements you should use ifelse. In your case it is sufficient to write

w <- function(a){
if (any(a>0)){
  a/sum(a)
}
  else 1
}

or a short vectorised version

ifelse(a > 0, a/sum(a), 1)

It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse gives output vector of length equal to length of a.

undefined reference to `WinMain@16'

Check that All Files are Included in Your Project:

I had this same error pop up after I updated cLion. After hours of tinkering, I noticed one of my files was not included in the project target. After I added it back to the active project, I stopped getting the undefined reference to winmain16, and the code compiled.

Edit: It's also worthwhile to check the build settings within your IDE.

(Not sure if this error is related to having recently updated the IDE - could be causal or simply correlative. Feel free to comment with any insight on that factor!)

How to change users in TortoiseSVN

After struggling with this and trying all the answers on this page, I finally realized I had the incorrect credentials stored by windows for the server that hosts our subversion. I cleared this stored value from windows credentials and all is well.

https://web.archive.org/web/20160614002053/http://windows.microsoft.com/en-us/windows7/remove-stored-passwords-certificates-and-other-credentials

Import cycle not allowed

I just encountered this. You may be accessing a method/type from within the same package using the package name itself.

Here is an example to illustrate what I mean:

In foo.go:

// foo.go
package foo

func Foo() {...}

In foo_test.go:

// foo_test.go
package foo

// try to access Foo()
foo.Foo() // WRONG <== This was the issue. You are already in package foo, there is no need to use foo.Foo() to access Foo()
Foo() // CORRECT

css ellipsis on second line

What a shame that you can't get it to work over two lines! Would be awesome if the element was display block and had a height set to 2em or something, and when the text overflowed it would show an ellipsis!

For a single liner you can use:

.show-ellipsis {
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
}

For multiple lines maybe you could use a Polyfill such as jQuery autoellipsis which is on github http://pvdspek.github.com/jquery.autoellipsis/

Java: Get month Integer from Date

java.time (Java 8)

You can also use the java.time package in Java 8 and convert your java.util.Date object to a java.time.LocalDate object and then just use the getMonthValue() method.

Date date = new Date();
LocalDate localDate = date.toInstant().atZone(ZoneId.systemDefault()).toLocalDate();
int month = localDate.getMonthValue();

Note that month values are here given from 1 to 12 contrary to cal.get(Calendar.MONTH) in adarshr's answer which gives values from 0 to 11.

But as Basil Bourque said in the comments, the preferred way is to get a Month enum object with the LocalDate::getMonth method.

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

Does adding a duplicate value to a HashSet/HashMap replace the previous value

HashMap basically contains Entry which subsequently contains Key(Object) and Value(Object).Internally HashSet are HashMap and HashMap do replace values as some of you already pointed..but does it really replaces the keys???No ..and that is the trick here. HashMap keeps its value as key in the underlying HashMap and value is just a dummy object.So if u try to reinsert same Value in HashMap(Key in underlying Map).It just replaces the dummy value and not the Key(Value for HashSet).

Look at the below code for HashSet Class:

public boolean  [More ...] add(E e) {

   return map.put(e, PRESENT)==null;
}

Here e is the value for HashSet but key for underlying map.and key is never replaced. Hope i am able to clear the confusion.

Define an <img>'s src attribute in CSS

CSS is not used to define values to DOM element attributes, javascript would be more suitable for this.

Java: Sending Multiple Parameters to Method

You can use varargs

public function yourFunction(Parameter... parameters)

See also

Java multiple arguments dot notation - Varargs

When using SASS how can I import a file from a different directory?

Gulp will do the job for watching your sass files and also adding paths of other file with includePaths. example:

gulp.task('sass', function() {
  return gulp.src('scss/app.scss')
    .pipe($.sass({
      includePaths: sassPaths
    })
    .pipe(gulp.dest('css'));
});

Command failed due to signal: Segmentation fault: 11

In my case I had declared the following property in one of my ViewControllers subclass:

@property NSString * title

I think this was conflicting with the already existing title property in ViewController. I renamed this property to something else and refactored its use and the error disappeared.

PHP CURL CURLOPT_SSL_VERIFYPEER ignored

We had the same problem on a CentOS7 machine. Disabling the VERIFYHOST VERIFYPEER did not solve the problem, we did not have the cURL error anymore but the response still was invalid. Doing a wget to the same link as the cURL was doing also resulted in a certificate error.

-> Our solution also was to reboot the VPS, this solved it and we were able to complete the request again.

For us this seemed to be a memory corruption problem. Rebooting the VPS reloaded the libary in the memory again and now it works. So if the above solution from @clover does not work try to reboot your machine.

tomcat - CATALINA_BASE and CATALINA_HOME variables

CATALINA_BASE is optional.

However, in the following scenarios it helps to setup CATALINA_BASE that is separate from CATALINA_HOME.

  1. When more than 1 instances of tomcat are running on same host

    • This helps have only 1 runtime of tomcat installation, with multiple CATALINA_BASE server configurations running on separate ports.
    • If any patching, or version upgrade needs be, only 1 installation changes required, or need to be tested/verified/signed-off.
  2. Separation of concern (Single responsibility)

    • Tomcat runtime is standard and does not change during every release process. i.e. Tomcat binaries
    • Release process may add more stuff as webapplication (webapps folder), environment configuration (conf directory), logs/temp/work directory

Create Elasticsearch curl query for not null and not empty("")

As @luqmaan pointed out in the comments, the documentation says that the filter exists doesn't filter out empty strings as they are considered non-null values.

So adding to @DrTech's answer, to effectively filter null and empty string values out, you should use something like this:

{
    "query" : {
        "constant_score" : {
            "filter" : {
                "bool": {
                    "must": {"exists": {"field": "<your_field_name_here>"}},
                    "must_not": {"term": {"<your_field_name_here>": ""}}
                }
            }
        }
    }
}

plot legends without border and with white background

Use option bty = "n" in legend to remove the box around the legend. For example:

legend(1, 5,
       "This legend text should not be disturbed by the dotted grey lines,\nbut the plotted dots should still be visible",
       bty = "n")

How to close a Tkinter window by pressing a Button?

With minimal editing to your code (Not sure if they've taught classes or not in your course), change:

def close_window(root): 
    root.destroy()

to

def close_window(): 
    window.destroy()

and it should work.


Explanation:

Your version of close_window is defined to expect a single argument, namely root. Subsequently, any calls to your version of close_window need to have that argument, or Python will give you a run-time error.

When you created a Button, you told the button to run close_window when it is clicked. However, the source code for Button widget is something like:

# class constructor
def __init__(self, some_args, command, more_args):
    #...
    self.command = command
    #...

# this method is called when the user clicks the button
def clicked(self):
    #...
    self.command() # Button calls your function with no arguments.
    #...

As my code states, the Button class will call your function with no arguments. However your function is expecting an argument. Thus you had an error. So, if we take out that argument, so that the function call will execute inside the Button class, we're left with:

def close_window(): 
    root.destroy()

That's not right, though, either, because root is never assigned a value. It would be like typing in print(x) when you haven't defined x, yet.

Looking at your code, I figured you wanted to call destroy on window, so I changed root to window.

Stuck while installing Visual Studio 2015 (Update for Microsoft Windows (KB2999226))

Today i also face this type of problem during visual studio 2015 Community installation. As i have 64bit OS. I used https://www.microsoft.com/en-us/download/details.aspx?id=49093 link to update KB2999226 mannualy.

Try It. Good luck.

apc vs eaccelerator vs xcache

Even both eacceleator and xcache perform quite well during moderate loads, APC maintains its stability under serious request intensity. If we're talking about a few hundred requests/sec here, you'll not feel the difference. But if you're trying to respond more, definetely stick with APC. Especially if your application has overly dynamic characteristics which will likely cause locking issues under such loads. http://www.ipsure.com/blog/2011/eaccelerator-as-zend-extension-high-load-averages-issue/ may help.

Where do I find some good examples for DDD?

.NET DDD Sample from Domain-Driven Design Book by Eric Evans can be found here: http://dddsamplenet.codeplex.com

Cheers,

Jakub G

CSS: background-color only inside the margin

That is not possible du to the Box Model. However you could use a workaround with css3's border-image, or border-color in general css.

However im unsure whether you may have a problem with resetting. Some browsers do set a margin to html as well. See Eric Meyers Reset CSS for more!

html{margin:0;padding:0;}

How does internationalization work in JavaScript?

Some of it is native, the rest is available through libraries.

For example Datejs is a good international date library.

For the rest, it's just about language translation, and JavaScript is natively Unicode compatible (as well as all major browsers).

Android TabLayout Android Design

I am facing some issue with menu change when fragment changes in ViewPager. I ended up implemented below code.

DashboardFragment

public class DashboardFragment extends BaseFragment {

    private Context mContext;
    private TabLayout mTabLayout;
    private ViewPager mViewPager;
    private DashboardPagerAdapter mAdapter;
    private OnModuleChangeListener onModuleChangeListener;
    private NavDashBoardActivity activityInstance;

    public void setOnModuleChangeListener(OnModuleChangeListener onModuleChangeListener) {
        this.onModuleChangeListener = onModuleChangeListener;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.dashboard_fragment, container, false);
    }

    //pass -1 if you want to get it via pager
    public Fragment getFragmentFromViewpager(int position) {
        if (position == -1)
            position = mViewPager.getCurrentItem();
        return ((Fragment) (mAdapter.instantiateItem(mViewPager, position)));
    }

    @Override
    public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);

        mContext = getActivity();

        activityInstance = (NavDashBoardActivity) getActivity();

        mTabLayout = (TabLayout) view.findViewById(R.id.tab_layout);
        mViewPager = (ViewPager) view.findViewById(R.id.view_pager);

        final List<EnumUtils.Module> moduleToShow = getModuleToShowList();
        mViewPager.setOffscreenPageLimit(moduleToShow.size());

        for(EnumUtils.Module module :moduleToShow)
            mTabLayout.addTab(mTabLayout.newTab().setText(EnumUtils.Module.getTabText(module)));

        updateTabPagerAndMenu(0 , moduleToShow);

        mAdapter = new DashboardPagerAdapter(getFragmentManager(),moduleToShow);
        mViewPager.setOffscreenPageLimit(mAdapter.getCount());

        mViewPager.setAdapter(mAdapter);

        mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(final TabLayout.Tab tab) {
                    mViewPager.post(new Runnable() {
                    @Override
                    public void run() {
                        mViewPager.setCurrentItem(tab.getPosition());
                    }
                });
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {
            }
        });

        mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
                //added to redraw menu on scroll
            }

            @Override
            public void onPageSelected(int position) {
                updateTabPagerAndMenu(position , moduleToShow);
            }

            @Override
            public void onPageScrollStateChanged(int state) {
            }
        });
    }

    //also validate other checks and this method should be in SharedPrefs...
    public static List<EnumUtils.Module> getModuleToShowList(){
        List<EnumUtils.Module> moduleToShow = new ArrayList<>();

        moduleToShow.add(EnumUtils.Module.HOME);
        moduleToShow.add(EnumUtils.Module.ABOUT);

        return moduleToShow;
    }

    public void setCurrentTab(final int position){
        if(mViewPager != null){
            mViewPager.postDelayed(new Runnable() {
                @Override
                public void run() {
                    mViewPager.setCurrentItem(position);
                }
            },100);
        }
    }

    private Fragment getCurrentFragment(){
        return mAdapter.getCurrentFragment();
    }

    private void updateTabPagerAndMenu(int position , List<EnumUtils.Module> moduleToShow){
        //it helps to change menu on scroll
        //http://stackoverflow.com/a/27984263/3496570
        //No effect after changing below statement
        ActivityCompat.invalidateOptionsMenu(getActivity());
        if(mTabLayout != null)
            mTabLayout.getTabAt(position).select();

        if(onModuleChangeListener != null){

            if(activityInstance != null){
                activityInstance.updateStatusBarColor(
                        EnumUtils.Module.getStatusBarColor(moduleToShow.get(position)));
            }
            onModuleChangeListener.onModuleChanged(moduleToShow.get(position));

            mTabLayout.setSelectedTabIndicatorColor(EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
            mTabLayout.setTabTextColors(ContextCompat.getColor(mContext,android.R.color.black)
                    , EnumUtils.Module.getModuleColor(moduleToShow.get(position)));
        }
    }
}

dashboardfragment.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:id="@+id/main_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <!-- our tablayout to display tabs  -->
    <android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="?attr/colorPrimary"
        android:minHeight="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        app:tabBackground="@android:color/white"
        app:tabGravity="fill"
        app:tabIndicatorHeight="4dp"
        app:tabMode="scrollable"
        app:tabSelectedTextColor="@android:color/black"
        app:tabTextColor="@android:color/black" />

    <!-- View pager to swipe views -->
    <android.support.v4.view.ViewPager
        android:id="@+id/view_pager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</LinearLayout>

DashboardPagerAdapter

public class DashboardPagerAdapter extends FragmentPagerAdapter {

private List<EnumUtils.Module> moduleList;
private Fragment mCurrentFragment = null;

public DashboardPagerAdapter(FragmentManager fm, List<EnumUtils.Module> moduleList){
    super(fm);
    this.moduleList = moduleList;
}

@Override
public Fragment getItem(int position) {
    return EnumUtils.Module.getDashboardFragment(moduleList.get(position));
}

@Override
public int getCount() {
    return moduleList.size();
}

@Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
    if (getCurrentFragment() != object) {
        mCurrentFragment = ((Fragment) object);
    }
    super.setPrimaryItem(container, position, object);
}

public Fragment getCurrentFragment() {
    return mCurrentFragment;
}

public int getModulePosition(EnumUtils.Module moduleName){
    for(int x = 0 ; x < moduleList.size() ; x++){
        if(moduleList.get(x).equals(moduleName))
            return x;
    }
    return -1;
}

}

And in each page of Fragment setHasOptionMenu(true) in onCreate and implement onCreateOptionMenu. then it will work properly.

dASHaCTIVITY

public class NavDashBoardActivity extends BaseActivity
        implements NavigationView.OnNavigationItemSelectedListener {

    private Context mContext;
    private DashboardFragment dashboardFragment;
    private Toolbar mToolbar;
    private DrawerLayout drawer;
    private ActionBarDrawerToggle toggle;

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

        mContext = NavDashBoardActivity.this;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(ContextCompat.getColor(mContext,R.color.yellow_action_bar));
        }

        mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);

        updateToolbarText(new ToolbarTextBO("NCompass " ,""));

        drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        toggle = new ActionBarDrawerToggle(
                this, drawer, mToolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
        drawer.addDrawerListener(toggle);
        toggle.syncState();

        //onclick of back button on Navigation it will popUp fragment...
        toggle.setToolbarNavigationClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(!toggle.isDrawerIndicatorEnabled()) {
                    getSupportFragmentManager().popBackStack();
                }
            }
        });

        final NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
        navigationView.setItemIconTintList(null);//It helps to show icon on Navigation
        updateNavigationMenuItem(navigationView);

        navigationView.setNavigationItemSelectedListener(this);

        //Left Drawer Upper Section
        View headerLayout = navigationView.getHeaderView(0); // 0-index header

        TextView userNameTv = (TextView) headerLayout.findViewById(R.id.tv_user_name);
        userNameTv.setText(AuthSharePref.readUserLoggedIn().getFullName());
        RoundedImageView ivUserPic = (RoundedImageView) headerLayout.findViewById(R.id.iv_user_pic);

        ivUserPic.setImageResource(R.drawable.profile_img);

        headerLayout.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                //close drawer and add a fragment to it
                drawer.closeDrawers();//also try other methods..
            }
        });

        //ZA code starts...
        dashboardFragment = new DashboardFragment();
        dashboardFragment.setOnModuleChangeListener(new OnModuleChangeListener() {
            @Override
            public void onModuleChanged(EnumUtils.Module module) {
                if(mToolbar != null){
                    mToolbar.setBackgroundColor(EnumUtils.Module.getModuleColor(module));

                    if(EnumUtils.Module.getMenuID(module) != -1)
                        navigationView.getMenu().findItem(EnumUtils.Module.getMenuID(module)).setChecked(true);
                }
            }
        });

        addBaseFragment(dashboardFragment);
        backStackListener();
    }



    public void updateStatusBarColor(int colorResourceID){
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().setStatusBarColor(colorResourceID);
        }
    }

    private void updateNavigationMenuItem(NavigationView navigationView){
        List<EnumUtils.Module> modules =  DashboardFragment.getModuleToShowList();

        if(!modules.contains(EnumUtils.Module.MyStores)){
            navigationView.getMenu().findItem(R.id.nav_my_store).setVisible(false);
        }
        if(!modules.contains(EnumUtils.Module.Livewall)){
            navigationView.getMenu().findItem(R.id.nav_live_wall).setVisible(false);
        }
    }

    private void backStackListener(){
        getSupportFragmentManager().addOnBackStackChangedListener(new FragmentManager.OnBackStackChangedListener() {
            @Override
            public void onBackStackChanged() {

                if(getSupportFragmentManager().getBackStackEntryCount() >= 1)
                {
                    toggle.setDrawerIndicatorEnabled(false); //disable "hamburger to arrow" drawable
                    toggle.setHomeAsUpIndicator(R.drawable.ic_arrow_back_black_24dp); //set your own
                    ///toggle.setDrawerArrowDrawable();
                    ///toggle.setDrawerIndicatorEnabled(false); // this will hide hamburger image
                    ///Toast.makeText(mContext,"Update to Arrow",Toast.LENGTH_SHORT).show();
                }
                else{
                    toggle.setDrawerIndicatorEnabled(true);
                }
                if(getSupportFragmentManager().getBackStackEntryCount() >0){
                    if(getCurrentFragment() instanceof DashboardFragment){
                        Fragment subFragment = ((DashboardFragment) getCurrentFragment())
                                .getViewpager(-1);
                    }
                }
                else{

                }
            }
        });
    }

    private void updateToolBarTitle(String title){
        getSupportActionBar().setTitle(title);
    }
    public void updateToolBarColor(String hexColor){
        if(mToolbar != null)
            mToolbar.setBackgroundColor(Color.parseColor(hexColor));
    }

    @Override
    public void onBackPressed() {
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        if (drawer.isDrawerOpen(GravityCompat.START)) {
            drawer.closeDrawer(GravityCompat.START);
        } else {
            super.onBackPressed();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        if (drawer.isDrawerOpen(GravityCompat.START))
            getMenuInflater().inflate(R.menu.empty, menu);

        return super.onCreateOptionsMenu(menu);//true is wriiten first..
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == android.R.id.home)
        {
            if (drawer.isDrawerOpen(GravityCompat.START))
                drawer.closeDrawer(GravityCompat.START);
            else {
                if (getSupportFragmentManager().getBackStackEntryCount() > 0) {

                } else
                    drawer.openDrawer(GravityCompat.START);
            }

            return false;///true;
        }

        return false;// false so that fragment can also handle the menu event. Otherwise it is handled their
        ///return super.onOptionsItemSelected(item);
    }

    @SuppressWarnings("StatementWithEmptyBody")
    @Override
    public boolean onNavigationItemSelected(MenuItem item) {
        // Handle navigation view item clicks here.
        int id = item.getItemId();

        if (id == R.id.nav_my_store) {
            // Handle the camera action
            dashboardFragment.setCurrentTab(EnumUtils.Module.MyStores);
        } 
        }else if  (id == R.id.nav_log_out)  {
            Dialogs.logOut(mContext);
        }

        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
        return true;
    }


    public void updateToolbarText(ToolbarTextBO toolbarTextBO){
        mToolbar.setTitle("");
        mToolbar.setSubtitle("");
        if(toolbarTextBO.getTitle() != null && !toolbarTextBO.getTitle().isEmpty())
            mToolbar.setTitle(toolbarTextBO.getTitle());
        if(toolbarTextBO.getDescription() != null && !toolbarTextBO.getDescription().isEmpty())
            mToolbar.setSubtitle(toolbarTextBO.getDescription());*/

    }

    @Override
    public void onPostCreate(@Nullable Bundle savedInstanceState, @Nullable PersistableBundle persistentState) {
        super.onPostCreate(savedInstanceState, persistentState);
        // Sync the toggle state after onRestoreInstanceState has occurred.
        toggle.syncState();
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        toggle.onConfigurationChanged(newConfig);
    }
}

How do I check in python if an element of a list is empty?

Just check if that element is equal to None type or make use of NOT operator ,which is equivalent to the NULL type you observe in other languages.

if not A[i]:
    ## do whatever

Anyway if you know the size of your list then you don't need to do all this.

How can I bind to the change event of a textarea in jQuery?

2018, without JQUERY

The question is with JQuery, it's just FYI.

JS

let textareaID = document.getElementById('textareaID');
let yourBtnID = document.getElementById('yourBtnID');
textareaID.addEventListener('input', function() {
    yourBtnID.style.display = 'none';
    if (textareaID.value.length) {
        yourBtnID.style.display = 'inline-block';
    }
});

HTML

<textarea id="textareaID"></textarea>
<button id="yourBtnID" style="display: none;">click me</div>