Programs & Examples On #Jekyll extensions

Expand div to max width when float:left is set

this usage may solve your problem.

width: calc(100% - 100px);

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
_x000D_
<head>_x000D_
  <meta charset="UTF-8" />_x000D_
  <title>Content with Menu</title>_x000D_
  <style>_x000D_
    .content .left {_x000D_
      float: left;_x000D_
      width: 100px;_x000D_
      background-color: green;_x000D_
    }_x000D_
    _x000D_
    .content .right {_x000D_
      float: left;_x000D_
      width: calc(100% - 100px);_x000D_
      background-color: red;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="content">_x000D_
    <div class="left">_x000D_
      <p>Hi, Flo!</p>_x000D_
    </div>_x000D_
    <div class="right">_x000D_
      <p>is</p>_x000D_
      <p>this</p>_x000D_
      <p>what</p>_x000D_
      <p>you are looking for?</p>_x000D_
    </div>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

SOAP client in .NET - references or examples?

Take a look at "using WCF Services with PHP". It explains the basics of what you need.

As a theory summary:

WCF or Windows Communication Foundation is a technology that allow to define services abstracted from the way - the underlying communication method - they'll be invoked.

The idea is that you define a contract about what the service does and what the service offers and also define another contract about which communication method is used to actually consume the service, be it TCP, HTTP or SOAP.

You have the first part of the article here, explaining how to create a very basic WCF Service.

More resources:

Using WCF with PHP5.

Aslo take a look to NuSOAP. If you now NuSphere this is a toolkit to let you connect from PHP to an WCF service.

What is the best way to measure execution time of a function?

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

MS-DOS Batch file pause with enter key

You can do it with the pause command, example:

dir
pause
echo Now about to end...
pause

How to save a list as numpy array in python?

First of all, I'd recommend you to go through NumPy's Quickstart tutorial, which will probably help with these basic questions.

You can directly create an array from a list as:

import numpy as np
a = np.array( [2,3,4] )

Or from a from a nested list in the same way:

import numpy as np
a = np.array( [[2,3,4], [3,4,5]] )

Error:Conflict with dependency 'com.google.code.findbugs:jsr305'

In your app's build.gradle add the following:

android {
    configurations.all {
        resolutionStrategy.force 'com.google.code.findbugs:jsr305:1.3.9'
    }
}

Enforces Gradle to only compile the version number you state for all dependencies, no matter which version number the dependencies have stated.

How to compare the contents of two string objects in PowerShell

You can do it in two different ways.

Option 1: The -eq operator

>$a = "is"
>$b = "fission"
>$c = "is"
>$a -eq $c
True
>$a -eq $b
False

Option 2: The .Equals() method of the string object. Because strings in PowerShell are .Net System.String objects, any method of that object can be called directly.

>$a.equals($b)
False
>$a.equals($c)
True
>$a|get-member -membertype method

List of System.String methods follows.

Running the new Intel emulator for Android

  1. Download HAXM from the Intel site.

  2. Install it.

  3. And then run the AVD from AndroidStudio, menu -> Tools -> AVD. Choose x86.

It works!

Using sed and grep/egrep to search and replace

My use case was I wanted to replace foo:/Drive_Letter with foo:/bar/baz/xyz In my case I was able to do it with the following code. I was in the same directory location where there were bulk of files.

find . -name "*.library" -print0 | xargs -0 sed -i '' -e 's/foo:\/Drive_Letter:/foo:\/bar\/baz\/xyz/g'

hope that helped.

UPDATE s|foo:/Drive_letter:|foo:/ba/baz/xyz|g

How do I disable log messages from the Requests library?

Kbrose's guidance on finding which logger was generating log messages was immensely useful. For my Django project, I had to sort through 120 different loggers until I found that it was the elasticsearch Python library that was causing issues for me. As per the guidance in most of the questions, I disabled it by adding this to my loggers:

      ...
      'elasticsearch': {
          'handlers': ['console'],
          'level': logging.WARNING,
      },     
      ...

Posting here in case someone else is seeing the unhelpful log messages come through whenever they run an Elasticsearch query.

Iterating through struct fieldnames in MATLAB

Since fields or fns are cell arrays, you have to index with curly brackets {} in order to access the contents of the cell, i.e. the string.

Note that instead of looping over a number, you can also loop over fields directly, making use of a neat Matlab features that lets you loop through any array. The iteration variable takes on the value of each column of the array.

teststruct = struct('a',3,'b',5,'c',9)

fields = fieldnames(teststruct)

for fn=fields'
  fn
  %# since fn is a 1-by-1 cell array, you still need to index into it, unfortunately
  teststruct.(fn{1})
end

What is the difference between cssSelector & Xpath and which is better with respect to performance for cross browser testing?

I’m going to hold the unpopular on SO selenium tag opinion that XPath is preferable to CSS in the longer run.

This long post has two sections - first I'll put a back-of-the-napkin proof the performance difference between the two is 0.1-0.3 milliseconds (yes; that's 100 microseconds), and then I'll share my opinion why XPath is more powerful.


Performance difference

Let's first tackle "the elephant in the room" – that xpath is slower than css.

With the current cpu power (read: anything x86 produced since 2013), even on browserstack/saucelabs/aws VMs, and the development of the browsers (read: all the popular ones in the last 5 years) that is hardly the case. The browser's engines have developed, the support of xpath is uniform, IE is out of the picture (hopefully for most of us). This comparison in the other answer is being cited all over the place, but it is very contextual – how many are running – or care about – automation against IE8?

If there is a difference, it is in a fraction of a millisecond.

Yet, most higher-level frameworks add at least 1ms of overhead over the raw selenium call anyways (wrappers, handlers, state storing etc); my personal weapon of choice – RobotFramework – adds at least 2ms, which I am more than happy to sacrifice for what it provides. A network roundtrip from an AWS us-east-1 to BrowserStack's hub is usually 11 milliseconds.

So with remote browsers if there is a difference between xpath and css, it is overshadowed by everything else, in orders of magnitude.


The measurements

There are not that many public comparisons (I've really seen only the cited one), so – here's a rough single-case, dummy and simple one.
It will locate an element by the two strategies X times, and compare the average time for that.

The target – BrowserStack's landing page, and its "Sign Up" button; a screenshot of the html as writing this post:

enter image description here

Here's the test code (python):

from selenium import webdriver
import timeit


if __name__ == '__main__':

    xpath_locator = '//div[@class="button-section col-xs-12 row"]'
    css_locator = 'div.button-section.col-xs-12.row'

    repetitions = 1000

    driver = webdriver.Chrome()
    driver.get('https://www.browserstack.com/')

    css_time = timeit.timeit("driver.find_element_by_css_selector(css_locator)", 
                             number=repetitions, globals=globals())
    xpath_time = timeit.timeit('driver.find_element_by_xpath(xpath_locator)', 
                             number=repetitions, globals=globals())

    driver.quit()

    print("css total time {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, css_time, (css_time/repetitions)*1000))
    print("xpath total time for {} repeats: {:.2f}s, per find: {:.2f}ms".
          format(repetitions, xpath_time, (xpath_time/repetitions)*1000))

For those not familiar with Python – it opens the page, and finds the element – first with the css locator, then with the xpath; the find operation is repeated 1,000 times. The output is the total time in seconds for the 1,000 repetitions, and average time for one find in milliseconds.

The locators are:

  • for xpath – "a div element having this exact class value, somewhere in the DOM";
  • the css is similar – "a div element with this class, somewhere in the DOM".

Deliberately chosen not to be over-tuned; also, the class selector is cited for the css as "the second fastest after an id".

The environment – Chrome v66.0.3359.139, chromedriver v2.38, cpu: ULV Core M-5Y10 usually running at 1.5GHz (yes, a "word-processing" one, not even a regular i7 beast).

Here's the output:

css total time 1000 repeats: 8.84s, per find: 8.84ms

xpath total time for 1000 repeats: 8.52s, per find: 8.52ms

Obviously the per find timings are pretty close; the difference is 0.32 milliseconds. Don't jump "the xpath is faster" – sometimes it is, sometimes it's css.


Let's try with another set of locators, a tiny-bit more complicated – an attribute having a substring (common approach at least for me, going after an element's class when a part of it bears functional meaning):

xpath_locator = '//div[contains(@class, "button-section")]'
css_locator = 'div[class~=button-section]'

The two locators are again semantically the same – "find a div element having in its class attribute this substring".
Here are the results:

css total time 1000 repeats: 8.60s, per find: 8.60ms

xpath total time for 1000 repeats: 8.75s, per find: 8.75ms

Diff of 0.15ms.


As an exercise - the same test as done in the linked blog in the comments/other answer - the test page is public, and so is the testing code.

They are doing a couple of things in the code - clicking on a column to sort by it, then getting the values, and checking the UI sort is correct.
I'll cut it - just get the locators, after all - this is the root test, right?

The same code as above, with these changes in:

  • The url is now http://the-internet.herokuapp.com/tables; there are 2 tests.

  • The locators for the first one - "Finding Elements By ID and Class" - are:

css_locator = '#table2 tbody .dues'
xpath_locator = "//table[@id='table2']//tr/td[contains(@class,'dues')]"

And here is the outcome:

css total time 1000 repeats: 8.24s, per find: 8.24ms

xpath total time for 1000 repeats: 8.45s, per find: 8.45ms

Diff of 0.2 milliseconds.

The "Finding Elements By Traversing":

css_locator = '#table1 tbody tr td:nth-of-type(4)'
xpath_locator = "//table[@id='table1']//tr/td[4]"

The result:

css total time 1000 repeats: 9.29s, per find: 9.29ms

xpath total time for 1000 repeats: 8.79s, per find: 8.79ms

This time it is 0.5 ms (in reverse, xpath turned out "faster" here).

So 5 years later (better browsers engines) and focusing only on the locators performance (no actions like sorting in the UI, etc), the same testbed - there is practically no difference between CSS and XPath.


So, out of xpath and css, which of the two to choose for performance? The answer is simple – choose locating by id.

Long story short, if the id of an element is unique (as it's supposed to be according to the specs), its value plays an important role in the browser's internal representation of the DOM, and thus is usually the fastest.

Yet, unique and constant (e.g. not auto-generated) ids are not always available, which brings us to "why XPath if there's CSS?"


The XPath advantage

With the performance out of the picture, why do I think xpath is better? Simple – versatility, and power.

Xpath is a language developed for working with XML documents; as such, it allows for much more powerful constructs than css.
For example, navigation in every direction in the tree – find an element, then go to its grandparent and search for a child of it having certain properties.
It allows embedded boolean conditions – cond1 and not(cond2 or not(cond3 and cond4)); embedded selectors – "find a div having these children with these attributes, and then navigate according to it".
XPath allows searching based on a node's value (its text) – however frowned upon this practice is, it does come in handy especially in badly structured documents (no definite attributes to step on, like dynamic ids and classes - locate the element by its text content).

The stepping in css is definitely easier – one can start writing selectors in a matter of minutes; but after a couple of days of usage, the power and possibilities xpath has quickly overcomes css.
And purely subjective – a complex css is much harder to read than a complex xpath expression.

Outro ;)

Finally, again very subjective - which one to chose?

IMO, there is no right or wrong choice - they are different solutions to the same problem, and whatever is more suitable for the job should be picked.

Being "a fan" of XPath I'm not shy to use in my projects a mix of both - heck, sometimes it is much faster to just throw a CSS one, if I know it will do the work just fine.

R numbers from 1 to 100

Your mistake is looking for range, which gives you the range of a vector, for example:

range(c(10, -5, 100))

gives

 -5 100

Instead, look at the : operator to give sequences (with a step size of one):

1:100

or you can use the seq function to have a bit more control. For example,

##Step size of 2
seq(1, 100, by=2)

or

##length.out: desired length of the sequence
seq(1, 100, length.out=5)

Python `if x is not None` or `if not x is None`?

Personally, I use

if not (x is None):

which is understood immediately without ambiguity by every programmer, even those not expert in the Python syntax.

Get jQuery version from inspecting the jQuery object

$().jquery will give you its version as a string.

How To Accept a File POST

Complementing Matt Frear's answer - This would be an ASP NET Core alternative for reading the file directly from Stream, without saving&reading it from disk:

public ActionResult OnPostUpload(List<IFormFile> files)
    {
        try
        {
            var file = files.FirstOrDefault();
            var inputstream = file.OpenReadStream();

            XSSFWorkbook workbook = new XSSFWorkbook(stream);

            var FIRST_ROW_NUMBER = {{firstRowWithValue}};

            ISheet sheet = workbook.GetSheetAt(0);
            // Example: var firstCellRow = (int)sheet.GetRow(0).GetCell(0).NumericCellValue;

            for (int rowIdx = 2; rowIdx <= sheet.LastRowNum; rowIdx++)
               {
                  IRow currentRow = sheet.GetRow(rowIdx);

                  if (currentRow == null || currentRow.Cells == null || currentRow.Cells.Count() < FIRST_ROW_NUMBER) break;

                  var df = new DataFormatter();                

                  for (int cellNumber = {{firstCellWithValue}}; cellNumber < {{lastCellWithValue}}; cellNumber++)
                      {
                         //business logic & saving data to DB                        
                      }               
                }
        }
        catch(Exception ex)
        {
            throw new FileFormatException($"Error on file processing - {ex.Message}");
        }
    }

How to create streams from string in Node.Js?

Do not use Jo Liss's resumer answer. It will work in most cases, but in my case it lost me a good 4 or 5 hours bug finding. There is no need for third party modules to do this.

NEW ANSWER:

var Readable = require('stream').Readable

var s = new Readable()
s.push('beep')    // the string you want
s.push(null)      // indicates end-of-file basically - the end of the stream

This should be a fully compliant Readable stream. See here for more info on how to use streams properly.

OLD ANSWER: Just use the native PassThrough stream:

var stream = require("stream")
var a = new stream.PassThrough()
a.write("your string")
a.end()

a.pipe(process.stdout) // piping will work as normal
/*stream.on('data', function(x) {
   // using the 'data' event works too
   console.log('data '+x)
})*/
/*setTimeout(function() {
   // you can even pipe after the scheduler has had time to do other things
   a.pipe(process.stdout) 
},100)*/

a.on('end', function() {
    console.log('ended') // the end event will be called properly
})

Note that the 'close' event is not emitted (which is not required by the stream interfaces).

batch file - counting number of files in folder and storing in a variable

for /F "tokens=1" %a in ('dir ^| findstr "File(s)"') do echo %a

Result:

C:\MyDir> for /F "tokens=1" %a in ('dir ^| findstr "File(s)"') do @set FILE_COUNT=%a

C:\MyDir> echo %FILE_COUNT%
4   // <== There's your answer

Trying to get property of non-object in

$sidemenu is not an object, so you can't call methods on it. It is probably not being sent to your view, or $sidemenus is empty.

What's the difference between IFrame and Frame?

Inline frame is just one "box" and you can place it anywhere on your site. Frames are a bunch of 'boxes' put together to make one site with many pages.

How to use a global array in C#?

Your class shoud look something like this:

class Something {     int[] array; //global array, replace type of course     void function1() {        array = new int[10]; //let say you declare it here that will be 10 integers in size     }     void function2() {        array[0] = 12; //assing value at index 0 to 12.     } } 

That way you array will be accessible in both functions. However, you must be careful with global stuff, as you can quickly overwrite something.

How do I get Flask to run on port 80?

So it's throwing up that error message because you have apache2 running on port 80.

If this is for development, I would just leave it as it is on port 5000.

If it's for production either:

Not Recommended

  • Stop apache2 first;

Not recommended as it states in the documentation:

You can use the builtin server during development, but you should use a full deployment option for production applications. (Do not use the builtin development server in production.)

Recommended

  • Proxy HTTP traffic through apache2 to Flask.

This way, apache2 can handle all your static files (which it's very good at - much better than the debug server built into Flask) and act as a reverse proxy for your dynamic content, passing those requests to Flask.

Here's a link to the official documentation about setting up Flask with Apache + mod_wsgi.

Edit 1 - Clarification for @Djack

Proxy HTTP traffic to Flask through apache2

When a request comes to the server on port 80 (HTTP) or port 443 (HTTPS) a web server like Apache or Nginx handles the connection of the request and works out what to do with it. In our case a request received should be configured to be passed through to Flask on the WSGI protocol and handled by the Python code. This is the "dynamic" part.

reverse proxy for dynamic content

There are a few advantages to configuring your web server like the above;

  • SSL Termination - The web server will be optimized to handle HTTPS requests with only a little configuration. Don't "roll your own" in Python which is probably very insecure in comparison.
  • Security - Opening a port to the internet requires careful consideration of security. Flask's development server is not designed for this and could have open bugs or security issues in comparison to a web server designed for this purpose. Note that a badly configured web server can also be insecure!
  • Static File Handling - It is possible for the builtin Flask web server to handle static files however this is not recommended; Nginx/Apache are much more efficient at handling static files like images, CSS, Javascript files and will only pass "dynamic" requests (those where the content is often read from a database or the content changes) to be handled by the Python code.
  • +more. This is bordering on scope for this question. If you want more info do some research into this area.

Access-control-allow-origin with multiple domains

For IIS 7.5+ you can use IIS CORS Module: https://www.iis.net/downloads/microsoft/iis-cors-module

Your web.config should be something like this:

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
    <system.webServer>
        <cors enabled="true" failUnlistedOrigins="true">
            <add origin="http://localhost:1506">
                <allowMethods>                    
                    <add method="GET" />
                    <add method="HEAD" />
                    <add method="POST" />
                    <add method="PUT" /> 
                    <add method="DELETE" /> 
                </allowMethods>
            </add>
            <add origin="http://localhost:1502">
                <allowMethods>
                    <add method="GET" />
                    <add method="HEAD" />
                    <add method="POST" />
                    <add method="PUT" /> 
                    <add method="DELETE" /> 
                </allowMethods>
            </add>
        </cors>
    </system.webServer>
</configuration>

You can find the configuration reference in here: https://docs.microsoft.com/en-us/iis/extensions/cors-module/cors-module-configuration-reference

How to detect lowercase letters in Python?

You should use raw_input to take a string input. then use islower method of str object.

s = raw_input('Type a word')
l = []
for c in s.strip():
    if c.islower():
        print c
        l.append(c)
print 'Total number of lowercase letters: %d'%(len(l) + 1)

Just do -

dir(s)

and you will find islower and other attributes of str

Importing JSON into an Eclipse project

Download json from java2s website then include in your project. In your class add these package java_basic;

import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

How do I compare version numbers in Python?

There is packaging package available, which will allow you to compare versions as per PEP-440, as well as legacy versions.

>>> from packaging.version import Version, LegacyVersion
>>> Version('1.1') < Version('1.2')
True
>>> Version('1.2.dev4+deadbeef') < Version('1.2')
True
>>> Version('1.2.8.5') <= Version('1.2')
False
>>> Version('1.2.8.5') <= Version('1.2.8.6')
True

Legacy version support:

>>> LegacyVersion('1.2.8.5-5-gdeadbeef')
<LegacyVersion('1.2.8.5-5-gdeadbeef')>

Comparing legacy version with PEP-440 version.

>>> LegacyVersion('1.2.8.5-5-gdeadbeef') < Version('1.2.8.6')
True

Fastest way to download a GitHub project

Updated July 2016

As of July 2016, the Download ZIP button has moved under Clone or download to extreme-right of header under the Code tab:

Download ZIP (2013)


If you don't see the button:

  • Make sure you've selected <> Code tab from right side navigation menu, or
  • Repo may not have a zip prepared. Add /archive/master.zip to the end of the repository URL and to generate a zipfile of the master branch.

    http://github.com/user/repository/

-to-

http://github.com/user/repository/archive/master.zip

to get the master branch source code in a zip file. You can do the same with tags and branch names, by replacing master in the URL above with the name of the branch or tag.

UIImage resize (Scale proportion)

This change worked for me:

// The size returned by CGImageGetWidth(imgRef) & CGImageGetHeight(imgRef) is incorrect as it doesn't respect the image orientation!
// CGImageRef imgRef = [image CGImage];
// CGFloat width = CGImageGetWidth(imgRef);
// CGFloat height = CGImageGetHeight(imgRef);
//
// This returns the actual width and height of the photo (and hence solves the problem
CGFloat width = image.size.width; 
CGFloat height = image.size.height;
CGRect bounds = CGRectMake(0, 0, width, height);

open new tab(window) by clicking a link in jquery

Try this:

window.open(url, '_blank');

This will open in new tab (if your code is synchronous and in this case it is. in other case it would open a window)

Remove icon/logo from action bar on android

    //disable application icon from ActionBar
    getActionBar().setDisplayShowHomeEnabled(false);

    //disable application name from ActionBar
    getActionBar().setDisplayShowTitleEnabled(false);

Timer function to provide time in nano seconds using C++

I am using the following to get the desired results:

#include <time.h>
#include <iostream>
using namespace std;

int main (int argc, char** argv)
{
    // reset the clock
    timespec tS;
    tS.tv_sec = 0;
    tS.tv_nsec = 0;
    clock_settime(CLOCK_PROCESS_CPUTIME_ID, &tS);
    ...
    ... <code to check for the time to be put here>
    ...
    clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &tS);
    cout << "Time taken is: " << tS.tv_sec << " " << tS.tv_nsec << endl;

    return 0;
}

How to set <Text> text to upper case in react native

React Native .toUpperCase() function works fine in a string but if you used the numbers or other non-string data types, it doesn't work. The error will have occurred.

Below Two are string properties:

<Text>{props.complexity.toUpperCase()}</Text>

<Text>{props.affordability.toUpperCase()}</Text>

getElementsByClassName not working

There are several issues:

  1. Class names (and IDs) are not allowed to start with a digit.
  2. You have to pass a class to getElementsByClassName().
  3. You have to iterate of the result set.

Example (untested):

<script type="text/javascript">
function hideTd(className){
    var elements = document.getElementsByClassName(className);
    for(var i = 0, length = elements.length; i < length; i++) {
       if( elements[i].textContent == ''){
          elements[i].style.display = 'none';
       } 
    }

  }
</script>
</head>
<body onload="hideTd('td');">
<table border="1">
  <tr>
    <td class="td">not empty</td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
  <tr>
    <td class="td"></td>
  </tr>
</table>
</body>

Note that getElementsByClassName() is not available up to and including IE8.

Update:

Alternatively you can give the table an ID and use:

var elements = document.getElementById('tableID').getElementsByTagName('td');

to get all td elements.

To hide the parent row, use the parentNode property of the element:

elements[i].parentNode.style.display = "none";

Can a variable number of arguments be passed to a function?

Adding to unwinds post:

You can send multiple key-value args too.

def myfunc(**kwargs):
    # kwargs is a dictionary.
    for k,v in kwargs.iteritems():
         print "%s = %s" % (k, v)

myfunc(abc=123, efh=456)
# abc = 123
# efh = 456

And you can mix the two:

def myfunc2(*args, **kwargs):
   for a in args:
       print a
   for k,v in kwargs.iteritems():
       print "%s = %s" % (k, v)

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

They must be both declared and called in that order, that is the function signature needs to be *args, **kwargs, and called in that order.

How to add Date Picker Bootstrap 3 on MVC 5 project using the Razor engine?

Simple:

[DataType(DataType.Date)]
Public DateTime Ldate {get;set;}

How to style a clicked button in CSS

If you just want the button to have different styling while the mouse is pressed you can use the :active pseudo class.

.button:active {
}

If on the other hand you want the style to stay after clicking you will have to use javascript.

Dump all documents of Elasticsearch

To export all documents from ElasticSearch into JSON, you can use the esbackupexporter tool. It works with index snapshots. It takes the container with snapshots (S3, Azure blob or file directory) as the input and outputs one or several zipped JSON files per index per day. It is quite handy when exporting your historical snapshots. To export your hot index data, you may need to make the snapshot first (see the answers above).

MySQL - Selecting data from multiple tables all with same structure but different data

Any of the above answers are valid, or an alternative way is to expand the table name to include the database name as well - eg:

SELECT * from us_music, de_music where `us_music.genre` = 'punk' AND `de_music.genre` = 'punk'

SQL Query Where Date = Today Minus 7 Days

Using dateadd to remove a week from the current date.

datex BETWEEN DATEADD(WEEK,-1,GETDATE()) AND GETDATE()

How to change the font on the TextView?

When your font is stored inside res/asset/fonts/Helvetica.ttf use the following:

Typeface tf = Typeface.createFromAsset(getAssets(),"fonts/Helvetica.ttf"); 
txt.setTypeface(tf);

Or, if your font file is stores inside res/font/helvetica.ttf use the following:

Typeface tf = ResourcesCompat.getFont(this,R.font.helvetica);
txt.setTypeface(tf);

XAMPP Object not found error

Drixson Oseña you are right but when you newly install xampp on your system "Object not found!

"The requested URL was not found on this server. If you entered the URL manually please check your spelling and try again. If you think this is a server error, please contact the webmaster. Error 404 localhost Apache/2.4.7 (Win32) OpenSSL/1.0.1e PHP/5.5.6"

However all folder in the htdocs but only open is that xampp website because of index.php error, so that's not a big deal just remove the index.html and index.php and try to open localhost again you'll be succeed.

Issue with virtualenv - cannot activate

If some beginner, like me, has followed multiple Python tutorials now possible has multiple Python versions and/or multiple versions of pip/virtualenv/pipenv...

In that case, answers listed, while many correct, might not help.

The first thing I would try in your place is uninstall and reinstall Python and go from there.

Eclipse IDE: How to zoom in on text?

Here is a cool way of ensuring zoom in and zoom out with mouse scroll-wheel in the Eclipse Editor. This one takes inspiration from the solution above from naveed ahmad which was not working for me.

1) First download Autohotkey from http://www.autohotkey.com/ and install it, then run it.

2) Then download tarlog-plugins from https://code.google.com/p/tarlog-plugins/downloads/list

3) Put the downloaded .jar file in the eclipse/plugins folder.

4) Restart Eclipse.

5) Add the following Autohotkey script, save it then reload it (right click on Autohotkey icon in taskbar and click "Reload this script")

; Ctrl + MouseWheel zooming in Eclipse Editor.
; Requires Tarlog plugins (https://code.google.com/p/tarlog-plugins/).
#IfWinActive ahk_class SWT_Window0
^WheelUp:: Send ^{NumpadAdd}
^WheelDown:: Send ^{NumpadSub}
#IfWinActive

And you should be done. You can now zoom in or zoom out with ctrl+mousewheel up and ctrl+mousewheel down. The only caveat is that Autohotkey must be running for this solution to work so ensure that it starts with Windows or run it just before firing Eclipse up. Works fine in Eclipse Kepler and Luna.

How to wrap text in textview in Android

By setting android:maxEms to a given value together with android:layout_weight="1" will cause the TextView to wrap once it reaches the given length of the ems.

Difference between one-to-many and many-to-one relationship

There is no difference. It's just a matter of language and preference as to which way round you state the relationship.

Deadly CORS when http://localhost is the origin

Agreed! CORS should be enabled on the server-side to resolve the issue ground up. However...

For me the case was:

I desperately wanted to test my front-end(React/Angular/VUE) code locally with the REST API provided by the client with no access to the server config.

Just for testing

After trying all the steps above that didn't work I was forced to disable web security and site isolation trials on chrome along with specifying the user data directory(tried skipping this, didn't work).

For Windows

cd C:\Program Files\Google\Chrome\Application

Disable web security and site isolation trials

chrome.exe  --disable-site-isolation-trials --disable-web-security --user-data-dir="PATH_TO_PROJECT_DIRECTORY"

This finally worked! Hope this helps!

Get filename and path from URI from mediastore

Slightly modified version of @PercyPercy - it doesn't throw and just returns null if anything goes wrong:

public String getPathFromMediaUri(Context context, Uri uri) {
    String result = null;

    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
    int col = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
    if (col >= 0 && cursor.moveToFirst())
        result = cursor.getString(col);
    cursor.close();

    return result;
}

List of zeros in python

$ python3
>>> from itertools import repeat
>>> list(repeat(0, 7))
[0, 0, 0, 0, 0, 0, 0]

how to disable DIV element and everything inside

The following css statement disables click events

pointer-events:none;

How to replace innerHTML of a div using jQuery?

The html() function can take strings of HTML, and will effectively modify the .innerHTML property.

$('#regTitle').html('Hello World');

However, the text() function will change the (text) value of the specified element, but keep the html structure.

$('#regTitle').text('Hello world'); 

Get the last insert id with doctrine 2?

A bit late to answer the question. But,

If it's a MySQL database

should $doctrine_record_object->id work if AUTO_INCREMENT is defined in database and in your table definition.

Using JavaMail with TLS

We actually have some notification code in our product that uses TLS to send mail if it is available.

You will need to set the Java Mail properties. You only need the TLS one but you might need SSL if your SMTP server uses SSL.

Properties props = new Properties();
props.put("mail.smtp.starttls.enable","true");
props.put("mail.smtp.auth", "true");  // If you need to authenticate
// Use the following if you need SSL
props.put("mail.smtp.socketFactory.port", d_port);
props.put("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.socketFactory.fallback", "false");

You can then either pass this to a JavaMail Session or any other session instantiator like Session.getDefaultInstance(props).

What's your most controversial programming opinion?

Premature optimization is NOT the root of all evil! Lack of proper planning is the root of all evil.

Remember the old naval saw

Proper Planning Prevents P*ss Poor Performance!

Append a tuple to a list - what's the difference between two ways?

The tuple function takes only one argument which has to be an iterable

tuple([iterable])

Return a tuple whose items are the same and in the same order as iterable‘s items.

Try making 3,4 an iterable by either using [3,4] (a list) or (3,4) (a tuple)

For example

a_list.append(tuple((3, 4)))

will work

Ruby: Merging variables in to a string

This is called string interpolation, and you do it like this:

"The #{animal} #{action} the #{second_animal}"

Important: it will only work when string is inside double quotes (" ").

Example of code that will not work as you expect:

'The #{animal} #{action} the #{second_animal}'

Java getHours(), getMinutes() and getSeconds()

For a time difference, note that the calendar starts at 01.01.1970, 01:00, not at 00:00. If you're using java.util.Date and java.text.SimpleDateFormat, you will have to compensate for 1 hour:

long start = System.currentTimeMillis();
long end = start + (1*3600 + 23*60 + 45) * 1000 + 678; // 1 h 23 min 45.678 s
Date timeDiff = new Date(end - start - 3600000); // compensate for 1h in millis
SimpleDateFormat timeFormat = new SimpleDateFormat("H:mm:ss.SSS");
System.out.println("Duration: " + timeFormat.format(timeDiff));

This will print:

Duration: 1:23:45.678

How to post data in PHP using file_get_contents?

An alternative, you can also use fopen

$params = array('http' => array(
    'method' => 'POST',
    'content' => 'toto=1&tata=2'
));

$ctx = stream_context_create($params);
$fp = @fopen($sUrl, 'rb', false, $ctx);
if (!$fp)
{
    throw new Exception("Problem with $sUrl, $php_errormsg");
}

$response = @stream_get_contents($fp);
if ($response === false) 
{
    throw new Exception("Problem reading data from $sUrl, $php_errormsg");
}

setState() inside of componentDidUpdate()

You can use setState inside componentDidUpdate

regex to match a single character that is anything but a space

The following should suffice:

[^ ]

If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):

[^\s]

or

\S  # Note this is a CAPITAL 'S'!

launch sms application with an intent

Use

Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setClassName("com.android.mms", "com.android.mms.ui.ConversationList");

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

Inserting records into a MySQL table using Java

no that cannot work(not with real data):

String sql = "INSERT INTO course " +
        "VALUES (course_code, course_desc, course_chair)";
    stmt.executeUpdate(sql);

change it to:

String sql = "INSERT INTO course (course_code, course_desc, course_chair)" +
        "VALUES (?, ?, ?)";

Create a PreparedStatment with that sql and insert the values with index:

PreparedStatement preparedStatement = conn.prepareStatement(sql);
preparedStatement.setString(1, "Test");
preparedStatement.setString(2, "Test2");
preparedStatement.setString(3, "Test3");
preparedStatement.executeUpdate(); 

Java reverse an int value without using array

public int getReverseNumber(int number)
{
    int reminder = 0, result = 0;
    while (number !=0)
    {
        if (number >= 10 || number <= -10)
        {
            reminder = number % 10;
            result = result + reminder;
            result = result * 10;
            number = number / 10;
        }
        else
        {
            result = result + number;
            number /= 10;
        }
    }
    return result;

}

// The above code will work for negative numbers also

Adding dictionaries together, Python

Here are quite a few ways to add dictionaries.

You can use Python3's dictionary unpacking feature.

ndic = {**dic0, **dic1}

Or create a new dict by adding both items.

ndic = dict(dic0.items() + dic1.items())

If your ok to modify dic0

dic0.update(dic1)

If your NOT ok to modify dic0

ndic = dic0.copy()
ndic.update(dic1)

If all the keys in one dict are ensured to be strings (dic1 in this case, of course args can be swapped)

ndic = dict(dic0, **dic1)

In some cases it may be handy to use dict comprehensions (Python 2.7 or newer),
Especially if you want to filter out or transform some keys/values at the same time.

ndic = {k: v for d in (dic0, dic1) for k, v in d.items()}

python: creating list from string

More concise than others:

def parseString(string):
    try:
        return int(string)
    except ValueError:
        return string

b = [[parseString(s) for s in clause.split(', ')] for clause in a]

Alternatively if your format is fixed as <string>, <int>, <int>, you can be even more concise:

def parseClause(a,b,c):
    return [a, int(b), int(c)]

b = [parseClause(*clause) for clause in a]

receiving json and deserializing as List of object at spring mvc controller

For me below code worked, first sending json string with proper headers

$.ajax({
        type: "POST",
        url : 'save',
        data : JSON.stringify(valObject),
        contentType:"application/json; charset=utf-8",
        dataType:"json",
        success : function(resp){
            console.log(resp);
        },
        error : function(resp){
            console.log(resp);
        }
    });

And then on Spring side -

@RequestMapping(value = "/save", 
                method = RequestMethod.POST,
                consumes="application/json")
public @ResponseBody String  save(@RequestBody ArrayList<KeyValue> keyValList) {
    //Saving call goes here
    return "";
}

Here KeyValue is simple pojo that corresponds to your JSON structure also you can add produces as you wish, I am simply returning string.

My json object is like this -

[{"storedKey":"vc","storedValue":"1","clientId":"1","locationId":"1"},
 {"storedKey":"vr","storedValue":"","clientId":"1","locationId":"1"}]

What's the difference between 'git merge' and 'git rebase'?

Git rebase is closer to a merge. The difference in rebase is:

  • the local commits are removed temporally from the branch.
  • run the git pull
  • insert again all your local commits.

So that means that all your local commits are moved to the end, after all the remote commits. If you have a merge conflict, you have to solve it too.

Fling gesture detection on grid layout

There is a lot of excellent information here. Unfortunately a lot of this fling-processing code is scattered around on various sites in various states of completion, even though one would think this is essential to many applications.

I've taken the time to create a fling listener that verifies that the appropriate conditions are met. I've added a page fling listener that adds more checks to ensure that flings meet the threshold for page flings. Both of these listeners allow you to easily restrict flings to the horizontal or vertical axis. You can see how it's used in a view for sliding images. I acknowledge that the people here have done most of the research---I've just put it together into a usable library.

These last few days represent my first stab at coding on Android; expect much more to come.

JQuery find first parent element with specific class prefix

Jquery later allowed you to to find the parents with the .parents() method.

Hence I recommend using:

var $div = $('#divid').parents('div[class^="div-a"]');

This gives all parent nodes matching the selector. To get the first parent matching the selector use:

var $div = $('#divid').parents('div[class^="div-a"]').eq(0);

For other such DOM traversal queries, check out the documentation on traversing the DOM.

Update cordova plugins in one command

I too would LOVE something like this - plugin management with the PhoneGap/Cordova CLI is so annoying. This blog post here may be a start to something like this - but I'm not quite sure A) how to leverage it yet or B) how well it would work.

http://nocurve.com/cordova-update-all-plugins-in-project

My initial attempt at running the entire script right in the terminal command line did create an output of text with add/remove plugin commands ... but they didn't actually execute they just echoed into the terminal. I've reached out to the author hoping they will explain a bit more.

how to format date in Component of angular 5

Another option can be using built in angular formatDate function. I am assuming that you are using reactive forms. Here todoDate is a date input field in template.

import {formatDate} from '@angular/common';

this.todoForm.controls.todoDate.setValue(formatDate(this.todo.targetDate, 'yyyy-MM-dd', 'en-US'));

Bootstrap DatePicker, how to set the start date for tomorrow?

If you are talking about Datepicker for bootstrap, you set the start date (the min date) by using the following:

$('#datepicker').datepicker('setStartDate', <DATETIME STRING HERE>);

jQuery.post( ) .done( ) and success:

jQuery used to ONLY have the callback functions for success and error and complete.

Then, they decided to support promises with the jqXHR object and that's when they added .done(), .fail(), .always(), etc... in the spirit of the promise API. These new methods serve much the same purpose as the callbacks but in a different form. You can use whichever API style works better for your coding style.

As people get more and more familiar with promises and as more and more async operations use that concept, I suspect that more and more people will move to the promise API over time, but in the meantime jQuery supports both.

The .success() method has been deprecated in favor of the common promise object method names.

From the jQuery doc, you can see how various promise methods relate to the callback types:

jqXHR.done(function( data, textStatus, jqXHR ) {}); An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

jqXHR.fail(function( jqXHR, textStatus, errorThrown ) {}); An alternative construct to the error callback option, the .fail() method replaces the deprecated .error() method. Refer to deferred.fail() for implementation details.

jqXHR.always(function( data|jqXHR, textStatus, jqXHR|errorThrown ) { }); An alternative construct to the complete callback option, the .always() method replaces the deprecated .complete() method.

In response to a successful request, the function's arguments are the same as those of .done(): data, textStatus, and the jqXHR object. For failed requests the arguments are the same as those of .fail(): the jqXHR object, textStatus, and errorThrown. Refer to deferred.always() for implementation details.

jqXHR.then(function( data, textStatus, jqXHR ) {}, function( jqXHR, textStatus, errorThrown ) {}); Incorporates the functionality of the .done() and .fail() methods, allowing (as of jQuery 1.8) the underlying Promise to be manipulated. Refer to deferred.then() for implementation details.

If you want to code in a way that is more compliant with the ES6 Promises standard, then of these four options you would only use .then().

Using PI in python 2.7

To have access to stuff provided by math module, like pi. You need to import the module first:

import math
print (math.pi)

Cannot load properties file from resources directory

I use something like this to load properties file.

        final ResourceBundle bundle = ResourceBundle
                .getBundle("properties/errormessages");

        for (final Enumeration<String> keys = bundle.getKeys(); keys
                .hasMoreElements();) {
            final String key = keys.nextElement();
            final String value = bundle.getString(key);
            prop.put(key, value);
        }

Why do we assign a parent reference to the child object in Java?

When you compile your program the reference variable of the base class gets memory and compiler checks all the methods in that class. So it checks all the base class methods but not the child class methods. Now at runtime when the object is created, only checked methods can run. In case a method is overridden in the child class that function runs. Child class other functions aren't run because the compiler hasn't recognized them at the compile time.

How can I split a text file using PowerShell?

I've made a little modification to split files based on size of each part.

##############################################################################
#.SYNOPSIS
# Breaks a text file into multiple text files in a destination, where each
# file contains a maximum number of lines.
#
#.DESCRIPTION
# When working with files that have a header, it is often desirable to have
# the header information repeated in all of the split files. Split-File
# supports this functionality with the -rc (RepeatCount) parameter.
#
#.PARAMETER Path
# Specifies the path to an item. Wildcards are permitted.
#
#.PARAMETER LiteralPath
# Specifies the path to an item. Unlike Path, the value of LiteralPath is
# used exactly as it is typed. No characters are interpreted as wildcards.
# If the path includes escape characters, enclose it in single quotation marks.
# Single quotation marks tell Windows PowerShell not to interpret any
# characters as escape sequences.
#
#.PARAMETER Destination
# (Or -d) The location in which to place the chunked output files.
#
#.PARAMETER Size
# (Or -s) The maximum size of each file. Size must be expressed in MB.
#
#.PARAMETER RepeatCount
# (Or -rc) Specifies the number of "header" lines from the input file that will
# be repeated in each output file. Typically this is 0 or 1 but it can be any
# number of lines.
#
#.EXAMPLE
# Split-File bigfile.csv -s 20 -rc 1
#
#.LINK 
# Out-TempFile
##############################################################################
function Split-File {

    [CmdletBinding(DefaultParameterSetName='Path')]
    param(

        [Parameter(ParameterSetName='Path', Position=1, Mandatory=$true, ValueFromPipeline=$true, ValueFromPipelineByPropertyName=$true)]
        [String[]]$Path,

        [Alias("PSPath")]
        [Parameter(ParameterSetName='LiteralPath', Mandatory=$true, ValueFromPipelineByPropertyName=$true)]
        [String[]]$LiteralPath,

        [Alias('s')]
        [Parameter(Position=2,Mandatory=$true)]
        [Int32]$Size,

        [Alias('d')]
        [Parameter(Position=3)]
        [String]$Destination='.',

        [Alias('rc')]
        [Parameter()]
        [Int32]$RepeatCount

    )

    process {

  # yeah! the cmdlet supports wildcards
        if ($LiteralPath) { $ResolveArgs = @{LiteralPath=$LiteralPath} }
        elseif ($Path) { $ResolveArgs = @{Path=$Path} }

        Resolve-Path @ResolveArgs | %{

            $InputName = [IO.Path]::GetFileNameWithoutExtension($_)
            $InputExt  = [IO.Path]::GetExtension($_)

            if ($RepeatCount) { $Header = Get-Content $_ -TotalCount:$RepeatCount }

   Resolve-Path @ResolveArgs | %{

    $InputName = [IO.Path]::GetFileNameWithoutExtension($_)
    $InputExt  = [IO.Path]::GetExtension($_)

    if ($RepeatCount) { $Header = Get-Content $_ -TotalCount:$RepeatCount }

    # get the input file in manageable chunks

    $Part = 1
    $buffer = ""
    Get-Content $_ -ReadCount:1 | %{

     # make an output filename with a suffix
     $OutputFile = Join-Path $Destination ('{0}-{1:0000}{2}' -f ($InputName,$Part,$InputExt))

     # In the first iteration the header will be
     # copied to the output file as usual
     # on subsequent iterations we have to do it
     if ($RepeatCount -and $Part -gt 1) {
      Set-Content $OutputFile $Header
     }

     # test buffer size and dump data only if buffer is greater than size
     if ($buffer.length -gt ($Size * 1MB)) {
      # write this chunk to the output file
      Write-Host "Writing $OutputFile"
      Add-Content $OutputFile $buffer
      $Part += 1
      $buffer = ""
     } else {
      $buffer += $_ + "`r"
     }
    }
   }
        }
    }
}

Why can I not create a wheel in python?

Update your setuptools, too.

pip install setuptools --upgrade

If that fails too, you could try with additional --force flag.

I have created a table in hive, I would like to know which directory my table is created in?

DESCRIBE FORMATTED <tablename>

or

DESCRIBE EXTENDED <tablename>

I prefer formatted because it is more human readable format

How to access a RowDataPacket object

I really don't see what is the big deal with this I mean look if a run my sp which is CALL ps_get_roles();. Yes I get back an ugly ass response from DB and stuff. Which is this one:


[
  [
    RowDataPacket {
      id: 1,
      role: 'Admin',
      created_at: '2019-12-19 16:03:46'
    },
    RowDataPacket {
      id: 2,
      role: 'Recruiter',
      created_at: '2019-12-19 16:03:46'
    },
    RowDataPacket {
      id: 3,
      role: 'Regular',
      created_at: '2019-12-19 16:03:46'
    }
  ],
  OkPacket {
    fieldCount: 0,
    affectedRows: 0,
    insertId: 0,
    serverStatus: 35,
    warningCount: 0,
    message: '',
    protocol41: true,
    changedRows: 0
  }
]

it is an array that kind of look like this:


rows[0] = [
    RowDataPacket {/* them table rows*/ },
    RowDataPacket { },
    RowDataPacket { }
];

rows[1] = OkPacket {
   /* them props */
}

but if I do an http response to index [0] of rows at the client I get:

[
  {"id":1,"role":"Admin","created_at":"2019-12-19 16:03:46"}, 
  {"id":2,"role":"Recruiter","created_at":"2019-12-19 16:03:46"},
  {"id":3,"role":"Regular","created_at":"2019-12-19 16:03:46"}
]

and I didnt have to do none of yow things

rows[0].map(row => {
   return console.log("row: ", {...row});
});

the output gets some like this:

row:  { id: 1, role: 'Admin', created_at: '2019-12-19 16:03:46' }
row:  { id: 2, role: 'Recruiter', created_at: '2019-12-19 16:03:46' }
row:  { id: 3, role: 'Regular', created_at: '2019-12-19 16:03:46' }

So you all is tripping for no reason. Or it also could be the fact that I'm running store procedures instead of regular querys, the response from query and sp is not the same.

How to Disable landscape mode in Android?

You can do this for your entire application without having to make all your activities extend a common base class.

The trick is first to make sure you include an Application subclass in your project. In its onCreate(), called when your app first starts up, you register an ActivityLifecycleCallbacks object (API level 14+) to receive notifications of activity lifecycle events.

This gives you the opportunity to execute your own code whenever any activity in your app is started (or stopped, or resumed, or whatever). At this point you can call setRequestedOrientation() on the newly created activity.

And do not forget to add app:name=".MyApp" in your manifest file.

class MyApp extends Application {

    @Override
    public void onCreate() {
        super.onCreate();  

        // register to be informed of activities starting up
        registerActivityLifecycleCallbacks(new ActivityLifecycleCallbacks() {

            @Override
            public void onActivityCreated(Activity activity, 
                                          Bundle savedInstanceState) {

                // new activity created; force its orientation to portrait
                activity.setRequestedOrientation(
                    ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
            }
            ....
        });
    }
}

Date query with ISODate in mongodb doesn't seem to work

Try this:

{ "dt" : { "$gte" : ISODate("2013-10-01") } }

How to randomize Excel rows

Perhaps the whole column full of random numbers is not the best way to do it, but it seems like probably the most practical as @mariusnn mentioned.

On that note, this stomped me for a while with Office 2010, and while generally answers like the one in lifehacker work,I just wanted to share an extra step required for the numbers to be unique:

  1. Create a new column next to the list that you're going to randomize
  2. Type in =rand() in the first cell of the new column - this will generate a random number between 0 and 1
  3. Fill the column with that formula. The easiest way to do this may be to:

    • go down along the new column up until the last cell that you want to randomize
    • hold down Shift and click on the last cell
    • press Ctrl+D
  4. Now you should have a column of identical numbers, even though they are all generated randomly.

    Random numbers... that are the same...

    The trick here is to recalculate them! Go to the Formulas tab and then click on Calculate Now (or press F9).

    Actually random numbers!

    Now all the numbers in the column will be actually generated randomly.

  5. Go to the Home tab and click on Sort & Filter. Choose whichever order you want (Smallest to Largest or Largest to Smallest) - whichever one will give you a random order with respect to the original order. Then click OK when the Sort Warning prompts you to Expand the selection.

  6. Your list should be randomized now! You can get rid of the column of random numbers if you want.

How to modify PATH for Homebrew?

open bash profile in textEdit

open -e .bash_profile

Edit file or paste in front of PATH export PATH=/usr/bin:/usr/sbin:/bin:/sbin:/usr/local/bin:/usr/local/sbin:~/bin

save & close the file

*To open .bash_profile directly open textEdit > file > recent

Python Replace \\ with \

In Python string literals, backslash is an escape character. This is also true when the interactive prompt shows you the value of a string. It will give you the literal code representation of the string. Use the print statement to see what the string actually looks like.

This example shows the difference:

>>> '\\'
'\\'
>>> print '\\'
\

Call a url from javascript

You can make an AJAX request if the url is in the same domain, e.g., same host different application. If so, I'd probably use a framework like jQuery, most likely the get method.

$.get('http://someurl.com',function(data,status) {
      ...parse the data...
},'html');

If you run into cross domain issues, then your best bet is to create a server-side action that proxies the request for you. Do your request to your server using AJAX, have the server request and return the response from the external host.

Thanks to@nickf, for pointing out the obvious problem with my original solution if the url is in a different domain.

Fastest way to determine if record exists

SELECT COUNT(*) FROM products WHERE products.id = ?;

This is the cross relational database solution that works in all databases.

Rounded Corners Image in Flutter

Using ClipRRect you need to hardcode BorderRadius, so if you need complete circular stuff, use ClipOval instead.

ClipOval(
  child: Image.network(
    "image_url",
    height: 100,
    width: 100,
    fit: BoxFit.cover,
  ),
),

What is a C++ delegate?

A delegate is a class that wraps a pointer or reference to an object instance, a member method of that object's class to be called on that object instance, and provides a method to trigger that call.

Here's an example:

template <class T>
class CCallback
{
public:
    typedef void (T::*fn)( int anArg );

    CCallback(T& trg, fn op)
        : m_rTarget(trg)
        , m_Operation(op)
    {
    }

    void Execute( int in )
    {
        (m_rTarget.*m_Operation)( in );
    }

private:

    CCallback();
    CCallback( const CCallback& );

    T& m_rTarget;
    fn m_Operation;

};

class A
{
public:
    virtual void Fn( int i )
    {
    }
};


int main( int /*argc*/, char * /*argv*/ )
{
    A a;
    CCallback<A> cbk( a, &A::Fn );
    cbk.Execute( 3 );
}

JSON and escaping characters

This is not a bug in either implementation. There is no requirement to escape U+00B0. To quote the RFC:

2.5. Strings

The representation of strings is similar to conventions used in the C family of programming languages. A string begins and ends with quotation marks. All Unicode characters may be placed within the quotation marks except for the characters that must be escaped: quotation mark, reverse solidus, and the control characters (U+0000 through U+001F).

Any character may be escaped.

Escaping everything inflates the size of the data (all code points can be represented in four or fewer bytes in all Unicode transformation formats; whereas encoding them all makes them six or twelve bytes).

It is more likely that you have a text transcoding bug somewhere in your code and escaping everything in the ASCII subset masks the problem. It is a requirement of the JSON spec that all data use a Unicode encoding.

jQuery - how can I find the element with a certain id?

I don't know if this solves your problem but instead of:

$("#tbIntervalos").find("td").attr("id", horaInicial);

you can just do:

$("#tbIntervalos td#" + horaInicial);

Do I need a content-type header for HTTP GET requests?

The accepted answer is wrong. The quote is correct, the assertion that PUT and POST must have it is incorrect. There is no requirement that PUT or POST actually have additional content. Nor is there a prohibition against GET actually having content.

The RFCs say exactly what they mean .. IFF your side (client OR origin server) will be sending additional content, beyond the HTTP headers, it SHOULD specify a Content-Type header. But note it is allowable to omit the Content-Type and still include content (say, by using a Content-Length header).

How to perform element-wise multiplication of two lists?

Use np.multiply(a,b):

import numpy as np
a = [1,2,3,4]
b = [2,3,4,5]
np.multiply(a,b)

How can I pad a value with leading zeros?

My little contribution with this topic (https://gist.github.com/lucasferreira/a881606894dde5568029):

/* Autor: Lucas Ferreira - http://blog.lucasferreira.com | Usage: fz(9) or fz(100, 7) */
function fz(o, s) {
    for(var s=Math.max((+s||2),(n=""+Math.abs(o)).length); n.length<s; (n="0"+n));
    return (+o < 0 ? "-" : "") + n;
};

Usage:

fz(9) & fz(9, 2) == "09"
fz(-3, 2) == "-03"
fz(101, 7) == "0000101"

I know, it's a pretty dirty function, but it's fast and works even with negative numbers ;)

How to get the number of columns from a JDBC ResultSet?

PreparedStatement ps=con.prepareStatement("select * from stud");

ResultSet rs=ps.executeQuery();

ResultSetMetaData rsmd=rs.getMetaData();

System.out.println("columns: "+rsmd.getColumnCount());  
System.out.println("Column Name of 1st column: "+rsmd.getColumnName(1));  
System.out.println("Column Type Name of 1st column: "+rsmd.getColumnTypeName(1)); 

How to make "if not true condition"?

This one

if [[ !  $(cat /etc/passwd | grep "sysa") ]]
Then echo " something"
exit 2
fi

How to send a POST request from node.js Express?

I use superagent, which is simliar to jQuery.

Here is the docs

And the demo like:

var sa = require('superagent');
sa.post('url')
  .send({key: value})
  .end(function(err, res) {
    //TODO
  });

Remove file extension from a file name string

The Path.GetFileNameWithoutExtension method gives you the filename you pass as an argument without the extension, as should be obvious from the name.

What is the simplest way to get indented XML with line breaks from XmlDocument?

A simple way is to use:

writer.WriteRaw(space_char);

Like this sample code, this code is what I used to create a tree view like structure using XMLWriter :

private void generateXML(string filename)
        {
            using (XmlWriter writer = XmlWriter.Create(filename))
            {
                writer.WriteStartDocument();
                //new line
                writer.WriteRaw("\n");
                writer.WriteStartElement("treeitems");
                //new line
                writer.WriteRaw("\n");
                foreach (RootItem root in roots)
                {
                    //indent
                    writer.WriteRaw("\t");
                    writer.WriteStartElement("treeitem");
                    writer.WriteAttributeString("name", root.name);
                    writer.WriteAttributeString("uri", root.uri);
                    writer.WriteAttributeString("fontsize", root.fontsize);
                    writer.WriteAttributeString("icon", root.icon);
                    if (root.children.Count != 0)
                    {
                        foreach (ChildItem child in children)
                        {
                            //indent
                            writer.WriteRaw("\t");
                            writer.WriteStartElement("treeitem");
                            writer.WriteAttributeString("name", child.name);
                            writer.WriteAttributeString("uri", child.uri);
                            writer.WriteAttributeString("fontsize", child.fontsize);
                            writer.WriteAttributeString("icon", child.icon);
                            writer.WriteEndElement();
                            //new line
                            writer.WriteRaw("\n");
                        }
                    }
                    writer.WriteEndElement();
                    //new line
                    writer.WriteRaw("\n");
                }

                writer.WriteEndElement();
                writer.WriteEndDocument();

            }

        }

This way you can add tab or line breaks in the way you are normally used to, i.e. \t or \n

Update Multiple Rows in Entity Framework from a list of ids

I think you are looking for below method:

var idList=new int[]{1, 2, 3, 4};
using (var db=new SomeDatabaseContext())
{
    var friends= db.Friends.Where(f=>idList.Contains(f.ID));
    friends.ForEachAsync(a=>a.msgSentBy='1234');
    await db.SaveChangesAsync();
}

This should be the efficient way of handling this.

Linking to a specific part of a web page

The upcoming Chrome "Scroll to text" feature is exactly what you are looking for....

https://github.com/bokand/ScrollToTextFragment

You basically add #targetText= at the end of the URL and the browser will scroll to the target text and highlight it after the page is loaded.

It is in the version of Chrome that is running on my desk, but currently it must be manually enabled. Presumably it will soon be enabled by default in the production Chrome builds and other browsers will follow, so OK to start adding to your links now and it will start working then.

Extract first and last row of a dataframe in pandas

Here is the same style as in large datasets:

x = df[:5]
y = pd.DataFrame([['...']*df.shape[1]], columns=df.columns, index=['...'])
z = df[-5:]
frame = [x, y, z]
result = pd.concat(frame)

print(result)

Output:

                     date  temp
0     1981-01-01 00:00:00  20.7
1     1981-01-02 00:00:00  17.9
2     1981-01-03 00:00:00  18.8
3     1981-01-04 00:00:00  14.6
4     1981-01-05 00:00:00  15.8
...                   ...   ...
3645  1990-12-27 00:00:00    14
3646  1990-12-28 00:00:00  13.6
3647  1990-12-29 00:00:00  13.5
3648  1990-12-30 00:00:00  15.7
3649  1990-12-31 00:00:00    13

How do I print an IFrame from javascript in Safari/Chrome

I used Andrew's script but added a piece before the printPage() function is called. The iframe needs focus, otherwise it will still print the parent frame in IE.

function printIframe(id)
{
    var iframe = document.frames ? document.frames[id] : document.getElementById(id);
    var ifWin = iframe.contentWindow || iframe;
    iframe.focus();
    ifWin.printPage();
    return false;
}

Don't thank me though, it was Andrew who wrote this. I just made a tweak =P

Edit a commit message in SourceTree Windows (already pushed to remote)

If the comment message includes non-English characters, using method provided by user456814, those characters will be replaced by question marks. (tested under sourcetree Ver2.5.5.0)

So I have to use the following method.

CAUTION: if the commit has been pulled by other members, changes below might cause chaos for them.

Step1: In the sourcetree main window, locate your repo tab, and click the "terminal" button to open the git command console.

Step2:

[Situation A]: target commit is the latest one.

1) In the git command console, input

git commit --amend -m "new comment message"

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force

[Situation B]: target commit is not the latest one.

1) In the git command console, input

git rebase -i HEAD~n

It is to squash the latest n commits. e.g. if you want to edit the message before the last one, n is 2. This command will open a vi window, the first word of each line is "pick", and you change the "pick" to "reword" for the line you want to edit. Then, input :wq to save&quit that vi window. Now, a new vi window will be open, in this window you input your new message. Also use :wq to save&quit.

2) If the target commit has been pushed to remote, you have to push again by force. In the git command console, input

git push --force


Finally: In the sourcetree main window, Press F5 to refresh.

get index of DataTable column with name

You can use DataColumn.Ordinal to get the index of the column in the DataTable. So if you need the next column as mentioned use Column.Ordinal + 1:

row[row.Table.Columns["ColumnName"].Ordinal + 1] = someOtherValue;

foreach vs someList.ForEach(){}

For fun, I popped List into reflector and this is the resulting C#:

public void ForEach(Action<T> action)
{
    if (action == null)
    {
        ThrowHelper.ThrowArgumentNullException(ExceptionArgument.match);
    }
    for (int i = 0; i < this._size; i++)
    {
        action(this._items[i]);
    }
}

Similarly, the MoveNext in Enumerator which is what is used by foreach is this:

public bool MoveNext()
{
    if (this.version != this.list._version)
    {
        ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_EnumFailedVersion);
    }
    if (this.index < this.list._size)
    {
        this.current = this.list._items[this.index];
        this.index++;
        return true;
    }
    this.index = this.list._size + 1;
    this.current = default(T);
    return false;
}

The List.ForEach is much more trimmed down than MoveNext - far less processing - will more likely JIT into something efficient..

In addition, foreach() will allocate a new Enumerator no matter what. The GC is your friend, but if you're doing the same foreach repeatedly, this will make more throwaway objects, as opposed to reusing the same delegate - BUT - this is really a fringe case. In typical usage you will see little or no difference.

What is the minimum length of a valid international phone number?

The minimum length is 4 for Saint Helena (Format: +290 XXXX) and Niue (Format: +683 XXXX).

How to determine the number of days in a month in SQL Server?

here's another one...

Select Day(DateAdd(day, -Day(DateAdd(month, 1, getdate())), 
                         DateAdd(month, 1, getdate())))

What is the use of ByteBuffer in Java?

This is a good description of its uses and shortcomings. You essentially use it whenever you need to do fast low-level I/O. If you were going to implement a TCP/IP protocol or if you were writing a database (DBMS) this class would come in handy.

How do I select elements of an array given condition?

Add one detail to @J.F. Sebastian's and @Mark Mikofski's answers:
If one wants to get the corresponding indices (rather than the actual values of array), the following code will do:

For satisfying multiple (all) conditions:

select_indices = np.where( np.logical_and( x > 1, x < 5) )[0] #   1 < x <5

For satisfying multiple (or) conditions:

select_indices = np.where( np.logical_or( x < 1, x > 5 ) )[0] # x <1 or x >5

How to access Session variables and set them in javascript?

I was able to solve a similar problem with simple URL parameters and auto refresh.

You can get the values from the URL parameters, do whatever you want with them and simply refresh the page.

HTML:

<a href=\"webpage.aspx?parameterName=parameterValue"> LinkText </a>

C#:

string variable = Request.QueryString["parameterName"];
if (parameterName!= null)
{
   Session["sessionVariable"] += parameterName;
   Response.AddHeader("REFRESH", "1;URL=webpage.aspx");
}

How do you Encrypt and Decrypt a PHP String?

These are compact methods to encrypt / decrypt strings with PHP using AES256 CBC:

function encryptString($plaintext, $password, $encoding = null) {
    $iv = openssl_random_pseudo_bytes(16);
    $ciphertext = openssl_encrypt($plaintext, "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, $iv);
    $hmac = hash_hmac('sha256', $ciphertext.$iv, hash('sha256', $password, true), true);
    return $encoding == "hex" ? bin2hex($iv.$hmac.$ciphertext) : ($encoding == "base64" ? base64_encode($iv.$hmac.$ciphertext) : $iv.$hmac.$ciphertext);
}

function decryptString($ciphertext, $password, $encoding = null) {
    $ciphertext = $encoding == "hex" ? hex2bin($ciphertext) : ($encoding == "base64" ? base64_decode($ciphertext) : $ciphertext);
    if (!hash_equals(hash_hmac('sha256', substr($ciphertext, 48).substr($ciphertext, 0, 16), hash('sha256', $password, true), true), substr($ciphertext, 16, 32))) return null;
    return openssl_decrypt(substr($ciphertext, 48), "AES-256-CBC", hash('sha256', $password, true), OPENSSL_RAW_DATA, substr($ciphertext, 0, 16));
}

Usage:

$enc = encryptString("mysecretText", "myPassword");
$dec = decryptString($enc, "myPassword");

Is there a JSON equivalent of XQuery/XPath?

Json Pointer seem's to be getting growing support too.

QtCreator: No valid kits found

Found the issue. Qt Creator wants you to use a compiler listed under one of their Qt libraries. Use the Maintenance Tool to install this.

To do so:

Go to Tools -> Options.... Select Build & Run on left. Open Kits tab. You should have Manual -> Desktop (default) line in list. Choose it. Now select something like Qt 5.5.1 in PATH (qt5) in Qt version combobox and click Apply button. From now you should be able to create, build and run empty Qt project.

Rails update_attributes without save?

I believe what you are looking for is assign_attributes.

It's basically the same as update_attributes but it doesn't save the record:

class User < ActiveRecord::Base
  attr_accessible :name
  attr_accessible :name, :is_admin, :as => :admin
end

user = User.new
user.assign_attributes({ :name => 'Josh', :is_admin => true }) # Raises an ActiveModel::MassAssignmentSecurity::Error
user.assign_attributes({ :name => 'Bob'})
user.name        # => "Bob"
user.is_admin?   # => false
user.new_record? # => true

Unsetting array values in a foreach loop


foreach($images as $key=>$image)                                
{               
   if($image == 'http://i27.tinypic.com/29ykt1f.gif' ||    
   $image == 'http://img3.abload.de/img/10nxjl0fhco.gif' ||    
   $image == 'http://i42.tinypic.com/9pp2tx.gif')     
   { unset($images[$key]); }                               
}

!!foreach($images as $key=>$image

cause $image is the value, so $images[$image] make no sense.

What is the function __construct used for?

The __construct method is used to pass in parameters when you first create an object--this is called 'defining a constructor method', and is a common thing to do.

However, constructors are optional--so if you don't want to pass any parameters at object construction time, you don't need it.

So:

// Create a new class, and include a __construct method
class Task {

    public $title;
    public $description;

    public function __construct($title, $description){
        $this->title = $title;
        $this->description = $description;
    }
}

// Create a new object, passing in a $title and $description
$task = new Task('Learn OOP','This is a description');

// Try it and see
var_dump($task->title, $task->description);

For more details on what a constructor is, see the manual.

How can I select an element with multiple classes in jQuery?

For the case

<element class="a">
  <element class="b c">
  </element>
</element>

You would need to put a space in between .a and .b.c

$('.a .b.c')

How to increment a variable on a for loop in jinja template?

After 2.10, to solve the scope problem, you can do something like this:

{% set count = namespace(value=0) %}
{% for i in p %}
  {{ count.value }}
  {% set count.value = count.value + 1 %}
{% endfor %}

How to create JSON post to api using C#

Have you tried using the WebClient class?

you should be able to use

string result = "";
using (var client = new WebClient())
{
    client.Headers[HttpRequestHeader.ContentType] = "application/json"; 
    result = client.UploadString(url, "POST", json);
}
Console.WriteLine(result);

Documentation at

http://msdn.microsoft.com/en-us/library/system.net.webclient%28v=vs.110%29.aspx

http://msdn.microsoft.com/en-us/library/d0d3595k%28v=vs.110%29.aspx

In Python, what does dict.pop(a,b) mean?

The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs

The second argument, default, is what pop returns if the first argument, key, is absent. (If you call pop with just one argument, key, it raises an exception if that key's absent).

In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:

b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data

you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).

subtract time from date - moment js

I might be missing something in your question here... but from what I can gather, by using the subtract method this should be what you're looking to do:

var timeStr = "00:03:15";
    timeStr = timeStr.split(':');

var h = timeStr[1],
    m = timeStr[2];

var newTime = moment("01:20:00 06-26-2014")
    .subtract({'hours': h, 'minutes': m})
    .format('hh:mm');

var str = h + " hours and " + m + " minutes earlier: " + newTime;

console.log(str); // 3 hours and 15 minutes earlier: 10:05

_x000D_
_x000D_
$(document).ready(function(){    _x000D_
     var timeStr = "00:03:15";_x000D_
        timeStr = timeStr.split(':');_x000D_
_x000D_
    var h = timeStr[1],_x000D_
        m = timeStr[2];_x000D_
_x000D_
    var newTime = moment("01:20:00 06-26-2014")_x000D_
        .subtract({'hours': h, 'minutes': m})_x000D_
        .format('hh:mm');_x000D_
_x000D_
    var str = h + " hours and " + m + " minutes earlier: " + newTime;_x000D_
_x000D_
    $('#new-time').html(str);_x000D_
})
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.9.0/moment.min.js"></script>_x000D_
_x000D_
_x000D_
<p id="new-time"></p>
_x000D_
_x000D_
_x000D_

Can I use a binary literal in C or C++?

You can use binary literals. They are standardized in C++14. For example,

int x = 0b11000;

Support in GCC

Support in GCC began in GCC 4.3 (see https://gcc.gnu.org/gcc-4.3/changes.html) as extensions to the C language family (see https://gcc.gnu.org/onlinedocs/gcc/C-Extensions.html#C-Extensions), but since GCC 4.9 it is now recognized as either a C++14 feature or an extension (see Difference between GCC binary literals and C++14 ones?)

Support in Visual Studio

Support in Visual Studio started in Visual Studio 2015 Preview (see https://www.visualstudio.com/news/vs2015-preview-vs#C++).

When should I use UNSIGNED and SIGNED INT in MySQL?

If you know the type of numbers you are going to store, your can choose accordingly. In this case your have 'id' which can never be negative. So you can use unsigned int. Range of signed int: -n/2 to +n/2 Range of unsigned int: 0 to n So you have twice the number of positive numbers available. Choose accordingly.

C# How to determine if a number is a multiple of another?

Use the modulus (%) operator:

6 % 3 == 0
7 % 3 == 1

Is it possible to use jQuery to read meta tags

Would this parser help you?

https://github.com/fiann/jquery.ogp

It parses meta OG data to JSON, so you can just use the data directly. If you prefer, you can read/write them directly using JQuery, of course. For example:

$("meta[property='og:title']").attr("content", document.title);
$("meta[property='og:url']").attr("content", location.toString());

Note the single-quotes around the attribute values; this prevents parse errors in jQuery.

How to create a file in Android?

I decided to write a class from this thread that may be helpful to others. Note that this is currently intended to write in the "files" directory only (e.g. does not write to "sdcard" paths).

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;

import android.content.Context;

public class AndroidFileFunctions {

    public static String getFileValue(String fileName, Context context) {
        try {
            StringBuffer outStringBuf = new StringBuffer();
            String inputLine = "";
            /*
             * We have to use the openFileInput()-method the ActivityContext
             * provides. Again for security reasons with openFileInput(...)
             */
            FileInputStream fIn = context.openFileInput(fileName);
            InputStreamReader isr = new InputStreamReader(fIn);
            BufferedReader inBuff = new BufferedReader(isr);
            while ((inputLine = inBuff.readLine()) != null) {
                outStringBuf.append(inputLine);
                outStringBuf.append("\n");
            }
            inBuff.close();
            return outStringBuf.toString();
        } catch (IOException e) {
            return null;
        }
    }

    public static boolean appendFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context, Context.MODE_APPEND);
    }

    public static boolean setFileValue(String fileName, String value,
            Context context) {
        return writeToFile(fileName, value, context,
                Context.MODE_WORLD_READABLE);
    }

    public static boolean writeToFile(String fileName, String value,
            Context context, int writeOrAppendMode) {
        // just make sure it's one of the modes we support
        if (writeOrAppendMode != Context.MODE_WORLD_READABLE
                && writeOrAppendMode != Context.MODE_WORLD_WRITEABLE
                && writeOrAppendMode != Context.MODE_APPEND) {
            return false;
        }
        try {
            /*
             * We have to use the openFileOutput()-method the ActivityContext
             * provides, to protect your file from others and This is done for
             * security-reasons. We chose MODE_WORLD_READABLE, because we have
             * nothing to hide in our file
             */
            FileOutputStream fOut = context.openFileOutput(fileName,
                    writeOrAppendMode);
            OutputStreamWriter osw = new OutputStreamWriter(fOut);
            // Write the string to the file
            osw.write(value);
            // save and close
            osw.flush();
            osw.close();
        } catch (IOException e) {
            return false;
        }
        return true;
    }

    public static void deleteFile(String fileName, Context context) {
        context.deleteFile(fileName);
    }
}

How to execute a shell script in PHP?

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

disable_functions = exec

And remove the exec, shell_exec entries if there are there.

Good Luck!

How to enable MySQL Query Log?

for mysql>=5.5 only for slow queries (1 second and more) my.cfg

[mysqld]
slow-query-log = 1
slow-query-log-file = /var/log/mysql/mysql-slow.log
long_query_time = 1
log-queries-not-using-indexes

How to get the focused element with jQuery?

$(':focus')[0] will give you the actual element.

$(':focus') will give you an array of elements, usually only one element is focused at a time so this is only better if you somehow have multiple elements focused.

Ternary operator in PowerShell

Powershell 7 has it. https://toastit.dev/2019/09/25/ternary-operator-powershell-7/

PS C:\Users\js> 0 ? 'yes' : 'no'
no
PS C:\Users\js> 1 ? 'yes' : 'no'
yes

What is FCM token in Firebase?

They deprecated getToken() method in the below release notes. Instead, we have to use getInstanceId.

https://firebase.google.com/docs/reference/android/com/google/firebase/iid/FirebaseInstanceId

Task<InstanceIdResult> task = FirebaseInstanceId.getInstance().getInstanceId();
task.addOnSuccessListener(new OnSuccessListener<InstanceIdResult>() {
      @Override
      public void onSuccess(InstanceIdResult authResult) {
          // Task completed successfully
          // ...
          String fcmToken = authResult.getToken();
      }
});

task.addOnFailureListener(new OnFailureListener() {
@Override
public void onFailure(@NonNull Exception e) {
    // Task failed with an exception
    // ...
}
});

To handle success and failure in the same listener, attach an OnCompleteListener:

task.addOnCompleteListener(new OnCompleteListener<InstanceIdResult>() {
@Override
public void onComplete(@NonNull Task<InstanceIdResult> task) {
    if (task.isSuccessful()) {
        // Task completed successfully
        InstanceIdResult authResult = task.getResult();
        String fcmToken = authResult.getToken();
    } else {
        // Task failed with an exception
        Exception exception = task.getException();
    }
}
});

Also, the FirebaseInstanceIdService Class is deprecated and they came up with onNewToken method in FireBaseMessagingService as replacement for onTokenRefresh,

you can refer to the release notes here, https://firebase.google.com/support/release-notes/android

@Override
public void onNewToken(String s) {
    super.onNewToken(s);
    Use this code logic to send the info to your server.
    //sendRegistrationToServer(s);
}

What are the differences between C, C# and C++ in terms of real-world applications?

Both C and C++ give you a lower level of abstraction that, with increased complexity, provides a breadth of access to underlying machine functionality that are not necessarily exposed with other languages. Compared to C, C++ adds the convenience of a fully object oriented language(reduced development time) which can, potentially, add an additional performance cost. In terms of real world applications, I see these languages applied in the following domains:

C

  • Kernel level software.
  • Hardware device drivers
  • Applications where access to old, stable code is required.

C,C++

  • Application or Server development where memory management needs to be fine tuned (and can't be left to generic garbage collection solutions).
  • Development environments that require access to libraries that do not interface well with more modern managed languages.
  • Although managed C++ can be used to access the .NET framework, it is not a seamless transition.

C# provides a managed memory model that adds a higher level of abstraction again. This level of abstraction adds convenience and improves development times, but complicates access to lower level APIs and makes specialized performance requirements problematic.

It is certainly possible to implement extremely high performance software in a managed memory environment, but awareness of the implications is essential.

The syntax of C# is certainly less demanding (and error prone) than C/C++ and has, for the initiated programmer, a shallower learning curve.

C#

  • Rapid client application development.
  • High performance Server development (StackOverflow for example) that benefits from the .NET framework.
  • Applications that require the benefits of the .NET framework in the language it was designed for.

Johannes Rössel makes the valid point that the use C# Pointers, Unsafe and Unchecked keywords break through the layer of abstraction upon which C# is built. I would emphasize that type of programming is the exception to most C# development scenarios and not a fundamental part of the language (as is the case with C/C++).

Get current date in Swift 3?

You can do it in this way with Swift 3.0:

let date = Date()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)

let year =  components.year
let month = components.month
let day = components.day

print(year)
print(month)
print(day)

Count number of 1's in binary representation

The below method can count the number of 1s in negative numbers as well.

private static int countBits(int number)    {
    int result = 0;
    while(number != 0)  {
        result += number & 1;
        number = number >>> 1;
    }
    return result;
}

However, a number like -1 is represented in binary as 11111111111111111111111111111111 and so will require a lot of shifting. If you don't want to do so many shifts for small negative numbers, another way could be as follows:

private static int countBits(int number)    {
    boolean negFlag = false;
    if(number < 0)  { 
        negFlag = true;
        number = ~number;
    }

    int result = 0;
    while(number != 0)  {
        result += number & 1;
        number = number >> 1;
    }
    return negFlag? (32-result): result;
}

How to define an optional field in protobuf 3

Another way is that you can use bitmask for each optional field. and set those bits if values are set and reset those bits which values are not set

enum bitsV {
    baz_present = 1; // 0x01
    baz1_present = 2; // 0x02

}
message Foo {
    uint32 bitMask;
    required int32 bar = 1;
    optional int32 baz = 2;
    optional int32 baz1 = 3;
}

On parsing check for value of bitMask.

if (bitMask & baz_present)
    baz is present

if (bitMask & baz1_present)
    baz1 is present

What does file:///android_asset/www/index.html mean?

It is actually called file:///android_asset/index.html

file:///android_assets/index.html will give you a build error.

Git fails when pushing commit to github

in these cases you can try ssh if https is stuck.

Also you can try increasing the buffer size to an astronomical figure so that you dont have to worry about the buffer size any more git config http.postBuffer 100000000

"Comparison method violates its general contract!"

If compareParents(s1, s2) == -1 then compareParents(s2, s1) == 1 is expected. With your code it's not always true.

Specifically if s1.getParent() == s2 && s2.getParent() == s1. It's just one of the possible problems.

Create Git branch with current changes

Since you haven't made any commits yet, you can save all your changes to the stash, create and switch to a new branch, then pop those changes back into your working tree:

git stash  # save local modifications to new stash
git checkout -b topic/newbranch
git stash pop  # apply stash and remove it from the stash list

What is the best algorithm for overriding GetHashCode?

ReSharper users can generate GetHashCode, Equals, and others with ReSharper -> Edit -> Generate Code -> Equality Members.

// ReSharper's GetHashCode looks like this
public override int GetHashCode() {
    unchecked {
        int hashCode = Id;
        hashCode = (hashCode * 397) ^ IntMember;
        hashCode = (hashCode * 397) ^ OtherIntMember;
        hashCode = (hashCode * 397) ^ (RefMember != null ? RefMember.GetHashCode() : 0);
        // ...
        return hashCode;
    }
}

Create mysql table directly from CSV file using the CSV Storage engine?

There is an easier way if you are using phpMyAdmin as your MySQL front end:

  1. Create a database with the default settings.
  2. Select the database.
  3. Click "Import" at the top of the screen.
  4. Select "CSV" under "Format".
  5. Choose the options appropriate to your CSV file, open the CSV file in a text editor and reference it to get the "appropriate" options.

If you have problems, no problem, simply drop the database and try again.

Regular Expression to find a string included between two characters while EXCLUDING the delimiters

PHP:

$string ='This is the match [more or less]';
preg_match('#\[(.*)\]#', $string, $match);
var_dump($match[1]);

if A vs if A is not None:

They do very different things.

The below checks if A has anything except the values False, [], None, '' and 0. It checks the value of A.

if A:

The below checks if A is a different object than None. It checks and compares the reference (memory address) of A and None.

if A is not None:

UPDATE: Further explanation

Many times the two seem to do the same thing so a lot of people use them interchangeably. The reason the two give the same results is many times by pure coincidence due to optimizations of the interpreter/compiler like interning or something else.

With those optimizations in mind, integers and strings of the same value end up using the same memory space. That probably explains why two separate strings act as if they are the same.

> a = 'test'
> b = 'test'
> a is b
True
> a == b
True

Other things don't behave the same though..

> a = []
> b = []
> a is b
False
> a == b
True

The two lists clearly have their own memory. Surprisingly tuples behave like strings.

> a = ()
> b = ()
> a is b
True
> a == b
True

Probably this is because tuples are guaranteed to not change, thus it makes sense to reuse the same memory.

This shows that you should be extra vigilant on what comparison operator you use. Use is and == depending on what you really want to check. These things can be hard to debug since is reads like prose that we often just skim over it.

Skipping Incompatible Libraries at compile

Normally, that is not an error per se; it is a warning that the first file it found that matches the -lPI-Http argument to the compiler/linker is not valid. The error occurs when no other library can be found with the right content.

So, you need to look to see whether /dvlpmnt/libPI-Http.a is a library of 32-bit object files or of 64-bit object files - it will likely be 64-bit if you are compiling with the -m32 option. Then you need to establish whether there is an alternative libPI-Http.a or libPI-Http.so file somewhere else that is 32-bit. If so, ensure that the directory that contains it is listed in a -L/some/where argument to the linker. If not, then you will need to obtain or build a 32-bit version of the library from somewhere.

To establish what is in that library, you may need to do:

mkdir junk
cd junk
ar x /dvlpmnt/libPI-Http.a
file *.o
cd ..
rm -fr junk

The 'file' step tells you what type of object files are in the archive. The rest just makes sure you don't make a mess that can't be easily cleaned up.

No assembly found containing an OwinStartupAttribute Error

if you want to use signalr you haveto add startup.cs Class in your project

Right Click In You Project Then Add New Item And Select OWIN Startup Class

then inside Configuration Method Add Code Below

app.MapSignalR();

I Hope it will be useful for you

Text not wrapping inside a div element

you can add this line: word-break:break-all; to your CSS-code

How do I define the name of image built with docker-compose

As per docker-compose 1.6.0:

You can now specify both a build and an image key if you're using the new file format. docker-compose build will build the image and tag it with the name you've specified, while docker-compose pull will attempt to pull it.

So your docker-compose.yml would be

version: '2'
services:
  wildfly:
      build: /path/to/dir/Dockerfile
      image: wildfly_server
      ports:
       - 9990:9990
       - 80:8080

To update docker-compose

sudo pip install -U docker-compose==1.6.0

Hexadecimal value 0x00 is a invalid character

As kind of a late answer:

I've had this problem with SSRS ReportService2005.asmx when uploading a report.

    Public Shared Sub CreateReport(ByVal strFileNameAndPath As String, ByVal strReportName As String, ByVal strReportingPath As String, Optional ByVal bOverwrite As Boolean = True)
        Dim rs As SSRS_2005_Administration_WithFOA = New SSRS_2005_Administration_WithFOA
        rs.Credentials = ReportingServiceInterface.GetMyCredentials(strCredentialsURL)
        rs.Timeout = ReportingServiceInterface.iTimeout
        rs.Url = ReportingServiceInterface.strReportingServiceURL
        rs.UnsafeAuthenticatedConnectionSharing = True

        Dim btBuffer As Byte() = Nothing

        Dim rsWarnings As Warning() = Nothing
        Try
            Dim fstrStream As System.IO.FileStream = System.IO.File.OpenRead(strFileNameAndPath)
            btBuffer = New Byte(fstrStream.Length - 1) {}
            fstrStream.Read(btBuffer, 0, CInt(fstrStream.Length))
            fstrStream.Close()
        Catch ex As System.IO.IOException
            Throw New Exception(ex.Message)
        End Try

        Try
            rsWarnings = rs.CreateReport(strReportName, strReportingPath, bOverwrite, btBuffer, Nothing)

            If Not (rsWarnings Is Nothing) Then
                Dim warning As Warning
                For Each warning In rsWarnings
                    Log(warning.Message)
                Next warning
            Else
                Log("Report: {0} created successfully with no warnings", strReportName)
            End If

        Catch ex As System.Web.Services.Protocols.SoapException
            Log(ex.Detail.InnerXml.ToString())
        Catch ex As Exception
            Log("Error at creating report. Invalid server name/timeout?" + vbCrLf + vbCrLf + "Error Description: " + vbCrLf + ex.Message)
            Console.ReadKey()
            System.Environment.Exit(1)
        End Try
    End Sub ' End Function CreateThisReport

The problem occurs when you allocate a byte array that is at least 1 byte larger than the RDL (XML) file.

Specifically, I used a C# to vb.net converter, that converted

  btBuffer = new byte[fstrStream.Length];

into

  btBuffer = New Byte(fstrStream.Length) {}

But because in C# the number denotes the NUMBER OF ELEMENTS in the array, and in VB.NET, that number denotes the UPPER BOUND of the array, I had an excess byte, causing this error.

So the problem's solution is simply:

  btBuffer = New Byte(fstrStream.Length - 1) {}

Expanding a parent <div> to the height of its children

_x000D_
_x000D_
#parent{_x000D_
  background-color:green;_x000D_
  height:auto;_x000D_
  width:300px;_x000D_
  overflow:hidden;_x000D_
}_x000D_
_x000D_
#childRightCol{_x000D_
  color:gray;_x000D_
  background-color:yellow;_x000D_
  margin:10px;_x000D_
  padding:10px;_x000D_
}
_x000D_
<div id="parent">_x000D_
    <div id="childRightCol">_x000D_
        <p>_x000D_
          Lorem ipsum dolor sit amet, consectetur adipiscing elit. Quisque vulputate sit amet neque ac consequat._x000D_
        </p>_x000D_
    </div>_x000D_
  </div>
_x000D_
_x000D_
_x000D_

you are manage by using overflow:hidden; property in css

Difference between .keystore file and .jks file

One reason to choose .keystore over .jks is that Unity recognizes the former but not the latter when you're navigating to select your keystore file (Unity 2017.3, macOS).

How to send JSON instead of a query string with $.ajax?

No, the dataType option is for parsing the received data.

To post JSON, you will need to stringify it yourself via JSON.stringify and set the processData option to false.

$.ajax({
    url: url,
    type: "POST",
    data: JSON.stringify(data),
    processData: false,
    contentType: "application/json; charset=UTF-8",
    complete: callback
});

Note that not all browsers support the JSON object, and although jQuery has .parseJSON, it has no stringifier included; you'll need another polyfill library.

How to change the Text color of Menu item in Android?

Options menu in android can be customized to set the background or change the text appearance. The background and text color in the menu couldn’t be changed using themes and styles. The android source code (data\res\layout\icon_menu_item_layout.xml)uses a custom item of class “com.android.internal.view.menu.IconMenuItem”View for the menu layout. We can make changes in the above class to customize the menu. To achieve the same, use LayoutInflater factory class and set the background and text color for the view.


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.my_menu, menu);
    getLayoutInflater().setFactory(new Factory() {
        @Override
        public View onCreateView(String name, Context context, AttributeSet attrs) {
            if (name .equalsIgnoreCase(“com.android.internal.view.menu.IconMenuItemView”)) {
                try{
                    LayoutInflater f = getLayoutInflater();
                    final View view = f.createView(name, null, attrs);
                    new Handler().post(new Runnable() {
                        public void run() {
                            // set the background drawable
                            view .setBackgroundResource(R.drawable.my_ac_menu_background);

                            // set the text color
                            ((TextView) view).setTextColor(Color.WHITE);
                        }
                    });
                    return view;
                } catch (InflateException e) {
                    } catch (ClassNotFoundException e) {}
            }
            return null;
        }
    });
    return super.onCreateOptionsMenu(menu);
}


Nexus 7 not visible over USB via "adb devices" from Windows 7 x64

The solution that seemed to fix this for me, on top of PTP, is not selecting Always allow from this computer when allowing USB debugging. Revoking the authorisations and manually accepting each time the device is connected fixed this for me. (Settings -> Developer options -> Revoke USB debugging authorisations)

target="_blank" vs. target="_new"

target="_blank" opens a new tab in most browsers.

Correct way to quit a Qt program?

If you're using Qt Jambi, this should work:

QApplication.closeAllWindows();

Read a HTML file into a string variable in memory

Use System.IO.File.ReadAllText(fileName)

How to switch databases in psql?

Listing and Switching Databases in PostgreSQL When you need to change between databases, you’ll use the \connect command, or \c followed by the database name as shown below:

postgres=# \connect database_name
postgres=# \c database_name

Check the database you are currently connected to.

SELECT current_database();

PostgreSQL List Databases

postgres=# \l
 postgres=# \list

PHP append one array to another (not array_push or +)

Following on from answer's by bstoney and Snark I did some tests on the various methods:

// Test 1 (array_merge)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
$array1 = array_merge($array1, $array2);
echo sprintf("Test 1: %.06f\n", microtime(true) - $start);

// Test2 (foreach)
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
foreach ($array2 as $v) {
    $array1[] = $v;
}
echo sprintf("Test 2: %.06f\n", microtime(true) - $start);

// Test 3 (... token)
// PHP 5.6+ and produces error if $array2 is empty
$array1 = $array2 = array_fill(0, 50000, 'aa');
$start = microtime(true);
array_push($array1, ...$array2);
echo sprintf("Test 3: %.06f\n", microtime(true) - $start);

Which produces:

Test 1: 0.002717 
Test 2: 0.006922 
Test 3: 0.004744

ORIGINAL: I believe as of PHP 7, method 3 is a significantly better alternative due to the way foreach loops now act, which is to make a copy of the array being iterated over.

Whilst method 3 isn't strictly an answer to the criteria of 'not array_push' in the question, it is one line and the most high performance in all respects, I think the question was asked before the ... syntax was an option.

UPDATE 25/03/2020: I've updated the test which was flawed as the variables weren't reset. Interestingly (or confusingly) the results now show as test 1 being the fastest, where it was the slowest, having gone from 0.008392 to 0.002717! This can only be down to PHP updates, as this wouldn't have been affected by the testing flaw.

So, the saga continues, I will start using array_merge from now on!

Overwriting my local branch with remote branch

What I do when I mess up my local branch is I just rename my broken branch, and check out/branch the upstream branch again:

git branch -m branch branch-old
git fetch remote
git checkout -b branch remote/branch

Then if you're sure you don't want anything from your old branch, remove it:

git branch -D branch-old

But usually I leave the old branch around locally, just in case I had something in there.

Block direct access to a file over http but allow php script access

That is how I prevented direct access from URL to my ini files. Paste the following code in .htaccess file on root. (no need to create extra folder)

<Files ~ "\.ini$">
  Order allow,deny
  Deny from all
</Files>

my settings.ini file is on the root, and without this code is accessible www.mydomain.com/settings.ini

Command line for looking at specific port

For Windows 8 User : Open Command Prompt, type netstat -an | find "your port number" , enter .

If reply comes like LISTENING then the port is in use, else it is free .

Making TextView scrollable on Android

Make your textview just adding this

TextView textview= (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(new ScrollingMovementMethod());

Name does not exist in the current context

In our case, beside changing ToolsVersion from 14.0 to 15.0 on .csproj projet file, as stated by Dominik Litschauer, we also had to install an updated version of MSBuild, since compilation is being triggered by a Jenkins job. After installing Build Tools for Visual Studio 2019, we had got MsBuild version 16.0 and all new C# features compiled ok.

How add items(Text & Value) to ComboBox & read them in SelectedIndexChanged (SelectedValue = null)

Dictionary<int,string> comboSource = new Dictionary<int,string>();
comboSource.Add(1, "Sunday");
comboSource.Add(2, "Monday");

Aftr adding values to Dictionary, use this as combobox datasource:

comboBox1.DataSource = new BindingSource(comboSource, null);
comboBox1.DisplayMember = "Value";
comboBox1.ValueMember = "Key";

Format a datetime into a string with milliseconds

I dealt with the same problem but in my case it was important that the millisecond was rounded and not truncated

from datetime import datetime, timedelta

def strftime_ms(datetime_obj):
    y,m,d,H,M,S = datetime_obj.timetuple()[:6]
    ms = timedelta(microseconds = round(datetime_obj.microsecond/1000.0)*1000)
    ms_date = datetime(y,m,d,H,M,S) + ms
    return ms_date.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]

How to implement a confirmation (yes/no) DialogPreference?

Android comes with a built-in YesNoPreference class that does exactly what you want (a confirm dialog with yes and no options). See the official source code here.

Unfortunately, it is in the com.android.internal.preference package, which means it is a part of Android's private APIs and you cannot access it from your application (private API classes are subject to change without notice, hence the reason why Google does not let you access them).

Solution: just re-create the class in your application's package by copy/pasting the official source code from the link I provided. I've tried this, and it works fine (there's no reason why it shouldn't).

You can then add it to your preferences.xml like any other Preference. Example:

<com.example.myapp.YesNoPreference
    android:dialogMessage="Are you sure you want to revert all settings to their default values?"
    android:key="com.example.myapp.pref_reset_settings_key"
    android:summary="Revert all settings to their default values."
    android:title="Reset Settings" />

Which looks like this:

screenshot

What is the simplest method of inter-process communication between 2 C# processes?

Anonymous pipes.

Use Asynchronous operations with BeginRead/BeginWrite and AsyncCallback.

How do I send email with JavaScript without opening the mail client?

You need a server-side support to achieve this. Basically your form should be posted (AJAX is fine as well) to the server and that server should connect via SMTP to some mail provider and send that e-mail.

Even if it was possible to send e-mails directly using JavaScript (that is from users computer), the user would still have to connect to some SMTP server (like gmail.com), provide SMTP credentials, etc. This is normally handled on the server-side (in your application), which knows these credentials.

Decode Hex String in Python 3

The answers from @unbeli and @Niklas are good, but @unbeli's answer does not work for all hex strings and it is desirable to do the decoding without importing an extra library (codecs). The following should work (but will not be very efficient for large strings):

>>> result = bytes.fromhex((lambda s: ("%s%s00" * (len(s)//2)) % tuple(s))('4a82fdfeff00')).decode('utf-16-le')
>>> result == '\x4a\x82\xfd\xfe\xff\x00'
True

Basically, it works around having invalid utf-8 bytes by padding with zeros and decoding as utf-16.

Does Ruby have a string.startswith("abc") built in method?

You can use String =~ Regex. It returns position of full regex match in string.

irb> ("abc" =~ %r"abc") == 0
=> true
irb> ("aabc" =~ %r"abc") == 0
=> false

Creating a REST API using PHP

In your example, it’s fine as it is: it’s simple and works. The only things I’d suggest are:

  1. validating the data POSTed
  2. make sure your API is sending the Content-Type header to tell the client to expect a JSON response:

    header('Content-Type: application/json');
    echo json_encode($response);
    

Other than that, an API is something that takes an input and provides an output. It’s possible to “over-engineer” things, in that you make things more complicated that need be.

If you wanted to go down the route of controllers and models, then read up on the MVC pattern and work out how your domain objects fit into it. Looking at the above example, I can see maybe a MathController with an add() action/method.

There are a few starting point projects for RESTful APIs on GitHub that are worth a look.

Import pandas dataframe column as string not int

Since pandas 1.0 it became much more straightforward. This will read column 'ID' as dtype 'string':

pd.read_csv('sample.csv',dtype={'ID':'string'})

As we can see in this Getting started guide, 'string' dtype has been introduced (before strings were treated as dtype 'object').

Padding a table row

The trick is to give padding on the td elements, but make an exception for the first (yes, it's hacky, but sometimes you have to play by the browser's rules):

td {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;   
}

td:first-child {
  padding-left:20px;
  padding-right:0;
}

First-child is relatively well supported: https://developer.mozilla.org/en-US/docs/CSS/:first-child

You can use the same reasoning for the horizontal padding by using tr:first-child td.

Alternatively, exclude the first column by using the not operator. Support for this is not as good right now, though.

td:not(:first-child) {
  padding-top:20px;
  padding-bottom:20px;
  padding-right:20px;       
}

How to find the privileges and roles granted to a user in Oracle?

select * 
from ROLE_TAB_PRIVS 
where role in (
    select granted_role
    from dba_role_privs 
    where granted_role in ('ROLE1','ROLE2')
)

Python dictionary: are keys() and values() always the same order?

For what it's worth, some heavy used production code I have written is based on this assumption and I never had a problem with it. I know that doesn't make it true though :-)

If you don't want to take the risk I would use iteritems() if you can.

for key, value in myDictionary.iteritems():
    print key, value

TypeScript and array reduce function

Reduce() is..

  • The reduce() method reduces the array to a single value.
  • The reduce() method executes a provided function for each value of the array (from left-to-right).
  • The return value of the function is stored in an accumulator (result/total).

It was ..

let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6

Change to

let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);

Also you can use in

  1. find max
    let array=[5,4,19,2,7];
    function findMax(acc,val)
    {
     if(val>acc){
       acc=val; 
     }
    }

    let biggest=arrays.reduce(findMax); // 19
  1. find an element that not repeated.
    arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
    v = 0
    for i in range(len(arr)):
    v = v ^ arr[i]
    print(value)  //6

how do I get a new line, after using float:left?

you can also use

<br style="clear:both" />

How to check certificate name and alias in keystore files?

You can run from Java code.

try {

        File file = new File(keystore location);
        InputStream is = new FileInputStream(file);
        KeyStore keystore = KeyStore.getInstance(KeyStore.getDefaultType());
        String password = "password";
        keystore.load(is, password.toCharArray());


        Enumeration<String> enumeration = keystore.aliases();
        while(enumeration.hasMoreElements()) {
            String alias = enumeration.nextElement();
            System.out.println("alias name: " + alias);
            Certificate certificate = keystore.getCertificate(alias);
            System.out.println(certificate.toString());

        }

    } catch (java.security.cert.CertificateException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        if(null != is)
            try {
                is.close();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
    }

Certificate class holds all information about the keystore.

UPDATE- OBTAIN PRIVATE KEY

Key key = keyStore.getKey(alias, password.toCharArray());
String encodedKey = new Base64Encoder().encode(key.getEncoded());
System.out.println("key ? " + encodedKey);

@prateek Hope this is what you looking for!

Unable to set default python version to python3 in ubuntu

As an added extra, you can add an alias for pip as well (in .bashrc or bash_aliases):

alias pip='pip3'

You many find that a clean install of python3 actually points to python3.x so you may need:

alias pip='pip3.6'
alias python='python3.6'

How to display an alert box from C# in ASP.NET?

You can create a global method to show message(alert) in your web form application.

public static class PageUtility
{
    public static void MessageBox(System.Web.UI.Page page,string strMsg)
    {
        //+ character added after strMsg "')"
        ScriptManager.RegisterClientScriptBlock(page, page.GetType(), "alertMessage", "alert('" + strMsg + "')", true);

    }
}

webform.aspx

protected void btnSave_Click(object sender, EventArgs e)
{
    PageUtility.MessageBox(this, "Success !");
}

Converting milliseconds to a date (jQuery/JavaScript)

Try using this code:

var datetime = 1383066000000; // anything
var date = new Date(datetime);
var options = {
        year: 'numeric', month: 'numeric', day: 'numeric',
    };

var result = date.toLocaleDateString('en', options); // 10/29/2013

See more: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/toLocaleDateString

Echo a blank (empty) line to the console from a Windows batch file

There is often the tip to use 'echo.'

But that is slow, and it could fail with an error message, as cmd.exe will search first for a file named 'echo' (without extension) and only when the file doesn't exists it outputs an empty line.

You could use echo(. This is approximately 20 times faster, and it works always. The only drawback could be that it looks odd.

More about the different ECHO:/\ variants is at DOS tips: ECHO. FAILS to give text or blank line.

'names' attribute must be the same length as the vector

The mistake I made that coerced this error was attempting to rename a column in a loop that I was no longer selecting in my SQL. This could also be caused by trying to do the same thing in a column that you were planning to select. Make sure the column that you are trying to change actually exists.

Finding the max value of an attribute in an array of objects

Comparison of three ONELINERS which handle minus numbers case (input in a array):

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y; // 30 chars time complexity:  O(n)

var maxB = a.sort((a,b)=>b.y-a.y)[0].y;    // 27 chars time complexity:  O(nlogn)
           
var maxC = Math.max(...a.map(o=>o.y));     // 26 chars time complexity: >O(2n)

editable example here. Ideas from: maxA, maxB and maxC (side effect of maxB is that array a is changed because sort is in-place).

_x000D_
_x000D_
var a = [
  {"x":"8/11/2009","y":0.026572007},{"x":"8/12/2009","y":0.025057454},    
  {"x":"8/14/2009","y":0.031004457},{"x":"8/13/2009","y":0.024530916}
]

var maxA = a.reduce((a,b)=>a.y>b.y?a:b).y;
var maxC = Math.max(...a.map(o=>o.y));
var maxB = a.sort((a,b)=>b.y-a.y)[0].y;

document.body.innerHTML=`<pre>maxA: ${maxA}\nmaxB: ${maxB}\nmaxC: ${maxC}</pre>`;
_x000D_
_x000D_
_x000D_

For bigger arrays the Math.max... will throw exception: Maximum call stack size exceeded (Chrome 76.0.3809, Safari 12.1.2, date 2019-09-13)

_x000D_
_x000D_
let a = Array(400*400).fill({"x": "8/11/2009", "y": 0.026572007 }); 

// Exception: Maximum call stack size exceeded

try {
  let max1= Math.max.apply(Math, a.map(o => o.y));
} catch(e) { console.error('Math.max.apply:', e.message) }

try {
  let max2= Math.max(...a.map(o=>o.y));
} catch(e) { console.error('Math.max-map:', e.message) }
_x000D_
_x000D_
_x000D_

Benchmark for the 4 element array

MySql Table Insert if not exist otherwise update

Try using this:

If you specify ON DUPLICATE KEY UPDATE, and a row is inserted that would cause a duplicate value in a UNIQUE index orPRIMARY KEY, MySQL performs an [UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...

The ON DUPLICATE KEY UPDATE clause can contain multiple column assignments, separated by commas.

With ON DUPLICATE KEY UPDATE, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify the CLIENT_FOUND_ROWS flag to mysql_real_connect() when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...

Capturing image from webcam in java?

Some time ago I've created generic Java library which can be used to take pictures with a PC webcam. The API is very simple, not overfeatured, can work standalone, but also supports additional webcam drivers like OpenIMAJ, JMF, FMJ, LTI-CIVIL, etc, and some IP cameras.

Link to the project is https://github.com/sarxos/webcam-capture

Example code (take picture and save in test.jpg):

Webcam webcam = Webcam.getDefault();
webcam.open();
BufferedImage image = webcam.getImage();
ImageIO.write(image, "JPG", new File("test.jpg"));

It is also available in Maven Central Repository or as a separate ZIP which includes all required dependencies and 3rd party JARs.

AngularJS : Prevent error $digest already in progress when calling $scope.$apply()

First of all, don’t fix it this way

if ( ! $scope.$$phase) { 
  $scope.$apply(); 
}

It does not make sense because $phase is just a boolean flag for the $digest cycle, so your $apply() sometimes won’t run. And remember it’s a bad practice.

Instead, use $timeout

    $timeout(function(){ 
  // Any code in here will automatically have an $scope.apply() run afterwards 
$scope.myvar = newValue; 
  // And it just works! 
});

If you are using underscore or lodash, you can use defer():

_.defer(function(){ 
  $scope.$apply(); 
});

Fragment Inside Fragment

Fragments can be added inside other fragments but then you will need to remove it from parent Fragment each time when onDestroyView() method of parent fragment is called. And again add it in Parent Fragment's onCreateView() method.

Just do like this :

@Override
    public void onDestroyView()
    {
                FragmentManager mFragmentMgr= getFragmentManager();
        FragmentTransaction mTransaction = mFragmentMgr.beginTransaction();
                Fragment childFragment =mFragmentMgr.findFragmentByTag("qa_fragment")
        mTransaction.remove(childFragment);
        mTransaction.commit();
        super.onDestroyView();
    }

How can I import Swift code to Objective-C?

There's one caveat if you're importing Swift code into your Objective-C files within the same framework. You have to do it with specifying the framework name and angle brackets:

#import <MyFramework/MyFramework-Swift.h>

MyFramework here is the "Product Module Name" build setting (PRODUCT_NAME = MyFramework).

Simply adding #import "MyFramework-Swift.h" won't work. If you check the built products directory (before such an #import is added, so you've had at least one successful build with some Swift code in the target), then you should still see the file MyFramework-Swift.h in the Headers directory.

How to define static constant in a class in swift

If you actually want a static property of your class, that isn't currently supported in Swift. The current advice is to get around that by using global constants:

let testStr = "test"
let testStrLen = countElements(testStr)

class MyClass {
    func myFunc() {
    }
}

If you want these to be instance properties instead, you can use a lazy stored property for the length -- it will only get evaluated the first time it is accessed, so you won't be computing it over and over.

class MyClass {
    let testStr: String = "test"
    lazy var testStrLen: Int = countElements(self.testStr)

    func myFunc() {
    }
}

How to include file in a bash shell script

Above answers are correct, but if run script in other folder, there will be some problem.

For example, the a.sh and b.sh are in same folder, a include b with . ./b.sh to include.

When run script out of the folder, for example with xx/xx/xx/a.sh, file b.sh will not found: ./b.sh: No such file or directory.

I use

. $(dirname "$0")/b.sh

C++ queue - simple example

std::queue<myclass*> that's it

Using Html.ActionLink to call action on different controller

try it it is working fine

  <%:Html.ActionLink("Details","Details","Product",  new {id=item.dateID },null)%>

Extract only right most n letters from a string

Just a thought:

public static string Right(this string @this, int length) {
    return @this.Substring(Math.Max(@this.Length - length, 0));
}

Update Rows in SSIS OLEDB Destination

You can't do a bulk-update in SSIS within a dataflow task with the OOB components.

The general pattern is to identify your inserts, updates and deletes and push the updates and deletes to a staging table(s) and after the Dataflow Task, use a set-based update or delete in an Execute SQL Task. Look at Andy Leonard's Stairway to Integration Services series. Scroll about 3/4 the way down the article to "Set-Based Updates" to see the pattern.

Stage data

http://www.sqlservercentral.com/Images/11369.png

Set based updates

enter image description here

You'll get much better performance with a pattern like this versus using the OLE DB Command transformation for anything but trivial amounts of data.

If you are into third party tools, I believe CozyRoc and I know PragmaticWorks have a merge destination component.

Save and load weights in keras

Here is a YouTube video that explains exactly what you're wanting to do: Save and load a Keras model

There are three different saving methods that Keras makes available. These are described in the video link above (with examples), as well as below.

First, the reason you're receiving the error is because you're calling load_model incorrectly.

To save and load the weights of the model, you would first use

model.save_weights('my_model_weights.h5')

to save the weights, as you've displayed. To load the weights, you would first need to build your model, and then call load_weights on the model, as in

model.load_weights('my_model_weights.h5')

Another saving technique is model.save(filepath). This save function saves:

  • The architecture of the model, allowing to re-create the model.
  • The weights of the model.
  • The training configuration (loss, optimizer).
  • The state of the optimizer, allowing to resume training exactly where you left off.

To load this saved model, you would use the following:

from keras.models import load_model
new_model = load_model(filepath)'

Lastly, model.to_json(), saves only the architecture of the model. To load the architecture, you would use

from keras.models import model_from_json
model = model_from_json(json_string)