Programs & Examples On #Zend lucene

[tag:Zend-Lucene] is the lucene library of the Zend Framework, which is a powerful open source web application framework for developing PHP 5 web applications. The Zend Framework module is a Drupal API module that makes the framework accessible to other Drupal modules.

How to extract text from the PDF document?

Download the class.pdf2text.php @ https://pastebin.com/dvwySU1a or http://www.phpclasses.org/browse/file/31030.html (Registration required)

Code:

include('class.pdf2text.php');
$a = new PDF2Text();
$a->setFilename('filename.pdf'); 
$a->decodePDF();
echo $a->output(); 

  • class.pdf2text.php Project Home

  • pdf2textclass doesn't work with all the PDF's I've tested, If it doesn't work for you, try PDF Parser


The apk must be signed with the same certificates as the previous version

If you have previous apk file with you(backup) then use jarSigner to extract certificate from that that apk, then use that key or use keytool to clone that certificate, may be that will help... Helpful links are jarsigner docs and keytool docs.

How to initialize a JavaScript Date to a particular time zone

Background

JavaScript's Date object tracks time in UTC internally, but typically accepts input and produces output in the local time of the computer it's running on. It has very few facilities for working with time in other time zones.

The internal representation of a Date object is a single number, representing the number of milliseconds that have elapsed since 1970-01-01 00:00:00 UTC, without regard to leap seconds. There is no time zone or string format stored in the Date object itself. When various functions of the Date object are used, the computer's local time zone is applied to the internal representation. If the function produces a string, then the computer's locale information may be taken into consideration to determine how to produce that string. The details vary per function, and some are implementation-specific.

The only operations the Date object can do with non-local time zones are:

  • It can parse a string containing a numeric UTC offset from any time zone. It uses this to adjust the value being parsed, and stores the UTC equivalent. The original local time and offset are not retained in the resulting Date object. For example:

    var d = new Date("2020-04-13T00:00:00.000+08:00");
    d.toISOString()  //=> "2020-04-12T16:00:00.000Z"
    d.valueOf()      //=> 1586707200000  (this is what is actually stored in the object)
    
  • In environments that have implemented the ECMASCript Internationalization API (aka "Intl"), a Date object can produce a locale-specific string adjusted to a given time zone identifier. This is accomplished via the timeZone option to toLocaleString and its variations. Most implementations will support IANA time zone identifiers, such as 'America/New_York'. For example:

    var d = new Date("2020-04-13T00:00:00.000+08:00");
    d.toLocaleString('en-US', { timeZone: 'America/New_York' })
    //=> "4/12/2020, 12:00:00 PM"
    // (midnight in China on Apring 13th is noon in New York on April 12th)
    

    Most modern environments support the full set of IANA time zone identifiers (see the compatibility table here). However, keep in mind that the only identifier required to be supported by Intl is 'UTC', thus you should check carefully if you need to support older browsers or atypical environments (for example, lightweight IoT devices).

Libraries

There are several libraries that can be used to work with time zones. Though they still cannot make the Date object behave any differently, they typically implement the standard IANA timezone database and provide functions for using it in JavaScript. Modern libraries use the time zone data supplied by the Intl API, but older libraries typically have overhead, especially if you are running in a web browser, as the database can get a bit large. Some of these libraries also allow you to selectively reduce the data set, either by which time zones are supported and/or by the range of dates you can work with.

Here are the libraries to consider:

Intl-based Libraries

New development should choose from one of these implementations, which rely on the Intl API for their time zone data:

Non-Intl Libraries

These libraries are maintained, but carry the burden of packaging their own time zone data, which can be quite large.

* While Moment and Moment-Timezone were previously recommended, the Moment team now prefers users chose Luxon for new development.

Discontinued Libraries

These libraries have been officially discontinued and should no longer be used.

Future Proposals

The TC39 Temporal Proposal aims to provide a new set of standard objects for working with dates and times in the JavaScript language itself. This will include support for a time zone aware object.

Is there an equivalent to CTRL+C in IPython Notebook in Firefox to break cells that are running?

To add to the above: If interrupt is not working, you can restart the kernel.

Go to the kernel dropdown >> restart >> restart and clear output. This usually does the trick. If this still doesn't work, kill the kernel in the terminal (or task manager) and then restart.

Interrupt doesn't work well for all processes. I especially have this problem using the R kernel.

Renew Provisioning Profile

They change how this works so often. This is what I had to do this time (May 2016):

  • Add a new provisioning profile in the Developer Member Center
  • Open XCode preferences, Account > Choose Apple ID > Choose Team Name > View Details
  • Click the Download button in the Action column for the newly-created provisioning profile

Could not find main class HelloWorld

You either want to add "." to your CLASSPATH to specify the current directory, or add it manually at run time the way unbeli suggested.

Java properties UTF-8 encoding in Eclipse

There are too many points in the process you describe where errors can occur, so I won't try to guess what you're doing wrong, but I think I know what's happening under the hood.

EF BF BD is the UTF-8 encoded form of U+FFFD, the standard replacement character that's inserted by decoders when they encounter malformed input. It sounds like your text is being saved as ISO-8859-1, then read as if it were UTF-8, then saved as UTF-8, then converted to the Properties format using native2ascii using the platform default encoding (e.g., windows-1252).

ü              => 0xFC                // save as ISO-8859-1
0xFC           => U+FFFD              // read as UTF-8
U+FFFD         => 0xEF 0xBF 0xBD      // save as UTF-8
0xEF 0xBF 0xBD => \u00EF\u00BF\u00BD  // native2ascii

I suggest you leave the "file.encoding" property alone. Like "file.separator" and "line.separator", it's not nearly as useful as you would expect it to be. Instead, get into the habit of always specifying an encoding when reading and writing text files.

How to check if a table contains an element in Lua?

I know this is an old post, but I wanted to add something for posterity. The simple way of handling the issue that you have is to make another table, of value to key.

ie. you have 2 tables that have the same value, one pointing one direction, one pointing the other.

function addValue(key, value)
    if (value == nil) then
        removeKey(key)
        return
    end
    _primaryTable[key] = value
    _secodaryTable[value] = key
end

function removeKey(key)
    local value = _primaryTable[key]
    if (value == nil) then
        return
    end
    _primaryTable[key] = nil
    _secondaryTable[value] = nil
end

function getValue(key)
    return _primaryTable[key]
end

function containsValue(value)
    return _secondaryTable[value] ~= nil
end

You can then query the new table to see if it has the key 'element'. This prevents the need to iterate through every value of the other table.

If it turns out that you can't actually use the 'element' as a key, because it's not a string for example, then add a checksum or tostring on it for example, and then use that as the key.

Why do you want to do this? If your tables are very large, the amount of time to iterate through every element will be significant, preventing you from doing it very often. The additional memory overhead will be relatively small, as it will be storing 2 pointers to the same object, rather than 2 copies of the same object. If your tables are very small, then it will matter much less, infact it may even be faster to iterate than to have another map lookup.

The wording of the question however strongly suggests that you have a large number of items to deal with.

How to make modal dialog in WPF?

Did you try showing your window using the ShowDialog method?

Don't forget to set the Owner property on the dialog window to the main window. This will avoid weird behavior when Alt+Tabbing, etc.

POST data to a URL in PHP

cURL-less you can use in php5

$url = 'URL';
$data = array('field1' => 'value', 'field2' => 'value');
$options = array(
        'http' => array(
        'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
        'method'  => 'POST',
        'content' => http_build_query($data),
    )
);

$context  = stream_context_create($options);
$result = file_get_contents($url, false, $context);
var_dump($result);

HTML/Javascript: how to access JSON data loaded in a script tag with src set

You can't load JSON like that, sorry.

I know you're thinking "why I can't I just use src here? I've seen stuff like this...":

<script id="myJson" type="application/json">
 { 
   name: 'Foo' 
 }
</script>

<script type="text/javascript">
    $(function() {
        var x = JSON.parse($('#myJson').html());
        alert(x.name); //Foo
     });
</script>

... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.

You have a short list of options to load your JSON from a remote file:

  1. Use $.get('your.json') or some other such AJAX method.
  2. Write a file that sets a global variable to your json. (seems hokey).
  3. Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
  4. Consult a voodoo priest.

Final point:

Remote JSON Request after page loads is also not an option, in case you want to suggest that.

... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.

How can I properly use a PDO object for a parameterized SELECT query

I've been working with PDO lately and the answer above is completely right, but I just wanted to document that the following works as well.

$nametosearch = "Tobias";
$conn = new PDO("server", "username", "password");
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$sth = $conn->prepare("SELECT `id` from `tablename` WHERE `name` = :name");
$sth->bindParam(':name', $nametosearch);
// Or sth->bindParam(':name', $_POST['namefromform']); depending on application
$sth->execute();

COALESCE Function in TSQL

Here is the way I look at COALESCE...and hopefully it makes sense...

In a simplistic form….

Coalesce(FieldName, 'Empty')

So this translates to…If "FieldName" is NULL, populate the field value with the word "EMPTY".

Now for mutliple values...

Coalesce(FieldName1, FieldName2, Value2, Value3)

If the value in Fieldname1 is null, fill it with the value in Fieldname2, if FieldName2 is NULL, fill it with Value2, etc.

This piece of test code for the AdventureWorks2012 sample database works perfectly & gives a good visual explanation of how COALESCE works:

SELECT Name, Class, Color, ProductNumber,
COALESCE(Class, Color, ProductNumber) AS FirstNotNull
FROM Production.Product

Installing Oracle Instant Client

I was able to setup Oracle Instant Client (Basic) 11g2 and Oracle ODBC (32bit) drivers on my 32bit Windows 7 PC. Note: you'll need a 'tnsnames.ora' file because it doesn't come with one. You can Google examples and copy/paste into a text file, change the parameters for your environment.

Setting up Oracle Instant Client-Basic 11g2 (Win7 32-bit)
(I think there's another step or two if your using 64-bit)

Oracle Instant Client

  • Unzip Oracle Instant Client - Basic
  • Put contents in folder like "C:\instantclient"
  • Edit PATH evironment variable, add path to Instant Client folder to the Variable Value.
  • Add new Variable called "TNS_ADMIN" point to same folder as Instant Client.
  • I had to create a "tnsnames.ora" file because it doesn't come with one. Put it in same folder as the client.
  • reboot or use Task Manager to kill "explorer.exe" and restart it to refresh the PATH environment variables.

ODBC Drivers

  • Unzip ODBC drivers
  • Copy all files into same folder as client "C:\instantclient"
  • Use command prompt to run "odbc_install.exe" (should say it was successful)

Note: The "un-documented" things that were hanging me up where...
- All files (Client and Drivers) needed to be in the same folder (nothing in sub-folders).
- Running the ODBC driver from the command prompt will allow you to see if it installs successfully. Double-clicking the installer just flashed a box on the screen, no idea it was failing because no error dialog.

After you've done this you should be able to setup a new DSN Data Source using the Oracle ODBC driver.
-Hope this helps someone else.

How to select clear table contents without destroying the table?

Try just clearing the data (not the entire table including headers):

ACell.ListObject.DataBodyRange.ClearContents

Is Visual Studio Community a 30 day trial?

No, Community edition is free, so just sign-in and rid the warning. For more detail please check following link.
https://visualstudio.microsoft.com/vs/support/community-edition-expired-buy-license/

Get Date Object In UTC format in Java

You can subtract the time zone difference from now.

final Calendar calendar  = Calendar.getInstance();
final int      utcOffset = calendar.get(Calendar.ZONE_OFFSET) + calendar.get(Calendar.DST_OFFSET);
final long     tempDate  = new Date().getTime();

return new Date(tempDate - utcOffset);

Cannot ignore .idea/workspace.xml - keeps popping up

If you have multiple projects in your git repo, .idea/workspace.xml will not match to any files.

Instead, do the following:

$ git rm -f **/.idea/workspace.xml

And make your .gitignore look something like this:

# User-specific stuff:
**/.idea/workspace.xml
**/.idea/tasks.xml
**/.idea/dictionaries
**/.idea/vcs.xml
**/.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
**/.idea/dataSources.ids
**/.idea/dataSources.xml
**/.idea/dataSources.local.xml
**/.idea/sqlDataSources.xml
**/.idea/dynamic.xml
**/.idea/uiDesigner.xml

## File-based project format:
*.iws

# IntelliJ
/out/

How to get past the login page with Wget?

You don't need cURL to do POSTed form data. --post-data 'key1=value1&key2=value2' works just fine. Note: you can also pass a file name to wget with the POST data in the file.

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

For anyone using knockout.js, I wanted some knockout.js observable properties that would tell me when the breakpoints are hit. I opted to use Modernizr's support for css-style media queries so the numbers matched the bootstrap definitions, and to get modernizr's compatibility benefits. My knockout view model is as follows:

var viewModel = function() {
    // depends on jquery, Modernizr
    var self = this;
    self.widthXsOrLess = ko.observable();
    self.widthSmOrLess = ko.observable();
    self.widthMdOrLess = ko.observable();
    var setWindowSizeVars = function() {
        self.widthXsOrLess(!Modernizr.mq('(min-width: 768px)'));
        self.widthSmOrLess(!Modernizr.mq('(min-width: 992px)'));
        self.widthMdOrLess(!Modernizr.mq('(min-width: 1200px)'));
    };
    $(window).resize(setWindowSizeVars);
    setWindowSizeVars();
};

How do I detect if Python is running as a 64-bit application?

import platform
platform.architecture()

From the Python docs:

Queries the given executable (defaults to the Python interpreter binary) for various architecture information.

Returns a tuple (bits, linkage) which contain information about the bit architecture and the linkage format used for the executable. Both values are returned as strings.

PKIX path building failed in Java application

Per your pastebin, you need to add the proxy.tkk.com certificate to the truststore.

Create two-dimensional arrays and access sub-arrays in Ruby

a = Array.new(Array.new(4))

0.upto(a.length-1) do |i|
  0.upto(a.length-1) do |j|
    a[i[j]] = 1
  end
end

0.upto(a.length-1) do |i|
  0.upto(a.length-1) do |j|
    print a[i[j]] = 1 #It's not a[i][j], but a[i[j]]
  end
  puts "\n"
end

Microsoft.Office.Core Reference Missing

I have the same trouble. I went to Add references, COM tab, an select Microsoft Office 15.0 Objetct Library. Ok, and my problem ends.

part of my code is:

EXCEL.Range rango;
            rango = (EXCEL.Range)HojadetrabajoExcel.get_Range("AE13", "AK23");
            rango.Select();
      //      EXCEL.Pictures Lafoto = (EXCEL.Pictures).HojadetrabajoExcel.Pictures(System.Reflection.Missing.Value);
            EXCEL.Pictures Lafoto = HojadetrabajoExcel.Pictures(System.Reflection.Missing.Value);

            HojadetrabajoExcel.Shapes.AddPicture(@"D:\GENETICA HUMANA\Reportes\imagenes\" + Variables.nombreimagen,
                Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoCTrue,
                float.Parse(rango.Left.ToString()),float.Parse(rango.Top.ToString()), float.Parse(rango.Width.ToString()),
                float.Parse(rango.Height.ToString()));

Python: how to print range a-z?

Hints:

import string
print string.ascii_lowercase

and

for i in xrange(0, 10, 2):
    print i

and

"hello{0}, world!".format('z')

How to use callback with useState hook in react

Another way to achieve this:

_x000D_
_x000D_
const [Name, setName] = useState({val:"", callback: null});_x000D_
React.useEffect(()=>{_x000D_
  console.log(Name)_x000D_
  const {callback} = Name;_x000D_
  callback && callback();_x000D_
}, [Name]);_x000D_
setName({val:'foo', callback: ()=>setName({val: 'then bar'})})
_x000D_
_x000D_
_x000D_

ERROR 403 in loading resources like CSS and JS in my index.php

You need to change permissions on the folder bootstrap/css. Your super user may be able to access it but it doesn't mean apache or nginx have access to it, that's why you still need to change the permissions.

Tip: I usually make the apache/nginx's user group owner of that kind of folders and give 775 permission to it.

PHP substring extraction. Get the string before the first '/' or the whole string

I think this should work?

substr($mystring, 0, (($pos = (strpos($mystring, '/') !== false)) ? $pos : strlen($mystring)));

How do I remove an object from an array with JavaScript?

var user = [
  { id: 1, name: 'Siddhu' },
  { id: 2, name: 'Siddhartha' },
  { id: 3, name: 'Tiwary' }
];

var recToRemove={ id: 1, name: 'Siddhu' };

user.splice(user.indexOf(recToRemove),1)

SOAP-UI - How to pass xml inside parameter

NOTE: This one is just an alternative for the previous provided .NET framework 3.5 and above

You can send it as raw xml

<test>or like this</test>

If you declare the paramater2 as XElement data type

Mount current directory as a volume in Docker on Windows 10

For Git Bash for Windows (in ConEmu), the following works for me (for Docker Windows containers):

docker run --rm -it -v `pwd -W`:c:/api microsoft/dotnet:2-runtime

Note the backticks/backquotes around pwd -W!

With all other variations of PWD I've tried I've received: "Error response from daemon: invalid volume specification: ..."

Update: The above was for Docker Windows containers, for Linux containers use:

docker run --rm -it -v `pwd -W`:/api -p 8080:80 microsoft/aspnetcore:2

Search for a string in all tables, rows and columns of a DB

I think this can be an easiest way to find a string in all rows of your database -without using cursors and FOR XML-.

CREATE PROCEDURE SPFindAll (@find VARCHAR(max) = '')
AS
BEGIN
    SET NOCOUNT ON;
    --
    DECLARE @query VARCHAR(max) = ''

    SELECT  @query = @query + 
            CASE 
                WHEN @query = '' THEN '' 
                ELSE ' UNION ALL '
            END +
            'SELECT ''' + s.name + ''' As schemaName, ''' + t.name + ''' As tableName, ''' + c.name + ''' As ColumnName, [' + c.name + '] COLLATE DATABASE_DEFAULT As [Data] FROM [' + s.name + '].[' + t.name + '] WHERE [' + c.name + '] Like ''%' + @find + '%'''
    FROM 
        sys.schemas s
        INNER JOIN
        sys.tables t ON s.[schema_id] = t.[schema_id]
        INNER JOIN 
        sys.columns c ON t.[object_id] = c.[object_id]
        INNER JOIN
        sys.types ty ON c.user_type_id = ty.user_type_id
    WHERE
        ty.name LIKE '%char'

    EXEC(@query)
END

By creating this stored procedure you can run it for any string you want to find like this:

EXEC SPFindAll 'Hello World'

The result will be like this:

schemaName | tableName | columnName | Data
-----------+-----------+------------+-----------------------
schema1    | Table1    | Column1    | Hello World
schema1    | Table1    | Column1    | Hello World!
schema1    | Table2    | Column1    | I say "Hello World".
schema1    | Table2    | Column2    | Hello World

Process with an ID #### is not running in visual studio professional 2013 update 3

Running as administrator didn't seem to make a difference when I got this.

  • Make sure all iisexpress.exe processes had been closed
  • Edit <path_to_your_solution>\Solution\.vs\config\applicationhost.config
  • Change the site name.

    <site name="MySite" id="1" serverAutoStart="true">

    to :

    <site name="MySite2" id="1" serverAutoStart="true">

  • That fixed it for me

array filter in python?

>>> a = set([6, 7, 8, 9, 10, 11, 12])
>>> sub_a = set([6, 9, 12])
>>> a - sub_a
set([8, 10, 11, 7])

Stretch child div height to fill parent that has dynamic height

Use display: flex to stretch your divs:

div#container {
    padding:20px;
    background:#F1F1F1;
    display: flex;
}

.content {
    width:150px;
    background:#ddd;
    padding:10px;
    margin-left: 10px;
}

JSFIDDLE

How to make IPython notebook matplotlib plot inline

Ctrl + Enter

%matplotlib inline

Magic Line :D

See: Plotting with Matplotlib.

How to show PIL images on the screen?

I tested this and it works fine for me:

from PIL import Image
im = Image.open('image.jpg')
im.show()

C++ int float casting

When doing integer division, the result will always be a integer unless one or more of the operands are a float. Just type cast one/both of the operands to a float and the compiler will do the conversion. Type casting is used when you want the arithmetic to perform as it should so the result will be the correct data type.

float m = static_cast<float>(a.y - b.y) / (a.x - b.x);

Ansible - Use default if a variable is not defined

Not totally related, but you can also check for both undefined AND empty (for e.g my_variable:) variable. (NOTE: only works with ansible version > 1.9, see: link)

- name: Create user
  user:
    name: "{{ ((my_variable == None) | ternary('default_value', my_variable)) \
    if my_variable is defined else 'default_value' }}"

PHP & MySQL: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given

The query either returned no rows or is erroneus, thus FALSE is returned. Change it to

if (!$dbc || mysqli_num_rows($dbc) == 0)

mysqli_num_rows:

Return Values

Returns TRUE on success or FALSE on failure. For SELECT, SHOW, DESCRIBE or EXPLAIN mysqli_query() will return a result object.

How do I create directory if it doesn't exist to create a file?

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

Saving utf-8 texts with json.dumps as UTF8, not as \u escape sequence

Using ensure_ascii=False in json.dumps is the right direction to solve this problem, as pointed out by Martijn. However, this may raise an exception:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xe7 in position 1: ordinal not in range(128)

You need extra settings in either site.py or sitecustomize.py to set your sys.getdefaultencoding() correct. site.py is under lib/python2.7/ and sitecustomize.py is under lib/python2.7/site-packages.

If you want to use site.py, under def setencoding(): change the first if 0: to if 1: so that python will use your operation system's locale.

If you prefer to use sitecustomize.py, which may not exist if you haven't created it. simply put these lines:

import sys
reload(sys)
sys.setdefaultencoding('utf-8')

Then you can do some Chinese json output in utf-8 format, such as:

name = {"last_name": u"?"}
json.dumps(name, ensure_ascii=False)

You will get an utf-8 encoded string, rather than \u escaped json string.

To verify your default encoding:

print sys.getdefaultencoding()

You should get "utf-8" or "UTF-8" to verify your site.py or sitecustomize.py settings.

Please note that you could not do sys.setdefaultencoding("utf-8") at interactive python console.

Best way to check that element is not present using Selenium WebDriver with java

Unable to comment to The Meteor Test Manual, since I have no rep, but I wanted to provide an example that took me quite awhile to figure out:

Assert.assertEquals(0, wd.findElements(By.locator("locator")).size());

This assertion verifies that there are no matching elements in the DOM and returns the value of Zero, so the assertion passes when the element is not present. Also it would fail if it was present.

How to check empty object in angular 2 template using *ngIf

Above answers are okay. But I have found a really nice option to use following in the view:

{{previous_info?.title}}

probably duplicated question Angular2 - error if don't check if {{object.field}} exists

How can I use async/await at the top level?

The actual solution to this problem is to approach it differently.

Probably your goal is some sort of initialization which typically happens at the top level of an application.

The solution is to ensure that there is only ever one single JavaScript statement at the top level of your application. If you have only one statement at the top of your application, then you are free to use async/await at every other point everwhere (subject of course to normal syntax rules)

Put another way, wrap your entire top level in a function so that it is no longer the top level and that solves the question of how to run async/await at the top level of an application - you don't.

This is what the top level of your application should look like:

import {application} from './server'

application();

Bootstrap 3 : Vertically Center Navigation Links when Logo Increasing The Height of Navbar

Bootstrap sets the height of the navbar automatically to 50px. The padding above and below links is set to 15px. I think that bootstrap is adding padding to your logo.

You can either remove some of the padding above and below your logo or you can add more padding above and below links.

Adding more padding should look something like this:

nav.navbar-inverse>li>a {
 padding-top: 25px;
 padding-bottom: 25px;
}

The Import android.support.v7 cannot be resolved

I tried the answer described here but it doesn´t worked for me. I have the last Android SDK tools ver. 23.0.2 and Android SDK Platform-tools ver. 20

The support library android-support-v4.jar is causing this conflict, just delete the library under /libs folder of your project, don´t be scared, the library is already contained in the library appcompat_v7, clean and build your project, and your project will work like a charm!

enter image description here

How to iterate a table rows with JQuery and access some cell values?

$("tr.item").each(function() {
  $this = $(this);
  var value = $this.find("span.value").html();
  var quantity = $this.find("input.quantity").val();
});

Split large string in n-size chunks in JavaScript

My issue with the above solution is that it beark the string into formal size chunks regardless of the position in the sentences.

I think the following a better approach; although it needs some performance tweaking:

 static chunkString(str, length, size,delimiter='\n' ) {
        const result = [];
        for (let i = 0; i < str.length; i++) {
            const lastIndex = _.lastIndexOf(str, delimiter,size + i);
            result.push(str.substr(i, lastIndex - i));
            i = lastIndex;
        }
        return result;
    }

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

Why does one use dependency injection?

Quite frankly, I believe people use these Dependency Injection libraries/frameworks because they just know how to do things in runtime, as opposed to load time. All this crazy machinery can be substituted by setting your CLASSPATH environment variable (or other language equivalent, like PYTHONPATH, LD_LIBRARY_PATH) to point to your alternative implementations (all with the same name) of a particular class. So in the accepted answer you'd just leave your code like

var logger = new Logger() //sane, simple code

And the appropriate logger will be instantiated because the JVM (or whatever other runtime or .so loader you have) would fetch it from the class configured via the environment variable mentioned above.

No need to make everything an interface, no need to have the insanity of spawning broken objects to have stuff injected into them, no need to have insane constructors with every piece of internal machinery exposed to the world. Just use the native functionality of whatever language you're using instead of coming up with dialects that won't work in any other project.

P.S.: This is also true for testing/mocking. You can very well just set your environment to load the appropriate mock class, in load time, and skip the mocking framework madness.

Use of *args and **kwargs

You can have a look at python docs (docs.python.org in the FAQ), but more specifically for a good explanation the mysterious miss args and mister kwargs (courtesy of archive.org) (the original, dead link is here).

In a nutshell, both are used when optional parameters to a function or method are used. As Dave says, *args is used when you don't know how many arguments may be passed, and **kwargs when you want to handle parameters specified by name and value as in:

myfunction(myarg=1)

Running CMD command in PowerShell

Try this:

& "C:\Program Files (x86)\Microsoft Configuration Manager\AdminConsole\bin\i386\CmRcViewer.exe" PCNAME

To PowerShell a string "..." is just a string and PowerShell evaluates it by echoing it to the screen. To get PowerShell to execute the command whose name is in a string, you use the call operator &.

Self Join to get employee manager name

Additionally you may want to get managers and their reports count with -

SELECT e2.ename ,count(e1.ename)  FROM employee_s e1 LEFT OUTER JOIN employee_s e2 
ON e1.manager_id = e2.eid
group by e2.ename;

How to import JSON File into a TypeScript file?

First solution - simply change the extension of your .json file to .ts and add export default at the beginning of the file, like so:

export default {
   property: value;
}

Then you can just simply import the file without the need to add typings, like so:

import data from 'data';

Second solution get the json via HttpClient.

Inject HttpClient into your component, like so:

export class AppComponent  {
  constructor(public http: HttpClient) {}
}

and then use this code:

this.http.get('/your.json').subscribe(data => {
  this.results = data;
});

https://angular.io/guide/http

This solution has one clear adventage over other solutions provided here - it doesn't require you to rebuild entire application if your json will change (it's loaded dynamically from a separate file, so you can modify only that file).

github: server certificate verification failed

It can be also self-signed certificate, etc. Turning off SSL verification globally is unsafe. You can install the certificate so it will be visible for the system, but the certificate should be perfectly correct.

Or you can clone with one time configuration parameter, so the command will be:

git clone -c http.sslverify=false https://myserver/<user>/<project>.git;

GIT will remember the false value, you can check it in the <project>/.git/config file.

Which mime type should I use for mp3

Use .mp3 audio/mpeg, that's the one I always used. I guess others are just aliases.

How can I call controller/view helper methods from the console in Ruby on Rails?

If the method is the POST method then:

app.post 'controller/action?parameter1=value1&parameter2=value2'

(Here parameters will be as per your applicability.)

Else if it is the GET method then:

app.get 'controller/action'

Array of structs example

You've started right - now you just need to fill the each student structure in the array:

struct student
{
    public int s_id;
    public String s_name, c_name, dob;
}
class Program
{
    static void Main(string[] args)
    {
        student[] arr = new student[4];

        for(int i = 0; i < 4; i++)
        {
            Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");


            arr[i].s_id = Int32.Parse(Console.ReadLine());
            arr[i].s_name = Console.ReadLine();
            arr[i].c_name = Console.ReadLine();
            arr[i].s_dob = Console.ReadLine();
       }
    }
}

Now, just iterate once again and write these information to the console. I will let you do that, and I will let you try to make program to take any number of students, and not just 4.

Proper use of mutexes in Python

I would like to improve answer from chris-b a little bit more.

See below for my code:

from threading import Thread, Lock
import threading
mutex = Lock()


def processData(data, thread_safe):
    if thread_safe:
        mutex.acquire()
    try:
        thread_id = threading.get_ident()
        print('\nProcessing data:', data, "ThreadId:", thread_id)
    finally:
        if thread_safe:
            mutex.release()


counter = 0
max_run = 100
thread_safe = False
while True:
    some_data = counter        
    t = Thread(target=processData, args=(some_data, thread_safe))
    t.start()
    counter = counter + 1
    if counter >= max_run:
        break

In your first run if you set thread_safe = False in while loop, mutex will not be used, and threads will step over each others in print method as below;

Not Thread safe

but, if you set thread_safe = True and run it, you will see all the output comes perfectly fine;

Thread safe

hope this helps.

SQL Inner-join with 3 tables?

SELECT table1.col,table2.col,table3.col 
FROM table1 
INNER JOIN 
(table2 INNER JOIN table3 
ON table3.id=table2.id) 
ON table1.id(f-key)=table2.id
AND //add any additional filters HERE

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

If you are sending this back to asp.net and need the data in request.form[] then you'll need to set the content type to "application/x-www-form-urlencoded; charset=utf-8"

Original post here

Secondly get rid of the Datatype, if your not expecting a return the POST will wait for about 4 minutes before failing. See here

Bootstrap 4 - Responsive cards in card-columns

Another late answer, but I was playing with this and came up with a general purpose Sass solution that I found useful and many others might as well. To give an overview, this introduces new classes that can modify the column count of a .card-columns element in very similar ways to columns with .col-4 or .col-lg-3:

@import "bootstrap";

$card-column-counts: 1, 2, 3, 4, 5;

.card-columns {
    @each $column-count in $card-column-counts {
        &.card-columns-#{$column-count} {
            column-count: $column-count;
        }
    }

    @each $breakpoint in map-keys($grid-breakpoints) {
        @include media-breakpoint-up($breakpoint) {
            $infix: breakpoint-infix($breakpoint, $grid-breakpoints);
            @each $column-count in $card-column-counts {
                &.card-columns#{$infix}-#{$column-count} {
                    column-count: $column-count;
                }
            }
        }
    }
}

The end result of this is if you have the following:

<div class="card-columns card-columns-2 card-columns-md-3 card-columns-xl-4">
   ...
</div>

Then you would have 2 columns by default, 3 for medium devices and up and 4 for xl devices and up. Additionally if you change your grid breakpoints this will automatically support those, and the $card-column-counts can be overridden to change the allowed numbers of columns.

Simple two column html layout without using tables

There's now a much simpler solution than when this question was originally asked, five years ago. A CSS Flexbox makes the two column layout originally asked for easy. This is the bare bones equivalent of the table in the original question:

<div style="display: flex">
    <div>AAA</div>
    <div>BBB</div>
</div>

One of the nice things about a Flexbox is that it lets you easily specify how child elements should shrink and grow to adjust to the container size. I will expand on the above example to make the box the full width of the page, make the left column a minimum of 75px wide, and grow the right column to capture the leftover space. I will also pull the style into its own proper block, assign some background colors so that the columns are apparent, and add legacy Flex support for some older browsers.

<style type="text/css">
.flexbox {
    display: -ms-flex;
    display: -webkit-flex;
    display: flex;
    width: 100%;
}

.left {
    background: #a0ffa0;
    min-width: 75px;
    flex-grow: 0;
}

.right {
    background: #a0a0ff;
    flex-grow: 1;
}
</style>

...

<div class="flexbox">
    <div class="left">AAA</div>
    <div class="right">BBB</div>
</div>

Flex is relatively new, and so if you're stuck having to support IE 8 and IE 9 you can't use it. However, as of this writing, http://caniuse.com/#feat=flexbox indicates at least partial support by browsers used by 94.04% of the market.

how to create a window with two buttons that will open a new window

You add your ActionListener twice to button. So correct your code for button2 to

  JButton button2 = new JButton("hello agin2");
  panel.add(button2);
  button2.addActionListener (new Action2());//note the button2 here instead of button

Furthermore, perform your Swing operations on the correct thread by using EventQueue.invokeLater

Gradle - Error Could not find method implementation() for arguments [com.android.support:appcompat-v7:26.0.0]

Your Code

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')

Replace it By

dependencies {
implementation fileTree(include: ['*.jar'], dir: 'libs')

How do I do logging in C# without using 3rd party libraries?

If you are looking for a real simple way to log, you can use this one liner. If the file doesn't exist, it's created.

System.IO.File.AppendAllText(@"c:\log.txt", "mymsg\n");

TypeError: 'float' object is not subscriptable

You are not selecting multiple indexes with PriceList[0][1][2][3][4][5][6] , instead each [] is going into a sub index.

Try this

PizzaChange=float(input("What would you like the new price for all standard pizzas to be? "))      
PriceList[0:7]=[PizzaChange]*7  
PriceList[7:11]=[PizzaChange+3]*4

How to make two plots side-by-side using Python?

Change your subplot settings to:

plt.subplot(1, 2, 1)

...

plt.subplot(1, 2, 2)

The parameters for subplot are: number of rows, number of columns, and which subplot you're currently on. So 1, 2, 1 means "a 1-row, 2-column figure: go to the first subplot." Then 1, 2, 2 means "a 1-row, 2-column figure: go to the second subplot."

You currently are asking for a 2-row, 1-column (that is, one atop the other) layout. You need to ask for a 1-row, 2-column layout instead. When you do, the result will be:

side by side plot

In order to minimize the overlap of subplots, you might want to kick in a:

plt.tight_layout()

before the show. Yielding:

neater side by side plot

Downloading and unzipping a .zip file without writing to disk

Adding on to the other answers using requests:

 # download from web

 import requests
 url = 'http://mlg.ucd.ie/files/datasets/bbc.zip'
 content = requests.get(url)

 # unzip the content
 from io import BytesIO
 from zipfile import ZipFile
 f = ZipFile(BytesIO(content.content))
 print(f.namelist())

 # outputs ['bbc.classes', 'bbc.docs', 'bbc.mtx', 'bbc.terms']

Use help(f) to get more functions details for e.g. extractall() which extracts the contents in zip file which later can be used with with open.

Batch program to to check if process exists

TASKLIST does not set errorlevel.

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"
exit

should do the job, since ":" should appear in TASKLIST output only if the task is NOT found, hence FIND will set the errorlevel to 0 for not found and 1 for found

Nevertheless,

taskkill /f /im "notepad.exe"

will kill a notepad task if it exists - it can do nothing if no notepad task exists, so you don't really need to test - unless there's something else you want to do...like perhaps

echo off
tasklist /fi "imagename eq notepad.exe" |find ":" > nul
if errorlevel 1 taskkill /f /im "notepad.exe"&exit

which would appear to do as you ask - kill the notepad process if it exists, then exit - otherwise continue with the batch

Get sum of MySQL column in PHP

$row['Value'] is probably a string. Try using intval($row['Value']).

Also, make sure you set $sum = 0 before the loop.

Or, better yet, add SUM(Value) AS Val_Sum to your SQL query.

Determine when a ViewPager changes pages

You can also use ViewPager.SimpleOnPageChangeListener instead of ViewPager.OnPageChangeListener and override only those methods you want to use.

viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {

    // optional 
    @Override
    public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { }

    // optional 
    @Override
    public void onPageSelected(int position) { }

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

Hope this help :)

Edit: As per android APIs, setOnPageChangeListener (ViewPager.OnPageChangeListener listener) is deprecated. Please check this url:- Android ViewPager API

Turn off display errors using file "php.ini"

It is not enough in case of PHP fpm. It was one more configuration file which can enable display_error. You should find www.conf. In my case it is in directory /etc/php/7.1/fpm/pool.d/

You should find php_flag[display_errors] = on and disable it, php_flag[display_errors] = off. This should solve the issue.

View the change history of a file using Git versioning

You can use vscode with GitLens, it's a very powerful tool. After installed GitLens, go to GitLens tab, select FILE HISTORY and you can browse it.

enter image description here

What is the equivalent of Java's final in C#?

Java class final and method final -> sealed. Java member variable final -> readonly for runtime constant, const for compile time constant.

No equivalent for Local Variable final and method argument final

Removing black dots from li and ul

Relatable post

Those pesky black dots you are referencing to are called bullets.

They are pretty simple to remove, just add this line to your css:

ul {
    list-style-type: none;
}

Hope this helps

Get page title with Selenium WebDriver using Java

In java you can do some thing like:

if(driver.getTitle().contains("some expected text"))
    //Pass
    System.out.println("Page title contains \"some expected text\" ");
else
    //Fail
    System.out.println("Page title doesn't contains \"some expected text\" ");

Copying PostgreSQL database to another server

Here is an example using pg_basebackup

I chose to go this route because it backs up the entire database cluster (users, databases, etc.).

I'm posting this as a solution on here because it details every step I had to take, feel free to add recommendations or improvements after reading other answers on here and doing some more research.

For Postgres 12 and Ubuntu 18.04 I had to do these actions:


On the server that is currently running the database:

Update pg_hba.conf, for me located at /etc/postgresql/12/main/pg_hba.conf

Add the following line (substitute 192.168.0.100 with the IP address of the server you want to copy the database to).

host  replication  postgres  192.168.0.100/32  trust

Update postgresql.conf, for me located at /etc/postgresql/12/main/postgresql.conf. Add the following line:

listen_addresses = '*'

Restart postgres:

sudo service postgresql restart


On the host you want to copy the database cluster to:

sudo service postgresql stop

sudo su root

rm -rf /var/lib/postgresql/12/main/*

exit

sudo -u postgres pg_basebackup -h 192.168.0.101 -U postgres -D /var/lib/postgresql/12/main/

sudo service postgresql start

Big picture - stop the service, delete everything in the data directory (mine is in /var/lib/postgreql/12). The permissions on this directory are drwx------ with user and group postgres. I could only do this as root, not even with sudo -u postgres. I'm unsure why. Ensure you are doing this on the new server you want to copy the database to! You are deleting the entire database cluster.

Make sure to change the IP address from 192.168.0.101 to the IP address you are copying the database from. Copy the data from the original server with pg_basebackup. Start the service.

Update pg_hba.conf and postgresql.conf to match the original server configuration - before you made any changes adding the replication line and the listen_addresses line (in my care I had to add the ability to log-in locally via md5 to pg_hba.conf).

Note there are considerations for max_wal_senders and wal_level that can be found in the documentation. I did not have to do anything with this.

ASP.NET Identity - HttpContext has no extension method for GetOwinContext

ARGH!

I found it... I didn't have an extra package, called Microsoft.Owin.Host.SystemWeb

Once i searched and installed this, it worked.

Now - i am not sure if i just missed everything, though found NO reference to such a library or package when going through various tutorials. It also didn't get installed when i installed all this Identity framework... Not sure if it were just me..

EDIT Although it's in the Microsoft.Owin.Host.SystemWeb assembly it is an extension method in the System.Web namespace, so you need to have the reference to the former, and be using the latter.

How can I create an array with key value pairs?

You can use this function in your application to add keys to indexed array.

public static function convertIndexedArrayToAssociative($indexedArr, $keys)
{
    $resArr = array();
    foreach ($indexedArr as $item)
    {
        $tmpArr = array();
        foreach ($item as $key=>$value)
        {
            $tmpArr[$keys[$key]] = $value;
        }
        $resArr[] = $tmpArr;
    }
    return $resArr;
}

How to find all trigger associated with a table with SQL Server?

Go through

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

This URL have set of queries by which you can get the list of triggers associated with particular table.

I believe you are working in sqlserver following are the steps to get modify triggers

To modify a trigger

  1. Expand a server group, and then expand a server.

  2. Expand Databases, expand the database in which the table containing the trigger belongs, and then click Tables.

  3. In the details pane, right-click the table on which the trigger exists, point to All Tasks, and then click Manage Triggers.

  4. In Name, select the name of the trigger.

  5. Change the text of the trigger in the Text field as necessary. Press CTRL+TAB to indent the text of a SQL Server Enterprise Manager trigger.

  6. To check the syntax of the trigger, click Check Syntax.

How to create cross-domain request?

Many long (and correct) answers here. But usually you won't do these things manually - at least not when you set up your first projects for development (this is where you usually stumble upon these things). If you use koa for the backend: use koa-cors. Install via npm...

npm install --save koa-cors

...and use it in the code:

const cors = require('koa-cors');
const Koa = require('koa');
const app = new Koa();
app.use(cors());

problem solved.

Adding gif image in an ImageView in android

We can easily add animated gif image on imageview using Ion library.

Tutorial video :: https://www.youtube.com/watch?v=IqKtpdeIpjA

ImageView image = (ImageView)findViewById(R.id.image_gif);
Ion.with(image).load("http://mygifimage.gif");

Using :before CSS pseudo element to add image to modal

1.this is my answer for your problem.

.ModalCarrot::before {
content:'';
background: url('blackCarrot.png'); /*url of image*/
height: 16px; /*height of image*/
width: 33px;  /*width of image*/
position: absolute;
}

Execute jQuery function after another function completes

Deferred promises are a nice way to chain together function execution neatly and easily. Whether AJAX or normal functions, they offer greater flexibility than callbacks, and I've found easier to grasp.

function Typer()
{
var dfd = $.Deferred();
    var srcText = 'EXAMPLE ';
    var i = 0;
    var result = srcText[i];

UPDATE :

////////////////////////////////

  var timer=    setInterval(function() {
                    if(i == srcText.length) {

    // clearInterval(this);


       clearInterval(timer);

////////////////////////////////


   dfd.resolve();
                        };
                        i++;
                        result += srcText[i].replace("\n", "<br />");
                        $("#message").html( result);
                },
                100);
              return dfd.promise();
            }

I've modified the play function so it returns a promise when the audio finishes playing, which might be useful to some. The third function fires when sound finishes playing.

   function playBGM()
    {
      var playsound = $.Deferred();
      $('#bgm')[0].play();
      $("#bgm").on("ended", function() {
         playsound.resolve();
      });
        return playsound.promise();
    }


    function thirdFunction() {
        alert('third function');
    }

Now call the whole thing with the following: (be sure to use Jquery 1.9.1 or above as I found that 1.7.2 executes all the functions at once, rather than waiting for each to resolve.)

Typer().then(playBGM).then(thirdFunction);  

Before today, I had no luck using deferred promises in this way, and finally have grasped it. Precisely timed, chained interface events occurring exactly when we want them to, including async events, has never been easy. For me at least, I now have it under control thanks largely to others asking questions here.

ASP.NET Web API : Correct way to return a 401/unauthorised response

Just return the following:

return Unauthorized();

Git: force user and password prompt

Addition to third answer: If you're using non-english Windows, you can find "Credentials Manager" through "Control panel" > "User Accounts" > "Credentials Manager" Icon of Credentials Manager

Git: How configure KDiff3 as merge tool and diff tool

To amend kris' answer, starting with Git 2.20 (Q4 2018), the proper command for git mergetool will be

git config --global merge.guitool kdiff3 

That is because "git mergetool" learned to take the "--[no-]gui" option, just like "git difftool" does.

See commit c217b93, commit 57ba181, commit 063f2bd (24 Oct 2018) by Denton Liu (Denton-L).
(Merged by Junio C Hamano -- gitster -- in commit 87c15d1, 30 Oct 2018)

mergetool: accept -g/--[no-]gui as arguments

In line with how difftool accepts a -g/--[no-]gui option, make mergetool accept the same option in order to use the merge.guitool variable to find the default mergetool instead of merge.tool.

How do I copy the contents of one ArrayList into another?

Lets try the example

     ArrayList<String> firstArrayList = new ArrayList<>();
            firstArrayList.add("One");
            firstArrayList.add("Two");
            firstArrayList.add("Three");
            firstArrayList.add("Four");
            firstArrayList.add("Five");
            firstArrayList.add("Six");
            //copy array list content into another array list
             ArrayList<String> secondArrayList=new ArrayList<>();
            secondArrayList.addAll(firstArrayList);
            //print all the content of array list
            Iterator itr = secondArrayList.iterator();
            while (itr.hasNext()) {
                System.out.println(itr.next());
            }

In print output as below

One
Two
Three
Four
Five
Six

We can also do by using clone() method for which is used to create exact copy

for that try you can try as like

 **ArrayList<String>secondArrayList = (ArrayList<String>) firstArrayList.clone();**
    And then print by using iterator
      **Iterator itr = secondArrayList.iterator();
                while (itr.hasNext()) {
                    System.out.println(itr.next());
                }**

Import JSON file in React

Simplest approach is following

// Save this as someJson.js
const someJson = {
  name: 'Name',
  age: 20
}

export default someJson

then

import someJson from './someJson'

Nginx location priority

From the HTTP core module docs:

  1. Directives with the "=" prefix that match the query exactly. If found, searching stops.
  2. All remaining directives with conventional strings. If this match used the "^~" prefix, searching stops.
  3. Regular expressions, in the order they are defined in the configuration file.
  4. If #3 yielded a match, that result is used. Otherwise, the match from #2 is used.

Example from the documentation:

location  = / {
  # matches the query / only.
  [ configuration A ] 
}
location  / {
  # matches any query, since all queries begin with /, but regular
  # expressions and any longer conventional blocks will be
  # matched first.
  [ configuration B ] 
}
location /documents/ {
  # matches any query beginning with /documents/ and continues searching,
  # so regular expressions will be checked. This will be matched only if
  # regular expressions don't find a match.
  [ configuration C ] 
}
location ^~ /images/ {
  # matches any query beginning with /images/ and halts searching,
  # so regular expressions will not be checked.
  [ configuration D ] 
}
location ~* \.(gif|jpg|jpeg)$ {
  # matches any request ending in gif, jpg, or jpeg. However, all
  # requests to the /images/ directory will be handled by
  # Configuration D.   
  [ configuration E ] 
}

If it's still confusing, here's a longer explanation.

Pandas Split Dataframe into two Dataframes at a specific row

I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.

import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)

np.split(df, [100,200,300], axis=0] wants explicit index numbers which may or may not be desirable.

How to Truncate a string in PHP to the word closest to a certain number of characters?

I believe this is the easiest way to do it:

$lines = explode('???',wordwrap($string, $length, '???'));
$newstring = $lines[0] . ' &bull; &bull; &bull;';

I'm using the special characters to split the text and cut it.

Placeholder in IE9

I searched on the internet and found a simple jquery code to handle this problem. In my side, it was solved and worked on ie 9.

$("input[placeholder]").each(function () {
        var $this = $(this);
        if($this.val() == ""){
            $this.val($this.attr("placeholder")).focus(function(){
                if($this.val() == $this.attr("placeholder")) {
                    $this.val("");
                }
            }).blur(function(){
                if($this.val() == "") {
                    $this.val($this.attr("placeholder"));
                }
            });
        }
    });

Converting HTML files to PDF

Amyuni WebkitPDF could be used with JNI for a Windows-only solution. This is a HTML to PDF/XAML conversion library, free for commercial and non-commercial use.

If the output files are not needed immediately, for better scalability it may be better to have a queue and a few background processes taking items from there, converting them and storing then on the database or file system.

usual disclaimer applies

Add a properties file to IntelliJ's classpath

I had a similar problem with a log4j.xml file for a unit test, did all of the above. But figured out it was because I was only re-running a failed test....if I re-run the entire test class the correct file is picked up. This is under Intelli-j 9.0.4

How do I lowercase a string in C?

It's in the standard library, and that's the most straight forward way I can see to implement such a function. So yes, just loop through the string and convert each character to lowercase.

Something trivial like this:

#include <ctype.h>

for(int i = 0; str[i]; i++){
  str[i] = tolower(str[i]);
}

or if you prefer one liners, then you can use this one by J.F. Sebastian:

for ( ; *p; ++p) *p = tolower(*p);

pip install failing with: OSError: [Errno 13] Permission denied on directory

User doesn't have write permission for some Python installation paths. You can give the permission by:

sudo chown -R $USER /absolute/path/to/directory

So you should give permission, then try to install it again, if you have new paths you should also give permission:

sudo chown -R $USER /usr/local/lib/python2.7/

Unordered List (<ul>) default indent

If you don't want indention in your list and also don't care about or don't want bullets, there is the CSS-free option of using a "definition list" (HTML 4.01) or "description list" (HTML 5). Use only the non-indenting definition <dt> tags, but not the indenting description <dd> tags, neither of which produces a bullet.

<dl>
  <dt>Item 1</dt>
  <dt>Item 2</dt>
  <dt>Item 3</dt>
</dl>

The output looks like this:

Item 1
Item 2
Item 3

invalid use of incomplete type

The reason is that when instantiating a class template, all its declarations (not the definitions) of its member functions are instantiated too. The class template is instantiated precisely when the full definition of a specialization is required. That is the case when it is used as a base class for example, as in your case.

So what happens is that A<B> is instantiated at

class B : public A<B>

at which point B is not a complete type yet (it is after the closing brace of the class definition). However, A<B>::action's declaration requires B to be complete, because it is crawling in the scope of it:

Subclass::mytype

What you need to do is delaying the instantiation to some point at which B is complete. One way of doing this is to modify the declaration of action to make it a member template.

template<typename T>
void action(T var) {
    (static_cast<Subclass*>(this))->do_action(var);
}

It is still type-safe because if var is not of the right type, passing var to do_action will fail.

How can I read an input string of unknown length?

i also have a solution with standard inputs and outputs

#include<stdio.h>
#include<malloc.h>
int main()
{
    char *str,ch;
    int size=10,len=0;
    str=realloc(NULL,sizeof(char)*size);
    if(!str)return str;
    while(EOF!=scanf("%c",&ch) && ch!="\n")
    {
        str[len++]=ch;
        if(len==size)
        {
            str = realloc(str,sizeof(char)*(size+=10));
            if(!str)return str;
        }
    }
    str[len++]='\0';
    printf("%s\n",str);
    free(str);
}

Handling optional parameters in javascript

I know this is a pretty old question, but I dealt with this recently. Let me know what you think of this solution.

I created a utility that lets me strongly type arguments and let them be optional. You basically wrap your function in a proxy. If you skip an argument, it's undefined. It may get quirky if you have multiple optional arguments with the same type right next to each other. (There are options to pass functions instead of types to do custom argument checks, as well as specifying default values for each parameter.)

This is what the implementation looks like:

function displayOverlay(/*message, timeout, callback*/) {
  return arrangeArgs(arguments, String, Number, Function, 
    function(message, timeout, callback) {
      /* ... your code ... */
    });
};

For clarity, here is what is going on:

function displayOverlay(/*message, timeout, callback*/) {
  //arrangeArgs is the proxy
  return arrangeArgs(
           //first pass in the original arguments
           arguments, 
           //then pass in the type for each argument
           String,  Number,  Function, 
           //lastly, pass in your function and the proxy will do the rest!
           function(message, timeout, callback) {

             //debug output of each argument to verify it's working
             console.log("message", message, "timeout", timeout, "callback", callback);

             /* ... your code ... */

           }
         );
};

You can view the arrangeArgs proxy code in my GitHub repository here:

https://github.com/joelvh/Sysmo.js/blob/master/sysmo.js

Here is the utility function with some comments copied from the repository:

/*
 ****** Overview ******
 * 
 * Strongly type a function's arguments to allow for any arguments to be optional.
 * 
 * Other resources:
 * http://ejohn.org/blog/javascript-method-overloading/
 * 
 ****** Example implementation ******
 * 
 * //all args are optional... will display overlay with default settings
 * var displayOverlay = function() {
 *   return Sysmo.optionalArgs(arguments, 
 *            String, [Number, false, 0], Function, 
 *            function(message, timeout, callback) {
 *              var overlay = new Overlay(message);
 *              overlay.timeout = timeout;
 *              overlay.display({onDisplayed: callback});
 *            });
 * }
 * 
 ****** Example function call ******
 * 
 * //the window.alert() function is the callback, message and timeout are not defined.
 * displayOverlay(alert);
 * 
 * //displays the overlay after 500 miliseconds, then alerts... message is not defined.
 * displayOverlay(500, alert);
 * 
 ****** Setup ******
 * 
 * arguments = the original arguments to the function defined in your javascript API.
 * config = describe the argument type
 *  - Class - specify the type (e.g. String, Number, Function, Array) 
 *  - [Class/function, boolean, default] - pass an array where the first value is a class or a function...
 *                                         The "boolean" indicates if the first value should be treated as a function.
 *                                         The "default" is an optional default value to use instead of undefined.
 * 
 */
arrangeArgs: function (/* arguments, config1 [, config2] , callback */) {
  //config format: [String, false, ''], [Number, false, 0], [Function, false, function(){}]
  //config doesn't need a default value.
  //config can also be classes instead of an array if not required and no default value.

  var configs = Sysmo.makeArray(arguments),
      values = Sysmo.makeArray(configs.shift()),
      callback = configs.pop(),
      args = [],
      done = function() {
        //add the proper number of arguments before adding remaining values
        if (!args.length) {
          args = Array(configs.length);
        }
        //fire callback with args and remaining values concatenated
        return callback.apply(null, args.concat(values));
      };

  //if there are not values to process, just fire callback
  if (!values.length) {
    return done();
  }

  //loop through configs to create more easily readable objects
  for (var i = 0; i < configs.length; i++) {

    var config = configs[i];

    //make sure there's a value
    if (values.length) {

      //type or validator function
      var fn = config[0] || config,
          //if config[1] is true, use fn as validator, 
          //otherwise create a validator from a closure to preserve fn for later use
          validate = (config[1]) ? fn : function(value) {
            return value.constructor === fn;
          };

      //see if arg value matches config
      if (validate(values[0])) {
        args.push(values.shift());
        continue;
      }
    }

    //add a default value if there is no value in the original args
    //or if the type didn't match
    args.push(config[2]);
  }

  return done();
}

Why is JsonRequestBehavior needed?

MVC defaults to DenyGet to protect you against a very specific attack involving JSON requests to improve the liklihood that the implications of allowing HTTP GET exposure are considered in advance of allowing them to occur.

This is opposed to afterwards when it might be too late.

Note: If your action method does not return sensitive data, then it should be safe to allow the get.

Further reading from my Wrox ASP.NET MVC3 book

By default, the ASP.NET MVC framework does not allow you to respond to an HTTP GET request with a JSON payload. If you need to send JSON in response to a GET, you'll need to explicitly allow the behavior by using JsonRequestBehavior.AllowGet as the second parameter to the Json method. However, there is a chance a malicious user can gain access to the JSON payload through a process known as JSON Hijacking. You do not want to return sensitive information using JSON in a GET request. For more details, see Phil's post at http://haacked.com/archive/2009/06/24/json-hijacking.aspx/ or this SO post.

Haack, Phil (2011). Professional ASP.NET MVC 3 (Wrox Programmer to Programmer) (Kindle Locations 6014-6020). Wrox. Kindle Edition.

Related StackOverflow question

With most recents browsers (starting with Firefox 21, Chrome 27, or IE 10), this is no more a vulnerability.

Doctrine findBy 'does not equal'

Based on the answer from Luis, you can do something more like the default findBy method.

First, create a default repository class that is going to be used by all your entities.

/* $config is the entity manager configuration object. */
$config->setDefaultRepositoryClassName( 'MyCompany\Repository' );

Or you can edit this in config.yml

doctrine: orm: default_repository_class: MyCompany\Repository

Then:

<?php

namespace MyCompany;

use Doctrine\ORM\EntityRepository;

class Repository extends EntityRepository {

    public function findByNot( array $criteria, array $orderBy = null, $limit = null, $offset = null )
    {
        $qb = $this->getEntityManager()->createQueryBuilder();
        $expr = $this->getEntityManager()->getExpressionBuilder();

        $qb->select( 'entity' )
            ->from( $this->getEntityName(), 'entity' );

        foreach ( $criteria as $field => $value ) {
            // IF INTEGER neq, IF NOT notLike
            if($this->getEntityManager()->getClassMetadata($this->getEntityName())->getFieldMapping($field)["type"]=="integer") {
                $qb->andWhere( $expr->neq( 'entity.' . $field, $value ) );
            } else {
                $qb->andWhere( $expr->notLike( 'entity.' . $field, $qb->expr()->literal($value) ) );
            }
        }

        if ( $orderBy ) {

            foreach ( $orderBy as $field => $order ) {

                $qb->addOrderBy( 'entity.' . $field, $order );
            }
        }

        if ( $limit )
            $qb->setMaxResults( $limit );

        if ( $offset )
            $qb->setFirstResult( $offset );

        return $qb->getQuery()
            ->getResult();
    }

}

The usage is the same than the findBy method, example:

$entityManager->getRepository( 'MyRepo' )->findByNot(
    array( 'status' => Status::STATUS_DISABLED )
);

Join two sql queries

Here's what worked for me:

select visits, activations, simulations, simulations/activations
   as sims_per_visit, activations/visits*100
   as adoption_rate, simulations/activations*100
   as completion_rate, duration/60
   as minutes, m1 as month, Wk1 as week, Yr1 as year 

from
(
    (select count(*) as visits, year(stamp) as Yr1, week(stamp) as Wk1, month(stamp)
    as m1 from sessions group by week(stamp), year(stamp)) as t3

    join

    (select count(*) as activations, year(stamp) as Yr2, week(stamp) as Wk2,
    month(stamp) as m2 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t4

    join

    (select count(*) as simulations, year(stamp) as Yr3 , week(stamp) as Wk3,
    month(stamp) as m3 from sessions where simulations>'0' group by week(stamp),
    year(stamp)) as t5

    join

    (select avg(duration) as duration, year(stamp) as Yr4 , week(stamp) as Wk4,
    month(stamp) as m4 from sessions where activated='1' group by week(stamp),
    year(stamp)) as t6
)
where Yr1=Yr2 and Wk1=Wk2 and Wk1=Wk3 and Yr1=Yr3 and Yr1=Yr4 and Wk1=Wk4

I used joins, not unions (I needed different columns for each query, a join puts it all in the same column) and I dropped the quotation marks (compared to what Liam was doing) because they were giving me errors.

Thanks! I couldn't have pulled that off without this page! PS: Sorry I don't know how you're getting your statements formatted with colors. etc.

Get MIME type from filename extension

You can use MimeMappings class. I think this is the easiest way. I give import of MimeMappings too. because I felt lots of trouble to find import of those classes.

import org.springframework.boot.web.server.MimeMappings;    
MimeMappings mm=new MimeMappings();
String mimetype = mm.get(fileExtension);
System.out.println(mimetype);

Upload files from Java client to a HTTP server

protected void doPost(HttpServletRequest request,
        HttpServletResponse response) throws ServletException, IOException {

    boolean isMultipart = ServletFileUpload.isMultipartContent(request);

    if (!isMultipart) {
        return;
    }

    DiskFileItemFactory factory = new DiskFileItemFactory();

    factory.setSizeThreshold(MAX_MEMORY_SIZE);

    factory.setRepository(new File(System.getProperty("java.io.tmpdir")));

    String uploadFolder = getServletContext().getRealPath("")
            + File.separator + DATA_DIRECTORY;//DATA_DIRECTORY is directory where you upload this file on the server

    ServletFileUpload upload = new ServletFileUpload(factory);

    upload.setSizeMax(MAX_REQUEST_SIZE);//MAX_REQUEST_SIZE is the size which size you prefer

And use <form enctype="multipart/form-data"> and use <input type="file"> in the html

ASP.NET MVC: No parameterless constructor defined for this object

This error started for me when I added a new way to instantiate a class.

Example:

    public class myClass
    {
         public string id{ get; set; }
         public List<string> myList{get; set;}

         // error happened after I added this
         public myClass(string id, List<string> lst)
         {
             this.id= id;
             this.myList= lst;
         }
     }

The error was resolved when I added when I made this change, adding a parameterless constructor. I believe the compiler creates a parameterless constuctor by default but if you add your own then you must explicitly create it.

    public class myClass
    {
         public string id{ get; set; }
         public List<string> myList{get; set;}

         // error doesn't happen when I add this
         public myClass() { }

         // error happened after I added this, but no longer happens after adding above
         public myClass(string id, List<string> lst)
         {
             this.id= id;
             this.myList= lst;
         }
     }

How do I change a TCP socket to be non-blocking?

The best method for setting a socket as non-blocking in C is to use ioctl. An example where an accepted socket is set to non-blocking is following:

long on = 1L;
unsigned int len;
struct sockaddr_storage remoteAddress;
len = sizeof(remoteAddress);
int socket = accept(listenSocket, (struct sockaddr *)&remoteAddress, &len)
if (ioctl(socket, (int)FIONBIO, (char *)&on))
{
    printf("ioctl FIONBIO call failed\n");
}

Error: Cannot access file bin/Debug/... because it is being used by another process

Worked for me. Task Manager -> Name of project -> End task. (i had 3 same processes with my project name);

VS 2013; Win 8;

Is it possible to use an input value attribute as a CSS selector?

As mentioned before, you need more than a css selector because it doesn't access the stored value of the node, so javascript is definitely needed. Heres another possible solution:

<style>
input:not([value=""]){
border:2px solid red;
}
</style>

<input type="text" onkeyup="this.setAttribute('value', this.value);"/>

Image Greyscale with CSS & re-color on mouse-over?

I use the following code on http://www.diagnomics.com/

Smooth transition from b/w to color with magnifying effect (scale)

    img.color_flip {
      filter: url(filters.svg#grayscale); /* Firefox 3.5+ */
      filter: gray; /* IE5+ */
      -webkit-filter: grayscale(1); /* Webkit Nightlies & Chrome Canary */
      -webkit-transition: all .5s ease-in-out;
    }

    img.color_flip:hover {
      filter: none;
      -webkit-filter: grayscale(0);
      -webkit-transform: scale(1.1);
    }

Generating random, unique values C#

You might try shuffling an array of possible ints if your range is only 0 through 9. This adds the benefit of avoiding any conflicts in the number generation.

var nums = Enumerable.Range(0, 10).ToArray();
var rnd = new Random();

// Shuffle the array
for (int i = 0;i < nums.Length;++i)
{
    int randomIndex = rnd.Next(nums.Length);
    int temp = nums[randomIndex];
    nums[randomIndex] = nums[i];
    nums[i] = temp;
}

// Now your array is randomized and you can simply print them in order
for (int i = 0;i < nums.Length;++i)
    Console.WriteLine(nums[i]);

What does API level mean?

This actually sums it up pretty nicely.

API Levels generally mean that as a programmer, you can communicate with the devices' built in functions and functionality. As the API level increases, functionality adds up (although some of it can get deprecated).

Choosing an API level for an application development should take at least two thing into account:

  1. Current distribution - How many devices can actually support my application, if it was developed for API level 9, it cannot run on API level 8 and below, then "only" around 60% of devices can run it (true to the date this post was made).
  2. Choosing a lower API level may support more devices but gain less functionality for your app. you may also work harder to achieve features you could've easily gained if you chose higher API level.

Android API levels can be divided to five main groups (not scientific, but what the heck):

  1. Android 1.5 - 2.3 (Cupcake to Gingerbread) - (API levels 3-10) - Android made specifically for smartphones.
  2. Android 3.0 - 3.2 (Honeycomb) (API levels 11-13) - Android made for tablets.
  3. Android 4.0 - 4.4 (KitKat) - (API levels 14-19) - A big merge with tons of additional functionality, totally revamped Android version, for both phone and tablets.
  4. Android 5.0 - 5.1 (Lollipop) - (API levels 21-22) - Material Design introduced.
  5. Android 6.0 - 6.… (Marshmallow) - (API levels 23-…) - Runtime Permissions,Apache HTTP Client Removed

SQL Server "cannot perform an aggregate function on an expression containing an aggregate or a subquery", but Sybase can

One option is to put the subquery in a LEFT JOIN:

select sum ( t.graduates ) - t1.summedGraduates 
from table as t
    left join 
     ( 
        select sum ( graduates ) summedGraduates, id
        from table  
        where group_code not in ('total', 'others' )
        group by id 
    ) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates 

Perhaps a better option would be to use SUM with CASE:

select sum(case when group_code = 'total' then graduates end) -
    sum(case when group_code not in ('total','others') then graduates end)
from yourtable

SQL Fiddle Demo with both

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

I encountered the same problem, probably when I uninstalled it and tried to install it again. This happens because of the database file containing login details is still stored in the pc, and the new password will not match the older one. So you can solve this by just uninstalling mysql, and then removing the left over folder from the C: drive (or wherever you must have installed).

Make columns of equal width in <table>

Found this on HTML table: keep the same width for columns

If you set the style table-layout: fixed; on your table, you can override the browser's automatic column resizing. The browser will then set column widths based on the width of cells in the first row of the table. Change your to and remove the inside of it, and then set fixed widths for the cells in .

NuGet Packages are missing

Tiberiu is correct. I had to edit my .csproj file as the files were moved and caused this issue

 <Import Project="..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props" Condition="Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" />

I changed at top of the file and at the bottom

<Error Condition="!Exists('..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.Net.Compilers.1.0.0\build\Microsoft.Net.Compilers.props'))" />
<Error Condition="!Exists('..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props')" Text="$([System.String]::Format('$(ErrorText)', '..\..\packages\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.1.0.1\build\Microsoft.CodeDom.Providers.DotNetCompilerPlatform.props'))" />

How to perform update operations on columns of type JSONB in Postgres 9.4

I wrote small function for myself that works recursively in Postgres 9.4. I had same problem (good they did solve some of this headache in Postgres 9.5). Anyway here is the function (I hope it works well for you):

CREATE OR REPLACE FUNCTION jsonb_update(val1 JSONB,val2 JSONB)
RETURNS JSONB AS $$
DECLARE
    result JSONB;
    v RECORD;
BEGIN
    IF jsonb_typeof(val2) = 'null'
    THEN 
        RETURN val1;
    END IF;

    result = val1;

    FOR v IN SELECT key, value FROM jsonb_each(val2) LOOP

        IF jsonb_typeof(val2->v.key) = 'object'
            THEN
                result = result || jsonb_build_object(v.key, jsonb_update(val1->v.key, val2->v.key));
            ELSE
                result = result || jsonb_build_object(v.key, v.value);
        END IF;
    END LOOP;

    RETURN result;
END;
$$ LANGUAGE plpgsql;

Here is sample use:

select jsonb_update('{"a":{"b":{"c":{"d":5,"dd":6},"cc":1}},"aaa":5}'::jsonb, '{"a":{"b":{"c":{"d":15}}},"aa":9}'::jsonb);
                            jsonb_update                             
---------------------------------------------------------------------
 {"a": {"b": {"c": {"d": 15, "dd": 6}, "cc": 1}}, "aa": 9, "aaa": 5}
(1 row)

As you can see it analyze deep down and update/add values where needed.

How to set a background image in Xcode using swift?

override func viewDidLoad() {

    let backgroundImage = UIImageView(frame: UIScreen.main.bounds)
    backgroundImage.image = UIImage(named: "bg_image")
    backgroundImage.contentMode = UIViewContentMode.scaleAspectfill
    self.view.insertSubview(backgroundImage, at: 0)

}

Updated at 20-May-2020:

The code snippet above doesn't work well after rotating the device. Here is the solution which can make the image stretch according to the screen size(after rotating):

class ViewController: UIViewController {

    var imageView: UIImageView = {
        let imageView = UIImageView(frame: .zero)
        imageView.image = UIImage(named: "bg_image")
        imageView.contentMode = .scaleToFill
        imageView.translatesAutoresizingMaskIntoConstraints = false
        return imageView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()

        view.insertSubview(imageView, at: 0)
        NSLayoutConstraint.activate([
            imageView.topAnchor.constraint(equalTo: view.topAnchor),
            imageView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            imageView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            imageView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
    }
}

Scale the contents of a div by a percentage?

This cross-browser lib seems safer - just zoom and moz-transform won't cover as many browsers as jquery.transform2d's scale().

http://louisremi.github.io/jquery.transform.js/

For example

$('#div').css({ transform: 'scale(.5)' });

Update

OK - I see people are voting this down without an explanation. The other answer here won't work in old Safari (people running Tiger), and it won't work consistently in some older browsers - that is, it does scale things but it does so in a way that's either very pixellated or shifts the position of the element in a way that doesn't match other browsers.

http://www.browsersupport.net/CSS/zoom

Or just look at this question, which this one is likely just a dupe of:

complete styles for cross browser CSS zoom

How do I measure separate CPU core usage for a process?

You can use:

 mpstat -P ALL 1

It shows how much each core is busy and it updates automatically each second. The output would be something like this (on a quad-core processor):

10:54:41 PM  CPU    %usr   %nice    %sys %iowait    %irq   %soft  %steal  %guest   %idle
10:54:42 PM  all    8.20    0.12    0.75    0.00    0.00    0.00    0.00    0.00   90.93
10:54:42 PM    0   24.00    0.00    2.00    0.00    0.00    0.00    0.00    0.00   74.00
10:54:42 PM    1   22.00    0.00    2.00    0.00    0.00    0.00    0.00    0.00   76.00
10:54:42 PM    2    2.02    1.01    0.00    0.00    0.00    0.00    0.00    0.00   96.97
10:54:42 PM    3    2.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   98.00
10:54:42 PM    4   14.15    0.00    1.89    0.00    0.00    0.00    0.00    0.00   83.96
10:54:42 PM    5    1.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00   99.00
10:54:42 PM    6    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00
10:54:42 PM    7    0.00    0.00    0.00    0.00    0.00    0.00    0.00    0.00  100.00

This command doesn't answer original question though i.e. it does not show CPU core usage for a specific process.

SQL Server 2008 can't login with newly created user

If you haven't restarted your SQL database Server after you make login changes, then make sure you do that. Start->Programs->Microsoft SQL Server -> Configuration tools -> SQL Server configuration manager -> Restart Server.

It looks like you only added the user to the server. You need to add them to the database too. Either open the database/Security/User/Add New User or open the server/Security/Logins/Properties/User Mapping.

How to increment a number by 2 in a PHP For Loop

Simple solution

<?php
   $x = 1;
     for($x = 1; $x < 8; $x++) {
        $x = $x + 1;
       echo $x;
     };    
?>

What is the most efficient way to concatenate N arrays?

Here is a function by which you can concatenate multiple number of arrays

function concatNarrays(args) {
    args = Array.prototype.slice.call(arguments);
    var newArr = args.reduce( function(prev, next) {
       return prev.concat(next) ;
    });

    return newArr;
}

Example -

console.log(concatNarrays([1, 2, 3], [5, 2, 1, 4], [2,8,9]));

will output

[1,2,3,5,2,1,4,2,8,9]

How to fix: /usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

If someone has the same issue as I had - make sure that you don't install from the Ubuntu 14.04 repo onto a 12.04 machine - it gives this same error. Reinstalling from the proper repository fixed the issue.

How would I access variables from one class to another?

var1 and var2 is an Instance variables of ClassA. Create an Instance of ClassB and when calling the methodA it will check the methodA in Child class (ClassB) first, If methodA is not present in ClassB you need to invoke the ClassA by using the super() method which will get you all the methods implemented in ClassA. Now, you can access all the methods and attributes of ClassB.

class ClassA(object):
    def __init__(self):
        self.var1 = 1
        self.var2 = 2

    def methodA(self):
        self.var1 = self.var1 + self.var2
        return self.var1


class ClassB(ClassA):
    def __init__(self):
        super().__init__()
        print("var1",self.var1)
        print("var2",self.var2)


object1 = ClassB()
sum = object1.methodA()
print(sum)

How to install a specific version of package using Composer?

I tried to require a development branch from a different repository and not the latest version and I had the same issue and non of the above worked for me :(

after a while I saw in the documentation that in cases of dev branch you need to require with a 'dev-' prefix to the version and the following worked perfectly.

composer require [vendorName]/[packageName]:dev-[gitBranchName]

Sending websocket ping/pong frame from browser

a possible solution in js

In case the WebSocket server initiative disconnects the ws link after a few minutes there no messages sent between the server and client.

  1. client sends a custom ping message, to keep alive by using the keepAlive function

  2. server ignore the ping message and response a custom pong message

var timerID = 0; 
function keepAlive() { 
    var timeout = 20000;  
    if (webSocket.readyState == webSocket.OPEN) {  
        webSocket.send('');  
    }  
    timerId = setTimeout(keepAlive, timeout);  
}  
function cancelKeepAlive() {  
    if (timerId) {  
        clearTimeout(timerId);  
    }  
}

What Content-Type value should I send for my XML sitemap?

The difference between text/xml and application/xml is the default character encoding if the charset parameter is omitted:

Text/xml and application/xml behave differently when the charset parameter is not explicitly specified. If the default charset (i.e., US-ASCII) for text/xml is inconvenient for some reason (e.g., bad web servers), application/xml provides an alternative (see "Optional parameters" of application/xml registration in Section 3.2).

For text/xml:

Conformant with [RFC2046], if a text/xml entity is received with the charset parameter omitted, MIME processors and XML processors MUST use the default charset value of "us-ascii"[ASCII]. In cases where the XML MIME entity is transmitted via HTTP, the default charset value is still "us-ascii".

For application/xml:

If an application/xml entity is received where the charset parameter is omitted, no information is being provided about the charset by the MIME Content-Type header. Conforming XML processors MUST follow the requirements in section 4.3.3 of [XML] that directly address this contingency. However, MIME processors that are not XML processors SHOULD NOT assume a default charset if the charset parameter is omitted from an application/xml entity.

So if the charset parameter is omitted, the character encoding of text/xml is US-ASCII while with application/xml the character encoding can be specified in the document itself.

Now a rule of thumb on the internet is: “Be strict with the output but be tolerant with the input.” That means make sure to meet the standards as much as possible when delivering data over the internet. But build in some mechanisms to overlook faults or to guess when receiving and interpreting data over the internet.

So in your case just pick one of the two types (I recommend application/xml) and make sure to specify the used character encoding properly (I recommend to use the respective default character encoding to play safe, so in case of application/xml use UTF-8 or UTF-16).

How do I set the proxy to be used by the JVM

Recently I've discovered the way to allow JVM to use browser proxy settings. What you need to do is to add ${java.home}/lib/deploy.jar to your project and to init the library like the following:

import com.sun.deploy.net.proxy.DeployProxySelector;
import com.sun.deploy.services.PlatformType;
import com.sun.deploy.services.ServiceManager;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public abstract class ExtendedProxyManager {

    private static final Log logger = LogFactory.getLog(ExtendedProxyManager.class);

    /**
     * After calling this method, proxy settings can be magically retrieved from default browser settings.
     */
    public static boolean init() {
        logger.debug("Init started");

        // Initialization code was taken from com.sun.deploy.ClientContainer:
        ServiceManager
                .setService(System.getProperty("os.name").toLowerCase().indexOf("windows") != -1 ? PlatformType.STANDALONE_TIGER_WIN32
                        : PlatformType.STANDALONE_TIGER_UNIX);

        try {
            // This will call ProxySelector.setDefault():
            DeployProxySelector.reset();
        } catch (Throwable throwable) {
            logger.error("Unable to initialize extended dynamic browser proxy settings support.", throwable);

            return false;
        }

        return true;
    }
}

Afterwards the proxy settings are available to Java API via java.net.ProxySelector.

The only problem with this approach is that you need to start JVM with deploy.jar in bootclasspath e.g. java -Xbootclasspath/a:"%JAVA_HOME%\jre\lib\deploy.jar" -jar my.jar. If somebody knows how to overcome this limitation, let me know.

Selecting a Linux I/O Scheduler

As documented in /usr/src/linux/Documentation/block/switching-sched.txt, the I/O scheduler on any particular block device can be changed at runtime. There may be some latency as the previous scheduler's requests are all flushed before bringing the new scheduler into use, but it can be changed without problems even while the device is under heavy use.

# cat /sys/block/hda/queue/scheduler
noop deadline [cfq]
# echo anticipatory > /sys/block/hda/queue/scheduler
# cat /sys/block/hda/queue/scheduler
noop [deadline] cfq

Ideally, there would be a single scheduler to satisfy all needs. It doesn't seem to exist yet. The kernel often doesn't have enough knowledge to choose the best scheduler for your workload:

  • noop is often the best choice for memory-backed block devices (e.g. ramdisks) and other non-rotational media (flash) where trying to reschedule I/O is a waste of resources
  • deadline is a lightweight scheduler which tries to put a hard limit on latency
  • cfq tries to maintain system-wide fairness of I/O bandwidth

The default was anticipatory for a long time, and it received a lot of tuning, but was removed in 2.6.33 (early 2010). cfq became the default some while ago, as its performance is reasonable and fairness is a good goal for multi-user systems (and even single-user desktops). For some scenarios -- databases are often used as examples, as they tend to already have their own peculiar scheduling and access patterns, and are often the most important service (so who cares about fairness?) -- anticipatory has a long history of being tunable for best performance on these workloads, and deadline very quickly passes all requests through to the underlying device.

Format bytes to kilobytes, megabytes, gigabytes

Here is an option using log10:

<?php

function format_number(float $n): string {
   $n2 = (int)(log10($n) / 3);
   return sprintf('%.3f', $n / 1e3 ** $n2) . ['', ' k', ' M', ' G'][$n2];
}

$s = format_number(9012345678);
var_dump($s == '9.012 G');

https://php.net/function.log10

Get controller and action name from within controller?

Add this to your base controller inside GetDefaults() method

    protected override void OnActionExecuting(ActionExecutingContext filterContext)
    {
         GetDefaults();
         base.OnActionExecuting(filterContext);
    }

    private void GetDefaults()
    {
    var actionName = filterContext.ActionDescriptor.ActionName;
    var controllerName = filterContext.ActionDescriptor.ControllerDescriptor.ControllerName;
    }

Implement your controllers to Basecontroller

Add a partial view _Breadcrumb.cshtml and add it in all required pages with @Html.Partial("_Breadcrumb")

_Breadcrumb.cshtml

<span>
    <a href="../@ViewData["controllerName"]">
        @ViewData["controllerName"]
    </a> > @ViewData["actionName"]
</span>

How to add a class to body tag?

Use:

$(document.body).addClass('about');

SQL Row_Number() function in Where Clause

To get around this issue, wrap your select statement in a CTE, and then you can query against the CTE and use the windowed function's results in the where clause.

WITH MyCte AS 
(
    select   employee_id,
             RowNum = row_number() OVER ( order by employee_id )
    from     V_EMPLOYEE 
    ORDER BY Employee_ID
)
SELECT  employee_id
FROM    MyCte
WHERE   RowNum > 0

Why so red? IntelliJ seems to think every declaration/method cannot be found/resolved

The issue was that the file I was trying to import was so large that IntelliJ wouldn't run any CodeInsights on it.

Setting the idea.max.intellisense.filesize option to a higher value as per the instructions on this answer resolved my issue.

Setting attribute disabled on a SPAN element does not prevent click events

@click=" canClick ? doClick : void 0"

User click but nothing happen can meet your

I use it in vuejs work fine

Any way to select without causing locking in MySQL?

SELECTs do not normally do any locking that you care about on InnoDB tables. The default transaction isolation level means that selects don't lock stuff.

Of course contention still happens.

How to use mysql JOIN without ON condition?

See some example in http://www.sitepoint.com/understanding-sql-joins-mysql-database/

You can use 'USING' instead of 'ON' as in the query

SELECT * FROM table1 LEFT JOIN table2 USING (id);

Insert multiple rows with one query MySQL

$servername = "localhost";

$username = "username";

$password = "password";

$dbname = "myDB";


// Create connection

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection

if ($conn->connect_error) {

die("Connection failed: " . $conn->connect_error);
}

$sql = "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('John', 'Doe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Mary', 'Moe', '[email protected]');";

$sql .= "INSERT INTO MyGuests (firstname, lastname, email)
VALUES ('Julie', 'Dooley', '[email protected]')";


 if ($conn->multi_query($sql) === TRUE) {

  echo "New records created successfully";

 } else {

   echo "Error: " . $sql . "<br>" . $conn->error;

}

$conn->close();

Source W3schools

In Python, how to display current time in readable format

First the quick and dirty way, and second the precise way (recognizing daylight's savings or not).

import time
time.ctime() # 'Mon Oct 18 13:35:29 2010'
time.strftime('%l:%M%p %Z on %b %d, %Y') # ' 1:36PM EDT on Oct 18, 2010'
time.strftime('%l:%M%p %z on %b %d, %Y') # ' 1:36PM EST on Oct 18, 2010'

Creating a UITableView Programmatically

vc.m

#import "ViewController.h"

import "secondViewController.h"

 @interface ViewController ()
 {

NSArray *cityArray;
NSArray *citySubTitleArray;
NSArray *cityImage;
NSInteger selectindexpath;

}
@end

 @implementation ViewController

 - (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

cityArray = [[NSArray 
alloc]initWithObjects:@"Coimbatore",@"Salem",@"Chennai",nil];

citySubTitleArray = [[NSArray alloc]initWithObjects:@"1",@"2",@"3", nil];
cityImage = [[NSArray alloc]initWithObjects:@"12-300x272.png"
 , @"380267_70d232fc33b44d4ebe7b42bbe63ee9be.png",@"apple-logo_318
 -40184.png", nil];

 }


 #pragma mark - UITableView Data Source

 - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
 {
return 1;

 }

 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection 
 :(NSInteger)section
  {
return cityImage.count;
 }

- (UITableViewCell *)tableView:(UITableView *)tableView 
cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellId = @"city";

UITableViewCell *cell =
 [tableView dequeueReusableCellWithIdentifier:cellId];

if (cell == nil)
{
    cell = [[UITableViewCell 
  alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:cellId];
}

cell.textLabel.text = [cityArray objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [citySubTitleArray objectAtIndex:indexPath.row];
cell.imageView.image = [UIImage imageNamed:
 [cityImage objectAtIndex:indexPath.row]];




 //    NSData *data = [[NSData alloc]initWithContentsOfURL:
 [NSURL URLWithString:@""]];

 //    cell.imageView.image = [UIImage imageWithData:data];

return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath
:  (NSIndexPath *)indexPath
 {
 NSLog(@"---- %@",[cityArray objectAtIndex:indexPath.row]);
 NSLog(@"----- %@",[cityImage objectAtIndex:indexPath.row]);
 selectindexpath=indexPath.row;
 [self performSegueWithIdentifier:@"second" sender:self];
  }

  #pragma mark - Navigation

 // In a storyboard-based application, you will often want to do a little p
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 if ([segue.identifier isEqualToString:@"second"])
 {
    secondViewController *object=segue.destinationViewController;
    object.cityName=[cityArray objectAtIndex:selectindexpath];
    object.cityImage=[cityImage objectAtIndex:selectindexpath];
       }
 }


- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
 }

 @end

vc.m

 #import <UIKit/UIKit.h>

 @interface ViewController : UIViewController<UITableViewDataSource
  , UITableViewDelegate>
 @property (strong, nonatomic) IBOutlet UITableView *cityLabelList;

@end

sv.m

 #import <UIKit/UIKit.h>

@interface secondViewController : UIViewController
@property(strong, nonatomic) NSString *cityName;
 @property(strong,nonatomic)NSString *cityImage;
@end

sv.h

#import "secondViewController.h"

 @interface secondViewController ()

 @property (strong, nonatomic) IBOutlet UILabel *lbl_desc;
 @property (strong, nonatomic) IBOutlet UIImageView *img_city;
    @end

 @implementation secondViewController

 - (void)viewDidLoad {
 [super viewDidLoad];
// Do any additional setup after loading the view.
self.title=self.cityName;


if ([self.cityName isEqualToString:@"Coimbatore"])
{


    self.lbl_desc.text=@"Coimbatore city";
    self.img_city.image=[UIImage imageNamed:
    [NSString stringWithFormat:@"%@",self.cityImage]];
}
 else if ([self.cityName isEqualToString:@"Chennai"])
 {

    self.lbl_desc.text= @"Chennai City Gangstar";
    self.img_city.image=[UIImage imageNamed:
   [NSString stringWithFormat:@"%@",self.cityImage]];

   }
  else
   {


    self.lbl_desc.text= @"selam City";
    self.img_city.image=[UIImage imageNamed:
   [NSString stringWithFormat:@"%@",self.cityImage]];

   }
 }

- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

Creating a REST API using PHP

Trying to write a REST API from scratch is not a simple task. There are many issues to factor and you will need to write a lot of code to process requests and data coming from the caller, authentication, retrieval of data and sending back responses.

Your best bet is to use a framework that already has this functionality ready and tested for you.

Some suggestions are:

Phalcon - REST API building - Easy to use all in one framework with huge performance

Apigility - A one size fits all API handling framework by Zend Technologies

Laravel API Building Tutorial

and many more. Simple searches on Bitbucket/Github will give you a lot of resources to start with.

How can I get the current class of a div with jQuery?

<div  id="my_id" class="my_class"></div>

if that is the first div then address it like so:

document.write("div CSS class: " + document.getElementsByTagName('div')[0].className);

alternatively do this:

document.write("alternative way: " + document.getElementById('my_id').className);

It yields the following results:

div CSS class: my_class
alternative way: my_class

What is the difference between bool and Boolean types in C#

Note that Boolean will only work were you have using System; (which is usually, but not necessarily, included) (unless you write it out as System.Boolean). bool does not need using System;

How to convert CSV to JSON in Node.js

Node-ETL package is enough for all BI processing.

npm install node-etl; 

Then :

var ETL=require('node-etl');
var output=ETL.extract('./data.csv',{
              headers:["a","b","c","d"],
              ignore:(line,index)=>index!==0, //ignore first line
 });

Android WSDL/SOAP service client

private static  final  String NAMESPACE = "http://tempuri.org/";
private static  final String URL = "http://example.com/CRM/Service.svc";
private static  final  String SOAP_ACTION = "http://tempuri.org/Login";
private static  final String METHOD_NAME = "Login";


//calling web services method

String loginresult=callService(username,password,usertype);


//calling webservices
String callService(String a1,String b1,Integer c1) throws Exception {

            Boolean flag=true;
            do
            {
                try{
                    System.out.println(flag);

                SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);

                PropertyInfo pa1 = new PropertyInfo();
                pa1.setName("Username");
                pa1.setValue(a1.toString());

                PropertyInfo pb1 = new PropertyInfo();
                pb1.setName("Password");
                pb1.setValue(b1.toString());

                PropertyInfo pc1 = new PropertyInfo();
                pc1.setName("UserType");
                pc1.setValue(c1);
                System.out.println(c1+"this is integer****s");




                System.out.println("new");
                request.addProperty(pa1);
                request.addProperty(pb1);
                request.addProperty(pc1);



                System.out.println("new2");
                SoapSerializationEnvelope envelope = new    SoapSerializationEnvelope(SoapEnvelope.VER11);
                envelope.dotNet = true;
                System.out.println("new3");
                envelope.setOutputSoapObject(request);
                HttpTransportSE androidHttpTransport = new HttpTransportSE(URL);
                androidHttpTransport.setXmlVersionTag("<?xml version=\"1.0\" encoding=\"utf-8\"?>");
                System.out.println("new4");
                try{
                androidHttpTransport.call(SOAP_ACTION, envelope);
                }
                catch(Exception e)
                {

                    System.out.println(e+"   this is exception");
                }
                System.out.println("new5");
                SoapObject response = (SoapObject)envelope.bodyIn;

                result = response.getProperty(0).toString(); 

                flag=false;
                System.out.println(flag);
                }catch (Exception e) {
                // TODO: handle exception
                    flag=false;
            }
            }
            while(flag);
            return result;

        }  
///

How do I enable saving of filled-in fields on a PDF form?

You can use the free foxit reader to fill in the forms, and if you pay a little you can design the forms that way you want.

You can also us iText to programmaticly create those forms.

There are free online services that allow you to upload a pdf and you can add fields also.

It depends on how you want to do the designing.

EDIT: If you use foxit reader, you can save any form that is fillable.

Difference between application/x-javascript and text/javascript content types

According to RFC 4329 the correct MIME type for JavaScript should be application/javascript. Howerver, older IE versions choke on this since they expect text/javascript.

MSSQL Regular expression

As above the question was originally about MySQL

Use REGEXP, not LIKE:

SELECT * FROM `table` WHERE ([url] NOT REGEXP '^[-A-Za-z0-9/.]+$')

How to check if a String contains any of some strings

var values = new [] {"abc", "def", "ghj"};
var str = "abcedasdkljre";
values.Any(str.Contains);

How to reshape data from long to wide format

much easier way!

devtools::install_github("yikeshu0611/onetree") #install onetree package

library(onetree)
widedata=reshape_toWide(data = dat1,id = "name",j = "numbers",value.var.prefix = "value")
widedata

        name     value1     value2     value3     value4
   firstName  0.3407997 -0.7033403 -0.3795377 -0.7460474
  secondName -0.8981073 -0.3347941 -0.5013782 -0.1745357

if you want to go back from wide to long, only change Wide to Long, and no changes in objects.

reshape_toLong(data = widedata,id = "name",j = "numbers",value.var.prefix = "value")

        name numbers      value
   firstName       1  0.3407997
  secondName       1 -0.8981073
   firstName       2 -0.7033403
  secondName       2 -0.3347941
   firstName       3 -0.3795377
  secondName       3 -0.5013782
   firstName       4 -0.7460474
  secondName       4 -0.1745357

How to make a Java Generic method static?

You need to move type parameter to the method level to indicate that you have a generic method rather than generic class:

public class ArrayUtils {
    public static <T> E[] appendToArray(E[] array, E item) {
        E[] result = (E[])new Object[array.length+1];
        result[array.length] = item;
        return result;
    }
}

How do you completely remove the button border in wpf?

Why don't you set both Background & BorderBrush by same brush

 <Style TargetType="{x:Type Button}" >
        <Setter Property="Background" Value="{StaticResource marginBackGround}"></Setter>
        <Setter Property="BorderBrush" Value="{StaticResource marginBackGround}"></Setter>            
 </Style>

<LinearGradientBrush  x:Key="marginBackGround" EndPoint=".5,1" StartPoint="0.5,0">
    <GradientStop Color="#EE82EE" Offset="0"/>
    <GradientStop Color="#7B30B6" Offset="0.5"/>
    <GradientStop Color="#510088" Offset="0.5"/>
    <GradientStop Color="#76209B" Offset="0.9"/>
    <GradientStop Color="#C750B9" Offset="1"/>
</LinearGradientBrush>

How can I return the difference between two lists?

With Stream API you can do something like this:

List<String> aWithoutB = a.stream()
    .filter(element -> !b.contains(element))
    .collect(Collectors.toList());

List<String> bWithoutA = b.stream()
    .filter(element -> !a.contains(element))
    .collect(Collectors.toList());

Python: Number of rows affected by cursor.execute("SELECT ...)

To get the number of selected rows I usually use the following:

cursor.execute(sql)
count = (len(cursor.fetchall))

What does "Changes not staged for commit" mean

You may see this error when you have added a new file to your code and you're now trying to commit the code without staging(adding) it.

To overcome this, you may first add the file by using git add (git add your_file_name.py) and then committing the changes (git commit -m "Rename Files" -m "Sample script to rename files as you like")

How can I tell AngularJS to "refresh"

Use

$route.reload();

remember to inject $route to your controller.

Javascript string/integer comparisons

Comparing Numbers to String Equivalents Without Using parseInt

console.log(Number('2') > Number('10'));
console.log( ('2'/1) > ('10'/1) );

var item = { id: 998 }, id = '998';
var isEqual = (item.id.toString() === id.toString());
isEqual;

How to add an extra row to a pandas dataframe

Try this:

df.loc[len(df)]=['8/19/2014','Jun','Fly','98765'] 

Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.

Overflow-x:hidden doesn't prevent content from overflowing in mobile browsers

No previous single solution worked for me, I had to mix them and got the issue fixed also on older devices (iphone 3).

First, I had to wrap the html content into an outer div:

<html>
  <body>
    <div id="wrapper">... old html goes here ...</div>
  </body>
</html>

Then I had to apply overflow hidden to the wrapper, because overflow-x was not working:

  #wrapper {
    overflow: hidden;
  }

and this fixed the issue.

How to save .xlsx data to file as a blob

I had the same problem as you. It turns out you need to convert the Excel data file to an ArrayBuffer.

var blob = new Blob([s2ab(atob(data))], {
    type: ''
});

href = URL.createObjectURL(blob);

The s2ab (string to array buffer) method (which I got from https://github.com/SheetJS/js-xlsx/blob/master/README.md) is:

function s2ab(s) {
  var buf = new ArrayBuffer(s.length);
  var view = new Uint8Array(buf);
  for (var i=0; i!=s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
  return buf;
}

Can pandas automatically recognize dates?

pandas read_csv method is great for parsing dates. Complete documentation at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.io.parsers.read_csv.html

you can even have the different date parts in different columns and pass the parameter:

parse_dates : boolean, list of ints or names, list of lists, or dict
If True -> try parsing the index. If [1, 2, 3] -> try parsing columns 1, 2, 3 each as a
separate date column. If [[1, 3]] -> combine columns 1 and 3 and parse as a single date
column. {‘foo’ : [1, 3]} -> parse columns 1, 3 as date and call result ‘foo’

The default sensing of dates works great, but it seems to be biased towards north american Date formats. If you live elsewhere you might occasionally be caught by the results. As far as I can remember 1/6/2000 means 6 January in the USA as opposed to 1 Jun where I live. It is smart enough to swing them around if dates like 23/6/2000 are used. Probably safer to stay with YYYYMMDD variations of date though. Apologies to pandas developers,here but i have not tested it with local dates recently.

you can use the date_parser parameter to pass a function to convert your format.

date_parser : function
Function to use for converting a sequence of string columns to an array of datetime
instances. The default uses dateutil.parser.parser to do the conversion.

Obtain smallest value from array in Javascript?

var array =[2,3,1,9,8];
var minvalue = array[0]; 
for (var i = 0; i < array.length; i++) {
    if(array[i]<minvalue)
    {
        minvalue = array[i];
    }

}
  console.log(minvalue);

make: *** [ ] Error 1 error

I got the same thing. Running "make" and it fails with just this message.

% make
make: *** [all] Error 1

This was caused by a command in a rule terminates with non-zero exit status. E.g. imagine the following (stupid) Makefile:

all:
       @false
       echo "hello"

This would fail (without printing "hello") with the above message since false terminates with exit status 1.

In my case, I was trying to be clever and make a backup of a file before processing it (so that I could compare the newly generated file with my previous one). I did this by having a in my Make rule that looked like this:

@[ -e $@ ] && mv $@ [email protected]

...not realizing that if the target file does not exist, then the above construction will exit (without running the mv command) with exit status 1, and thus any subsequent commands in that rule failed to run. Rewriting my faulty line to:

@if [ -e $@ ]; then mv $@ [email protected]; fi

Solved my problem.

Getting unique values in Excel by using formulas only

Resorting to a PivotTable might not count as using formulas only but seems more practical that most other suggestions so far:

SO1429899 example

Convert LocalDateTime to LocalDateTime in UTC

I personally prefer

LocalDateTime.now(ZoneOffset.UTC);

as it is the most readable option.

Can I add an image to an ASP.NET button?

You can add image to asp.net button. you dont need to use only image button or link button. When displaying button on browser, it is converting to html button as default. So you can use its "Style" properties for adding image. My example is below. I hope it works for you.

Style="background-image:url('Image/1.png');"

You can change image location with using

background-repeat

properties. So you can write a button like below:

<asp:Button ID="btnLogin" runat="server" Text="Login" Style="background-image:url('Image/1.png'); background-repeat:no-repeat"/>

Getting all files in directory with ajax

Javascript which runs on the client machine can't access the local disk file system due to security restrictions.

If you want to access the client's disk file system then look into an embedded client application which you serve up from your webpage, like an Applet, Silverlight or something like that. If you like to access the server's disk file system, then look for the solution in the server side corner using a server side programming language like Java, PHP, etc, whatever your webserver is currently using/supporting.

Loop through each cell in a range of cells when given a Range object

To make a note on Dick's answer, this is correct, but I would not recommend using a For Each loop. For Each creates a temporary reference to the COM Cell behind the scenes that you do not have access to (that you would need in order to dispose of it).

See the following for more discussion:

How do I properly clean up Excel interop objects?

To illustrate the issue, try the For Each example, close your application, and look at Task Manager. You should see that an instance of Excel is still running (because all objects were not disposed of properly).

A cleaner way to handle this is to query the spreadsheet using ADO:

http://technet.microsoft.com/en-us/library/ee692882.aspx

How do I add python3 kernel to jupyter (IPython)

open terminal(or cmd for window), then run following commands: (On window, drop "source" in the second line.)

conda create -n py35 python=3.5
source activate py35
conda install notebook ipykernel
ipython kernel install --user --name=python3.5

I tried some method but It doesnt work, then I found this way. It worked with me. Hoping it can help.

Pass multiple parameters to rest API - Spring

Multiple parameters can be given like below,

    @RequestMapping(value = "/mno/{objectKey}", method = RequestMethod.GET, produces = "application/json")
    public List<String> getBook(HttpServletRequest httpServletRequest, @PathVariable(name = "objectKey") String objectKey
      , @RequestParam(value = "id", defaultValue = "false")String id,@RequestParam(value = "name", defaultValue = "false") String name) throws Exception {
               //logic
}

How to install latest version of git on CentOS 7.x/6.x

It can be very confusing, and dangerous, to replace the upstream base repositories with add-on repositories without considerable testing and thought. RPMforge, in particularly, is effectively moribund and is not getting updates.

I personally publish tools for building git 2.4, wrapped as an alternatively named "git24" package, at https://github.com/nkadel/git24-srpm/. Feel free to access and fork those if you want packages distinguished from the standard system packages, much as "samba" and "samba4" packages are differentiated.

WCFTestClient The HTTP request is unauthorized with client authentication scheme 'Anonymous'

Another possible solution to this error that I found. Might not have answered OP's exact question but may help others who stumble across this error message.

I was creating my Client in code using WebHttpBinding, in order to replicate the following line:

<security mode="TransportCredentialOnly">
  <transport clientCredentialType="Windows" proxyCredentialType="Windows" />
</security>

I had to do:

var binding = new WebHttpBinding(WebHttpSecurityMode.TransportCredentialOnly);
                binding.Security.Transport.ClientCredentialType = HttpClientCredentialType.Windows;
                binding.Security.Transport.ProxyCredentialType = HttpProxyCredentialType.Windows;

as well as setting proxy.ClientCredentials.Windows.AllowedImpersonationLevel = System.Security.Principal.TokenImpersonationLevel.Impersonation;

Java collections convert a string to a list of characters

The lack of a good way to convert between a primitive array and a collection of its corresponding wrapper type is solved by some third party libraries. Guava, a very common one, has a convenience method to do the conversion:

List<Character> characterList = Chars.asList("abc".toCharArray());
Set<Character> characterSet = new HashSet<Character>(characterList);

How to use a TRIM function in SQL Server

You are missing two closing parentheses...and I am not sure an ampersand works as a string concatenation operator. Try '+'

SELECT dbo.COL_V_Cost_GEMS_Detail.TNG_SYS_NR AS [EHP Code], 
dbo.COL_TBL_VCOURSE.TNG_NA AS [Course Title], 
LTRIM(RTRIM(FCT_TYP_CD)) + ') AND (' + LTRIM(RTRIM(DEP_TYP_ID)) + ')' AS [Course Owner]

Call PHP function from Twig template

I am surprised the code answer is not posted already, it's a one liner.

You could just {{ categeory_id | getVariations }}

It's a one-liner:

$twig->addFilter('getVariations', new Twig_Filter_Function('getVariations'));

Can Twitter Bootstrap alerts fade in as well as out?

I don't agree with the way that Bootstrap uses fade in (as seen in their documentation - http://v4-alpha.getbootstrap.com/components/alerts/), and my suggestion is to avoid the class names fade and in, and to avoid that pattern in general (which is currently seen in the top-rated answer to this question).

(1) The semantics are wrong - transitions are temporary, but the class names live on. So why should we name our classes fade and fade in? It should be faded and faded-in, so that when developers read the markup, it's clear that those elements were faded or faded-in. The Bootstrap team has already done away with hide for hidden, why is fade any different?

(2) Using 2 classes fade and in for a single transition pollutes the class space. And, it's not clear that fade and in are associated with one another. The in class looks like a completely independent class, like alert and alert-success.

The best solution is to use faded when the element has been faded out, and to replace that class with faded-in when the element has been faded in.

Alert Faded

So to answer the question. I think the alert markup, style, and logic should be written in the following manner. Note: Feel free to replace the jQuery logic, if you're using vanilla javascript.

HTML

<div id="saveAlert" class="alert alert-success">
  <a class="close" href="#">×</a>
  <p><strong>Well done!</strong> You successfully read this alert message.</p>
</div>

CSS

.faded {
  opacity: 0;
  transition: opacity 1s;
}

JQuery

$('#saveAlert .close').on('click', function () {

  $("#saveAlert")
    .addClass('faded');

});

Configuring IntelliJ IDEA for unit testing with JUnit

In my case (IntelliJ 2020-02, Kotlin dev) JUnit library was already included by Create project wizard. I needed to enable JUnit plugin:

IntelliJ JUnit plugin

to get green Run test icons next to each test class and method:

enter image description here

and CTRL+Shift+R will run test under caret, and CTRL+shift+D to debug.

Make the console wait for a user input to close

public static void main(String args[])
{
    Scanner s = new Scanner(System.in);

    System.out.println("Press enter to continue.....");

    s.nextLine();   
}

This nextline is a pretty good option as it will help us run next line whenever the enter key is pressed.

How to vertically align into the center of the content of a div with defined width/height?

I found this solution in this article

.parent-element {
  -webkit-transform-style: preserve-3d;
  -moz-transform-style: preserve-3d;
  transform-style: preserve-3d;
}

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

It work like a charm if the height of element is not fixed.

How to Compare two strings using a if in a stored procedure in sql server 2008?

declare @temp as varchar
  set @temp='Measure'
  if(@temp = 'Measure')
Select Measure from Measuretable
else
Select OtherMeasure from Measuretable

How to get an isoformat datetime string including the default timezone?

To get the current time in UTC in Python 3.2+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).isoformat()
'2015-01-27T05:57:31.399861+00:00'

To get local time in Python 3.3+:

>>> from datetime import datetime, timezone
>>> datetime.now(timezone.utc).astimezone().isoformat()
'2015-01-27T06:59:17.125448+01:00'

Explanation: datetime.now(timezone.utc) produces a timezone aware datetime object in UTC time. astimezone() then changes the timezone of the datetime object, to the system's locale timezone if called with no arguments. Timezone aware datetime objects then produce the correct ISO format automatically.

WebView link click open default browser

I had to do the same thing today and I have found a very useful answer on StackOverflow that I want to share here in case someone else needs it.

Source (from sven)

webView.setWebViewClient(new WebViewClient(){
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        if (url != null && (url.startsWith("http://") || url.startsWith("https://"))) {
            view.getContext().startActivity(
                new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
            return true;
        } else {
            return false;
        }
    }
});

How to add multiple columns to pandas dataframe in one assignment?

if adding a lot of missing columns (a, b, c ,....) with the same value, here 0, i did this:

    new_cols = ["a", "b", "c" ] 
    df[new_cols] = pd.DataFrame([[0] * len(new_cols)], index=df.index)

It's based on the second variant of the accepted answer.

How can I get the corresponding table header (th) from a table cell (td)?

That's simple, if you reference them by index. If you want to hide the first column, you would:

Copy code

$('#thetable tr').find('td:nth-child(1),th:nth-child(1)').toggle();

The reason I first selected all table rows and then both td's and th's that were the n'th child is so that we wouldn't have to select the table and all table rows twice. This improves script execution speed. Keep in mind, nth-child() is 1 based, not 0.

How to get IP address of the device from code?

This is the easiest and simple way ever exist on the internet... First of all, add this permission to your manifest file...

  1. "INTERNET"

  2. "ACCESS_NETWORK_STATE"

add this in onCreate file of Activity..

    getPublicIP();

Now Add this function to your MainActivity.class.

_x000D_
_x000D_
    private void getPublicIP() {_x000D_
ArrayList<String> urls=new ArrayList<String>(); //to read each line_x000D_
_x000D_
        new Thread(new Runnable(){_x000D_
            public void run(){_x000D_
                //TextView t; //to show the result, please declare and find it inside onCreate()_x000D_
_x000D_
                try {_x000D_
                    // Create a URL for the desired page_x000D_
                    URL url = new URL("https://api.ipify.org/"); //My text file location_x000D_
                    //First open the connection_x000D_
                    HttpURLConnection conn=(HttpURLConnection) url.openConnection();_x000D_
                    conn.setConnectTimeout(60000); // timing out in a minute_x000D_
_x000D_
                    BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));_x000D_
_x000D_
                    //t=(TextView)findViewById(R.id.TextView1); // ideally do this in onCreate()_x000D_
                    String str;_x000D_
                    while ((str = in.readLine()) != null) {_x000D_
                        urls.add(str);_x000D_
                    }_x000D_
                    in.close();_x000D_
                } catch (Exception e) {_x000D_
                    Log.d("MyTag",e.toString());_x000D_
                }_x000D_
_x000D_
                //since we are in background thread, to post results we have to go back to ui thread. do the following for that_x000D_
_x000D_
                PermissionsActivity.this.runOnUiThread(new Runnable(){_x000D_
                    public void run(){_x000D_
                        try {_x000D_
                            Toast.makeText(PermissionsActivity.this, "Public IP:"+urls.get(0), Toast.LENGTH_SHORT).show();_x000D_
                        }_x000D_
                        catch (Exception e){_x000D_
                            Toast.makeText(PermissionsActivity.this, "TurnOn wiffi to get public ip", Toast.LENGTH_SHORT).show();_x000D_
                        }_x000D_
                    }_x000D_
                });_x000D_
_x000D_
            }_x000D_
        }).start();_x000D_
_x000D_
    }
_x000D_
_x000D_
_x000D_

Internet Access in Ubuntu on VirtualBox

How did you configure networking when you created the guest? The easiest way is to set the network adapter to NAT, if you don't need to access the vm from another pc.

Android studio logcat nothing to show

When everything else didn't work, here's what I did. Since adb logcat worked nicely, I decided to rely on it. Running adb logcat -v color in the Android Studio's embedded terminal produced outputs similar to the normal logcat, and allowed code links to work too:

Running adb logcat -v color in the embedded console

But this came with a few issues:

  • You can't specify a package to watch. Using the --pid=<your PID> option, you can watch the output of a single process. But since every time you restart your app the PID changes, you have re-run this command with every restart.
  • The colors are annoying (in my opinion).
  • The output fields are not aligned with previous messages, the whole thing is not well formatted which makes following the logcat much harder than it should be (the same happens with the embedded logcat, though).

So I decided to make my own tool to automatically watch my package PID(s) and prettify the logcat output:

import java.awt.AWTException;
import java.io.*;
import java.util.ArrayList;
import java.awt.Robot;
import java.awt.event.KeyEvent;

public class Logcat {

    private static final String ADB_FILE_PATH = "adb";

    // Customizations,
    private static final Color     V_COLOR = Color.RESET;
    private static final Color     D_COLOR = Color.RESET;
    private static final Color     I_COLOR = Color.RESET;
    private static final Color     W_COLOR = Color.BLUE;
    private static final Color     E_COLOR = Color.RED_BRIGHT;
    private static final Color  HINT_COLOR = Color.MAGENTA_BOLD_BRIGHT;
    private static final Color OTHER_COLOR = Color.GREEN_BOLD_BRIGHT;

    private static final int       DATE_LENGTH =   5;
    private static final int       TIME_LENGTH =  12;
    private static final int PROCESS_ID_LENGTH =   5;
    private static final int  THREAD_ID_LENGTH =   5;
    private static final int  LOG_LEVEL_LENGTH =   1;
    private static final int        TAG_LENGTH =  20;
    private static final int    MESSAGE_LENGTH = 110;

    private static final String SEPARATOR = " | ";
    private static final String CONTINUATION = "?";
    private static final String INDENTATION = "  ";

    private static final int PROCESS_IDS_UPDATE_INTERVAL_MILLIS = 1224;

    private static final int HISTORY_LENGTH = 1000;

    // State,
    private static boolean skipProcessIDCheck;
    private static ArrayList<String> processIDs = new ArrayList<String>();

    private static String logLevelToShow="V";  // All.

    private static Process logcatProcess;
    private static boolean appClosed;
    private static boolean stopEverything;

    private static String[] history = new String[HISTORY_LENGTH];
    private static int currentLocationInHistory, historyLength;

    public static void main(final String args[]) {

        clearAndroidStudioConsole();
        System.out.println("besm Allah");

        // Get processes ids of the provided package,
        if (args.length==0) {
            skipProcessIDCheck = true;
        } else {
            skipProcessIDCheck = false;
            getProcessIDs    (args[0]);    // Do it once before we start.
            monitorProcessIDs(args[0]);    // Do it periodically from now on.
        }

        // Start capturing and prettifying logcat,
        if (!monitorLogcat()) {
            stopEverything = true;
            return;
        }

        // Handle user input,
        handleUserInput();
    }

    private static void watch(final Process process, final ProcessListener listener) {

        // Read process standard output and send it to the listener line by line,
        new Thread() {
            public void run() {
                BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
                String line = "";
                try {
                    do {
                        if (bufferedReader.ready()) {
                            line = bufferedReader.readLine();
                            if (line!=null && !line.isEmpty()) listener.onNewLine(line);
                        } else {
                            Thread.sleep(100);
                        }
                    } while (line!=null && !stopEverything);
                } catch (Exception e) { e.printStackTrace(); }
            }
        }.start();
    }

    private static void monitorProcessIDs(String packageName) {

        // Continuously monitor the process IDs of this package and update when changed,
        new Thread() {
            public void run() {
                do {
                    try { Thread.sleep(PROCESS_IDS_UPDATE_INTERVAL_MILLIS); } catch (InterruptedException e) {}
                    getProcessIDs(packageName);
                } while (!stopEverything);
            }
        }.start();
    }

    private static void getProcessIDs(String packageName) {

        // Get the process IDs associated with this package once,
        ArrayList<String> newProcessIDs = new ArrayList<String>();
        Runtime runtime = Runtime.getRuntime();
        try {
            Process getPIDProcess = runtime.exec(ADB_FILE_PATH + " shell ps");
            watch(getPIDProcess, (line) -> {
                if (line.contains(packageName)) {
                    newProcessIDs.add(removeRedundantSpaces(line).split(" ")[1]);
                }
            });
            getPIDProcess.waitFor();
            Thread.sleep(500);  // Make sure we've already handled all the input from the process.
        } catch (Exception e) { e.printStackTrace(); }

        // Return immediately if program is closed,
        if (stopEverything) return ;

        // Some action upon getting the pid(s),
        boolean shouldRepeatHistory = false;
        if (newProcessIDs.isEmpty()) {

            // Just closed,
            if (!appClosed) {
                appClosed = true;
                prettify("----- App closed -----");
            }
        } else if (appClosed) {

            // Just opened, clear,
            appClosed = false;
            clearAndroidStudioConsole();
            prettify("----- App opened -----");
            shouldRepeatHistory = true;
        } else {

            // Detect changes in processes,
            for (String pid : newProcessIDs) {
                if (!processIDs.contains(pid)) {
                    clearAndroidStudioConsole();
                    prettify("----- Process(es) changed (or app restarted - some logs could have been missed) -----");
                    shouldRepeatHistory = true;
                    break ;
                }
            }
        }

        // Set the new PID(s),
        processIDs = newProcessIDs;
        if (shouldRepeatHistory) repeatHistory();
    }

    private static boolean monitorLogcat() {

        Runtime runtime = Runtime.getRuntime();
        try {
            logcatProcess = runtime.exec(ADB_FILE_PATH + " logcat -v threadtime");
            watch(logcatProcess, (line) -> {

                // Learn history, in case we need to repeat it,
                if (appClosed || processLogcatLine(line)) {
                    history[currentLocationInHistory] = line;
                    currentLocationInHistory = (currentLocationInHistory + 1) % history.length;
                    if (historyLength<history.length) historyLength++;
                }
            });
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }

    private static boolean processLogcatLine(String line) {
        try {
            return prettify(line);
        } catch (Exception e) {
            print(line, OTHER_COLOR);
            System.out.println();

            // Debug,
            e.printStackTrace();
            return true;
        }
    }

    // Returns true if line should be kept in history,
    private static synchronized boolean prettify(String line) {

        if (line.startsWith("-")) {
            // It's a "beginning of <something>" line,
            print(line, HINT_COLOR);
            System.out.println();
            return true;
        }

        // Get the individual fields,
        String      date = line.substring(0, line.indexOf(' ')); line = line.substring(line.indexOf(' ')+1); line = line.trim();
        String      time = line.substring(0, line.indexOf(' ')); line = line.substring(line.indexOf(' ')+1); line = line.trim();
        String processID = line.substring(0, line.indexOf(' ')); line = line.substring(line.indexOf(' ')+1); line = line.trim();

        // Break early if possible,
        if (!skipProcessIDCheck && !processIDs.contains(processID.trim())) return false;

        // Continue parsing,
        String  threadID = line.substring(0, line.indexOf(' ')); line = line.substring(line.indexOf(' ')+1); line = line.trim();
        String  logLevel = line.substring(0, line.indexOf(' ')); line = line.substring(line.indexOf(' ')+1); line = line.trim();

        // Break early if possible,
        switch (logLevel) {
            case "V": if (!"V"    .contains(logLevelToShow)) return true; break;
            case "D": if (!"VD"   .contains(logLevelToShow)) return true; break;
            case "I": if (!"VDI"  .contains(logLevelToShow)) return true; break;
            case "W": if (!"VDIW" .contains(logLevelToShow)) return true; break;
            case "E": if (!"VDIWE".contains(logLevelToShow)) return true; break;
        }

        // Continue parsing,
        String       tag = line.substring(0, line.indexOf(':')); line = line.substring(line.indexOf(':')+1); line = line.trim();

        // Because some tags have a trailing ":",
        if (line.startsWith(":")) {
            tag += ":";
            line = line.substring(1);
        }

        // Indent lines starting by "at",
        String indentation = "";
        if (line.startsWith("at ")) {
            indentation = "   " + INDENTATION;
            line = " " + INDENTATION + line;
        }

        // Print the prettified log,
        Color color;
        switch (logLevel) {
            case "V": color = V_COLOR; break;
            case "D": color = D_COLOR; break;
            case "I": color = I_COLOR; break;
            case "W": color = W_COLOR; break;
            case "E": color = E_COLOR; break;
            default:
                color = Color.RESET;
        }

        String fields = adjustLength(     date,       DATE_LENGTH) + SEPARATOR +
                        adjustLength(     time,       TIME_LENGTH) + SEPARATOR +
                        adjustLength(processID, PROCESS_ID_LENGTH) + SEPARATOR +
                        adjustLength( threadID,  THREAD_ID_LENGTH) + SEPARATOR +
                        adjustLength( logLevel,  LOG_LEVEL_LENGTH) + SEPARATOR +
                        adjustLength(      tag,        TAG_LENGTH) + SEPARATOR;

        // Split the message onto multiple lines if needed,
        String message = chunkPreservingParentheses(line, MESSAGE_LENGTH, 2);
        print(fields + message, color);
        System.out.println();

        while (line.length() > message.length()) {

            // Debug,
            //print(line, OTHER_COLOR);
            //System.out.println("Line: " + line.length() + "length: " + message.length() + ", cont: " + CONTINUATION.length() + "dent: " + indentation.length());
            //System.out.println();

            // Remove the already printed part.
            line = line.substring(message.length()-CONTINUATION.length());

            // Add a dot to make links work,
            boolean shouldAddDot=false;
            if (line.matches("^[^\\.]*\\(.*:[123456789][1234567890]*\\).*")) shouldAddDot = true;

            // Indent,
            line = (shouldAddDot ? "." : (indentation.isEmpty() ? "" : " ")) + indentation + line;

            // Take another chunk,
            message = chunkPreservingParentheses(line, MESSAGE_LENGTH, 2+indentation.length());

            // Front pad to align this part with the message body,
            String paddedMessage = message;
            for (int i=0; i<fields.length(); i++) paddedMessage = ' ' + paddedMessage;

            // Print,
            print(paddedMessage, color);
            System.out.println();
        }

        return true;  // Keep in local buffer.
    }

    private static String adjustLength(String text, int length) {
        while (text.length() < length) text += ' ';
        if (text.length() > length) {
            text = text.substring(0, length-CONTINUATION.length());
            text += CONTINUATION;
        }
        return text;
    }

    private static String chunkPreservingParentheses(String text, int length, int minChunckLength) {

        if (text.length() <= length) return text;

        // Take a chunk out of the text,
        String chunk = text.substring(0, length-CONTINUATION.length()) + CONTINUATION;

        // Check if a paranthesis was opened and not closed,
        int lastOpenParanthesisIndex = chunk.lastIndexOf('(');
        int lastCloseParanthesisIndex = chunk.lastIndexOf(')');
        if (lastCloseParanthesisIndex <= lastOpenParanthesisIndex) {  // Also works when either is not found.
            if (minChunckLength<1) minChunckLength = 1;
            if (lastOpenParanthesisIndex > minChunckLength+CONTINUATION.length()) { // Avoid endless loops.
                int includeParenthesisSize = (CONTINUATION.length()>0) ? 1 : 0;
                chunk = text.substring(0, lastOpenParanthesisIndex+includeParenthesisSize-CONTINUATION.length()) + CONTINUATION;
            }
        }

        return chunk;
    }

    private static void repeatHistory() {
        int index = currentLocationInHistory-historyLength;
        if (index < 0) index += history.length;
        for (int i=0; i<historyLength; i++) {
            processLogcatLine(history[index]);
            index = (index + 1) % history.length;
        }
    }

    private static void print(String text, Color color) {
        System.out.print(color);
        System.out.print(text);
        System.out.print(Color.RESET);
    }

    private static String removeRedundantSpaces(String text) {
        String newText = text.replace("  ", " ");
        while (!text.equals(newText)) {
            text = newText;
            newText = text.replace("  ", " ");
        }
        return text;
    }

    private static void clearAndroidStudioConsole() {

        // Couldn't find a reliable way to clear Intellij terminal scrollback, so we just print
        // a LOT of newlines,
        StringBuilder bunchOfNewLines = new StringBuilder();
        for (int i=0; i<124; i++) bunchOfNewLines.append(System.lineSeparator());
        System.out.print(bunchOfNewLines);

        // Scroll the current line to the top of the window,
        try {
            // If we are on Windows,
            new ProcessBuilder("cmd", "/c", "cls").inheritIO().start().waitFor();
        } catch (Exception e) {

            // We are not on Windows,
            bunchOfNewLines = new StringBuilder();
            for (int i=0; i<124; i++) bunchOfNewLines.append("\b\r");
            System.out.print(bunchOfNewLines);
        }
    }

    private static void handleUserInput() {

        // Line read. Unfortunately, java doesn't provide character by character reading out of the box.
        BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(System.in));
        String input = "";
        do {
            try {
                if (bufferedReader.ready()) {
                    input = input = bufferedReader.readLine().toUpperCase();

                    // Set log level,
                    if (input.equals("V")||input.equals("D")||input.equals("I")||input.equals("W")||input.equals("E")) {

                        if (!logLevelToShow.equals(input)) {
                            logLevelToShow = input;
                            clearAndroidStudioConsole();
                            repeatHistory();
                        }

                        prettify("----- Log level set to " + logLevelToShow + " -----");

                    } else if (input.equals("C")) {

                        // Clear screen and history,
                        clearAndroidStudioConsole();
                        historyLength = 0;
                    }
                } else {
                    Thread.sleep(100);
                }
            } catch (Exception e) { e.printStackTrace(); }

            // Check if the logcat process is still alive,
            if (!logcatProcess.isAlive()) {
                prettify("----- adb logcat process terminated -----");
                stopEverything = true;
            }

        } while (!stopEverything && !input.equals("Q"));

        // Allow all monitoring threads to exit,
        stopEverything = true;
    }

    interface ProcessListener {
        void onNewLine(String line);
    }

    enum Color {

        // Thanks to this answer: https://stackoverflow.com/a/51944613/1942069

        //Color end string, color reset
        RESET("\033[0m"),

        // Regular Colors. Normal color, no bold, background color etc.
        BLACK  ("\033[0;30m"),
        RED    ("\033[0;31m"),
        GREEN  ("\033[0;32m"),
        YELLOW ("\033[0;33m"),
        BLUE   ("\033[0;34m"),
        MAGENTA("\033[0;35m"),
        CYAN   ("\033[0;36m"),
        WHITE  ("\033[0;37m"),

        // Bold
        BLACK_BOLD  ("\033[1;30m"),
        RED_BOLD    ("\033[1;31m"),
        GREEN_BOLD  ("\033[1;32m"),
        YELLOW_BOLD ("\033[1;33m"),
        BLUE_BOLD   ("\033[1;34m"),
        MAGENTA_BOLD("\033[1;35m"),
        CYAN_BOLD   ("\033[1;36m"),
        WHITE_BOLD  ("\033[1;37m"),

        // Underline
        BLACK_UNDERLINED  ("\033[4;30m"),
        RED_UNDERLINED    ("\033[4;31m"),
        GREEN_UNDERLINED  ("\033[4;32m"),
        YELLOW_UNDERLINED ("\033[4;33m"),
        BLUE_UNDERLINED   ("\033[4;34m"),
        MAGENTA_UNDERLINED("\033[4;35m"),
        CYAN_UNDERLINED   ("\033[4;36m"),
        WHITE_UNDERLINED  ("\033[4;37m"),

        // Background
        BLACK_BACKGROUND  ("\033[40m"),
        RED_BACKGROUND    ("\033[41m"),
        GREEN_BACKGROUND  ("\033[42m"),
        YELLOW_BACKGROUND ("\033[43m"),
        BLUE_BACKGROUND   ("\033[44m"),
        MAGENTA_BACKGROUND("\033[45m"),
        CYAN_BACKGROUND   ("\033[46m"),
        WHITE_BACKGROUND  ("\033[47m"),

        // High Intensity
        BLACK_BRIGHT  ("\033[0;90m"),
        RED_BRIGHT    ("\033[0;91m"),
        GREEN_BRIGHT  ("\033[0;92m"),
        YELLOW_BRIGHT ("\033[0;93m"),
        BLUE_BRIGHT   ("\033[0;94m"),
        MAGENTA_BRIGHT("\033[0;95m"),
        CYAN_BRIGHT   ("\033[0;96m"),
        WHITE_BRIGHT  ("\033[0;97m"),

        // Bold High Intensity
        BLACK_BOLD_BRIGHT  ("\033[1;90m"),
        RED_BOLD_BRIGHT    ("\033[1;91m"),
        GREEN_BOLD_BRIGHT  ("\033[1;92m"),
        YELLOW_BOLD_BRIGHT ("\033[1;93m"),
        BLUE_BOLD_BRIGHT   ("\033[1;94m"),
        MAGENTA_BOLD_BRIGHT("\033[1;95m"),
        CYAN_BOLD_BRIGHT   ("\033[1;96m"),
        WHITE_BOLD_BRIGHT  ("\033[1;97m"),

        // High Intensity backgrounds
        BLACK_BACKGROUND_BRIGHT  ("\033[0;100m"),
        RED_BACKGROUND_BRIGHT    ("\033[0;101m"),
        GREEN_BACKGROUND_BRIGHT  ("\033[0;102m"),
        YELLOW_BACKGROUND_BRIGHT ("\033[0;103m"),
        BLUE_BACKGROUND_BRIGHT   ("\033[0;104m"),
        MAGENTA_BACKGROUND_BRIGHT("\033[0;105m"),
        CYAN_BACKGROUND_BRIGHT   ("\033[0;106m"),
        WHITE_BACKGROUND_BRIGHT  ("\033[0;107m");

        private final String code;

        Color(String code) { this.code = code; }
        @Override public String toString() { return code; }
    }
}

Just dump this code into Logcat.java and compile using:

javac Logcat.java

And run inside the Android Studio's embedded terminal:

java Logcat <your.package.name>

For example:

java Logcat com.nomone.vr_desktop

The result looks like this:

My own Logcat prettifier

It's highly customizable, I've separated most of the options in the first section of the app, so you can tweak the colors and formatting easily. If the adb tool is not in your PATH environment variable, just set its full path in the ADB_FILE_PATH variable (in the code) before compiling.

When the application is running, you can type the following shortcuts:

  • c to clear the screen and local buffer.
  • v, i, d, w, e to change the logcat level.
  • q to quit gracefully. Ctrl+c works too.

Unfortunately, you have to press enter after pressing these keys. Seems like Java doesn't allow single character input from console without writing system specific code. Sorry!

Disclaimer

  • This doesn't work if multiple devices are connected using adb.
  • I haven't thoroughly tested this. I've only used it for a while on a few devices.
  • I haven't tested this on Windows or Mac, but I tried to avoid using anything system specific, so it should still work.

I hope this solves your problem :)

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

ImportError: No module named tensorflow

Try installing tensorflow in the user site - This installation only works for you.

pip install tensorflow --user

Styling text input caret

It is enough to use color property alongside with -webkit-text-fill-color this way:

_x000D_
_x000D_
    input {_x000D_
        color: red; /* color of caret */_x000D_
        -webkit-text-fill-color: black; /* color of text */_x000D_
    }
_x000D_
<input type="text"/>
_x000D_
_x000D_
_x000D_

Works in WebKit browsers (but not in iOS Safari, where is still used system color for caret) and also in Firefox.

The -webkit-text-fill-color CSS property specifies the fill color of characters of text. If this property is not set, the value of the color property is used. MDN

So this means we set text color with text-fill-color and caret color with standard color property. In unsupported browser, caret and text will have same color – color of the caret.

Fill Combobox from database

string query = "SELECT column_name FROM table_name";      //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();                               
            
while (reader.Read())   //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}

Check Postgres access for a user

Use this to list Grantee too and remove (PG_monitor and Public) for Postgres PaaS Azure.

SELECT grantee,table_catalog, table_schema, table_name, privilege_type
FROM   information_schema.table_privileges 
WHERE  grantee not in ('pg_monitor','PUBLIC');

Make Adobe fonts work with CSS3 @font-face in IE9

For everyone who gets the error: "tableversion must be 0, 1 or and is hex:003" when using ttfpatch, i've compiled embed for 64bit. I have not changed anything, just added need libs and compiled. Use at own risk.

Usage: ConsoleApplication1 font.ttf

http://www.mediafire.com/download/8x1px8aqq18lcx8/ConsoleApplication1.exe