Programs & Examples On #Mod ssl

The Apache Httpd interface to OpenSSL

ssl_error_rx_record_too_long and Apache SSL

I had the same problem in some browser to access to my SSL site. I have found that I had to give to fireFox the right proxy (FireFox was accessing directly to internet).

Depending of the lan configuration (Tunneling, filtering, proxy redirection), the "direct access to internet" mode for FireFox throws this error.

How to use the PRINT statement to track execution as stored procedure is running?

SQL Server returns messages after a batch of statements has been executed. Normally, you'd use SQL GO to indicate the end of a batch and to retrieve the results:

PRINT '1'
GO

WAITFOR DELAY '00:00:05'

PRINT '2'
GO

WAITFOR DELAY '00:00:05'

PRINT '3'
GO

In this case, however, the print statement you want returned immediately is in the middle of a loop, so the print statements cannot be in their own batch. The only command I know of that will return in the middle of a batch is RAISERROR (...) WITH NOWAIT, which gbn has provided as an answer as I type this.

SQL get the last date time record

Considering that max(dates) can be different for each filename, my solution :

select filename, dates, status
from yt a
where a.dates = (
  select max(dates)
    from yt b
    where a.filename = b.filename
)
;

http://sqlfiddle.com/#!18/fdf8d/1/0

HTH

Alter column in SQL Server

I think you want this syntax:

ALTER TABLE tb_TableName  
add constraint cnt_Record_Status Default '' for Record_Status

Based on some of your comments, I am going to guess that you might already have null values in your table which is causing the alter of the column to not null to fail. If that is the case, then you should run an UPDATE first. Your script will be:

update tb_TableName
set Record_Status  = ''
where Record_Status is null

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status VARCHAR(20) NOT NULL

ALTER TABLE tb_TableName
ADD CONSTRAINT DEF_Name DEFAULT '' FOR Record_Status

See SQL Fiddle with demo

Gradle project refresh failed after Android Studio update

Close your project, and then import project. That work for me. It's a simply way.

good luck.

How can I tell jackson to ignore a property for which I don't have control over the source code?

Using Java Class

new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false)

Using Annotation

@JsonIgnoreProperties(ignoreUnknown=true)

Pandas: Setting no. of max rows

to set unlimited number of rows use

None

i.e.,

pd.set_option('display.max_cols', None)

now the notebook will display all the rows in all datasets within the notebook ;)

Similarly you can set to show all columns as

pd.set_option('display.max_rows', None)

now if you use run the cell with only dataframe with out any head or tail tags as

df

then it will show all the rows and columns in the dataframe df

How can I generate an ObjectId with mongoose?

You can create a new MongoDB ObjectId like this using mongoose:

var mongoose = require('mongoose');
var newId = new mongoose.mongo.ObjectId('56cb91bdc3464f14678934ca');
// or leave the id string blank to generate an id with a new hex identifier
var newId2 = new mongoose.mongo.ObjectId();

How can I get a value from a map?

map.at("key") throws exception if missing key

If k does not match the key of any element in the container, the function throws an out_of_range exception.

http://www.cplusplus.com/reference/map/map/at/

Android Service needs to run always (Never pause or stop)

You can implement startForeground for the service and even if it dies you can restart it by using START_STICKY on startCommand(). Not sure though this is the right implementation.

Html/PHP - Form - Input as array

in addition: for those who have a empty POST variable, don't use this:

name="[levels][level][]"

rather use this (as it is already here in this example):

name="levels[level][]"

RSA: Get exponent and modulus given a public key

Beware the leading 00 that can appear in the modulus when using:

openssl rsa -pubin -inform PEM -text -noout < public.key

The example modulus contains 257 bytes rather than 256 bytes because of that 00, which is included because the 9 in 98 looks like a negative signed number.

jQuery Select first and second td

If you want to add a class to the first and second td you can use .each() and slice()

$(".location table tbody tr").each(function(){
    $(this).find("td").slice(0, 2).addClass("black");
});

Example on jsfiddle

How can I rename a single column in a table at select?

There is no need to use AS, just use:

SELECT table1.price Table1 Price, table2.price Table2 Price, .....

How to check if a double is null?

How are you getting the value of "results"? Are you getting it via ResultSet.getDouble()? In that case, you can check ResultSet.wasNull().

How to convert buffered image to image and vice-versa?

You can try saving (or writing) the Buffered Image with the changes you made and then opening it as an Image.

EDIT:

try {
    // Retrieve Image
    BufferedImage buffer = ImageIO.read(new File("old.png"));;
    // Here you can rotate your image as you want (making your magic)
    File outputfile = new File("saved.png");
    ImageIO.write(buffer, "png", outputfile); // Write the Buffered Image into an output file
    Image image  = ImageIO.read(new File("saved.png")); // Opening again as an Image
} catch (IOException e) {
    ...
}

How can I convert a DateTime to an int?

long n = long.Parse(date.ToString("yyyyMMddHHmmss"));

see Custom Date and Time Format Strings

Python loop for inside lambda

If you are like me just want to print a sequence within a lambda, without get the return value (list of None).

x = range(3)
from __future__ import print_function           # if not python 3
pra = lambda seq=x: map(print,seq) and None     # pra for 'print all'
pra()
pra('abc')

Getting a directory name from a filename

I'm so surprised no one has mentioned the standard way in Posix

Please use basename / dirname constructs.

man basename

How to echo JSON in PHP

if you want to encode or decode an array from or to JSON you can use these functions

$myJSONString = json_encode($myArray);
$myArray = json_decode($myString);

json_encode will result in a JSON string, built from an (multi-dimensional) array. json_decode will result in an Array, built from a well formed JSON string

with json_decode you can take the results from the API and only output what you want, for example:

echo $myArray['payload']['ign'];

Zip folder in C#

using DotNetZip (available as nuget package):

public void Zip(string source, string destination)
{
    using (ZipFile zip = new ZipFile
    {
        CompressionLevel = CompressionLevel.BestCompression
    })
    {
        var files = Directory.GetFiles(source, "*",
            SearchOption.AllDirectories).
            Where(f => Path.GetExtension(f).
                ToLowerInvariant() != ".zip").ToArray();

        foreach (var f in files)
        {
            zip.AddFile(f, GetCleanFolderName(source, f));
        }

        var destinationFilename = destination;

        if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
        {
            destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
        }

        zip.Save(destinationFilename);
    }
}

private string GetCleanFolderName(string source, string filepath)
{
    if (string.IsNullOrWhiteSpace(filepath))
    {
        return string.Empty;
    }

    var result = filepath.Substring(source.Length);

    if (result.StartsWith("\\"))
    {
        result = result.Substring(1);
    }

    result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

    return result;
}

Usage:

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");

Or

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");

How to find the day, month and year with moment.js

If you are looking for answer in string values , try this

var check = moment('date/utc format');
day = check.format('dddd') // => ('Monday' , 'Tuesday' ----)
month = check.format('MMMM') // => ('January','February.....)
year = check.format('YYYY') // => ('2012','2013' ...)  

Can I invoke an instance method on a Ruby module without including it?

After almost 9 years here's a generic solution:

module CreateModuleFunctions
  def self.included(base)
    base.instance_methods.each do |method|
      base.module_eval do
        module_function(method)
        public(method)
      end
    end
  end
end

RSpec.describe CreateModuleFunctions do
  context "when included into a Module" do
    it "makes the Module's methods invokable via the Module" do
      module ModuleIncluded
        def instance_method_1;end
        def instance_method_2;end

        include CreateModuleFunctions
      end

      expect { ModuleIncluded.instance_method_1 }.to_not raise_error
    end
  end
end

The unfortunate trick you need to apply is to include the module after the methods have been defined. Alternatively you may also include it after the context is defined as ModuleIncluded.send(:include, CreateModuleFunctions).

Or you can use it via the reflection_utils gem.

spec.add_dependency "reflection_utils", ">= 0.3.0"

require 'reflection_utils'
include ReflectionUtils::CreateModuleFunctions

jquery how to catch enter key and change event to tab

Here's a jQuery plugin I wrote that handles enter key as a callback or as a tab key (with an optional callback):

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('#one').onEnter('tab');_x000D_
  $('#two').onEnter('tab');_x000D_
  $('#three').onEnter('tab');_x000D_
  $('#four').onEnter('tab');_x000D_
  $('#five').onEnter('tab');_x000D_
});_x000D_
_x000D_
/**_x000D_
 * jQuery.onEnter.js_x000D_
 * Written by: Jay Simons_x000D_
 * Cloudulus.Media (https://code.cloudulus.media)_x000D_
 */_x000D_
_x000D_
if (window.jQuery) {_x000D_
    (function ($) {_x000D_
        $.fn.onEnter = function (opt1, opt2, opt3) {_x000D_
            return this.on('keyup', function (e) {_x000D_
                var me = $(this);_x000D_
                var code = e.keyCode ? e.keyCode : e.which;_x000D_
                if (code == 13) {_x000D_
                    if (typeof opt1 == 'function')_x000D_
                    {_x000D_
                        opt1(me, opt2);_x000D_
                        return true;_x000D_
                    }else if (opt1 == 'tab')_x000D_
                    {_x000D_
                        var eles = $(document).find('input,select,textarea,button').filter(':visible:not(:disabled):not([readonly])');_x000D_
                        var foundMe = false;_x000D_
                        var next = null;_x000D_
                        eles.each(function(){_x000D_
                            if (!next){_x000D_
                                if (foundMe) next = $(this);_x000D_
                                if (JSON.stringify($(this)) == JSON.stringify(me)) foundMe = true;_x000D_
                            }_x000D_
                        });_x000D_
                        next.focus();_x000D_
                        if (typeof opt2 === 'function')_x000D_
                        {_x000D_
                            opt2(me, opt3);_x000D_
                        }_x000D_
                        return true;_x000D_
                    }_x000D_
                }_x000D_
            }).on('keydown', function(e){_x000D_
                var code = e.keyCode ? e.keyCode : e.which;_x000D_
                if (code == 13)_x000D_
                {_x000D_
                    e.preventDefault();_x000D_
                    e.stopPropagation();_x000D_
                    return false;_x000D_
                }_x000D_
            });_x000D_
        }_x000D_
    })(jQuery);_x000D_
} else {_x000D_
    console.log("onEnter.js: This class requies jQuery > v3!");_x000D_
}
_x000D_
input,_x000D_
select,_x000D_
textarea,_x000D_
button {_x000D_
  display: block;_x000D_
  margin-bottom: 1em;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>_x000D_
<form>_x000D_
  <input id="one" type="text" placeholder="Input 1" />_x000D_
  <input id="two" type="text" placeholder="Input 2" />_x000D_
_x000D_
  <select id="four">_x000D_
    <option selected>A Select Box</option>_x000D_
    <option>Opt 1</option>_x000D_
    <option>Opt 2</option>_x000D_
  </select>_x000D_
  <textarea id="five" placeholder="A textarea"></textarea>_x000D_
  <input id="three" type="text" placeholder="Input 3" />_x000D_
  <button>A Button</button>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Reading data from a website using C#

The WebClient class should be more than capable of handling the functionality you describe, for example:

System.Net.WebClient wc = new System.Net.WebClient();
byte[] raw = wc.DownloadData("http://www.yoursite.com/resource/file.htm");

string webData = System.Text.Encoding.UTF8.GetString(raw);

or (further to suggestion from Fredrick in comments)

System.Net.WebClient wc = new System.Net.WebClient();
string webData = wc.DownloadString("http://www.yoursite.com/resource/file.htm");

When you say it took 30 seconds, can you expand on that a little more? There are many reasons as to why that could have happened. Slow servers, internet connections, dodgy implementation etc etc.

You could go a level lower and implement something like this:

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create("http://www.yoursite.com/resource/file.htm");

using (StreamWriter streamWriter = new StreamWriter(webRequest.GetRequestStream(), Encoding.UTF8))
{
    streamWriter.Write(requestData);
}

string responseData = string.Empty;
HttpWebResponse httpResponse = (HttpWebResponse)webRequest.GetResponse();
using (StreamReader responseReader = new StreamReader(httpResponse.GetResponseStream()))
{
    responseData = responseReader.ReadToEnd();
}

However, at the end of the day the WebClient class wraps up this functionality for you. So I would suggest that you use WebClient and investigate the causes of the 30 second delay.

Finding a substring within a list in Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

The best answer is already given in the gradle output:

* Try:
Run with --stacktrace option to get the stack trace. 

Open the Terminal in Android Studio and run gradlew :app:mergeDebugResources --stacktrace. (In my case it was the Windows 240 char limit), but it should give you the root cause for any other issue just as well.

How to find text in a column and saving the row number where it is first found - Excel VBA

A few comments:

  1. Since the search position is important you should specify where you start the search. I use ws.[a1] and xlNext below so my search starts in A2 of the specified sheet.
  2. Some of Finds arguments - including lookat use the prior search settings. So you should always specify xlWhole or xlPart to match all or part a string respectively.
  3. You can do all you want - including inserting a row, and prompting the user for a new value (my code will suggest 20 if the prior value was 19) without using Select or Activate

suggested code

Sub FindEm()
Dim Wb As Workbook
Dim ws As Worksheet
Dim rng1 As Range
Set Wb = ThisWorkbook
Set ws = Wb.Sheets("ECM Overview")
Set rng1 = ws.Range("A:A").Find("ProjTemp", ws.[a1], xlValues, xlWhole, , xlNext)
If Not rng1 Is Nothing Then
rng1.EntireRow.Insert
rng1.Offset(-1, 0).Value = Application.InputBox("Please enter data", "User Data Entry", rng1.Offset(-2, 0) + 1, , , , , 1)
Else
MsgBox "ProjTemp not found", vbCritical
End If
End Sub

ISO C++ forbids comparison between pointer and integer [-fpermissive]| [c++]

char a[2] defines an array of char's. a is a pointer to the memory at the beginning of the array and using == won't actually compare the contents of a with 'ab' because they aren't actually the same types, 'ab' is integer type. Also 'ab' should be "ab" otherwise you'll have problems here too. To compare arrays of char you'd want to use strcmp.

Something that might be illustrative is looking at the typeid of 'ab':

#include <iostream>
#include <typeinfo>
using namespace std;
int main(){
    int some_int =5;
    std::cout << typeid('ab').name() << std::endl;
    std::cout << typeid(some_int).name() << std::endl;
    return 0;
}

on my system this returns:

i
i

showing that 'ab' is actually evaluated as an int.

If you were to do the same thing with a std::string then you would be dealing with a class and std::string has operator == overloaded and will do a comparison check when called this way.

If you wish to compare the input with the string "ab" in an idiomatic c++ way I suggest you do it like so:

#include <iostream>
#include <string>
using namespace std;
int main(){
    string a;
    cout<<"enter ab ";
    cin>>a;
    if(a=="ab"){
         cout<<"correct";
    }
    return 0;
}

This one is due to:

if(a=='ab') , here, a is const char* type (ie : array of char)

'ab' is a constant value,which isn't evaluated as string (because of single quote) but will be evaluated as integer.

Since char is a primitive type inherited from C, no operator == is defined.

the good code should be:

if(strcmp(a,"ab")==0) , then you'll compare a const char* to another const char* using strcmp.

HTML5 record audio to file

You can use Recordmp3js from GitHub to achieve your requirements. You can record from user's microphone and then get the file as an mp3. Finally upload it to your server.

I used this in my demo. There is a already a sample available with the source code by the author in this location : https://github.com/Audior/Recordmp3js

The demo is here: http://audior.ec/recordmp3js/

But currently works only on Chrome and Firefox.

Seems to work fine and pretty simple. Hope this helps.

nuget 'packages' element is not declared warning

You can always make simple xsd schema for 'packages.config' to get rid of this warning. To do this, create file named "packages.xsd":

<?xml version="1.0" encoding="utf-8" ?>
<xs:schema xmlns:xs="http://www.w3.org/2001/XMLSchema" elementFormDefault="qualified"
      targetNamespace="urn:packages" xmlns="urn:packages">
  <xs:element name="packages">
    <xs:complexType>
      <xs:sequence>
        <xs:element name="package" maxOccurs="unbounded">
          <xs:complexType>
            <xs:attribute name="id" type="xs:string" use="required" />
            <xs:attribute name="version" type="xs:string" use="required" />
            <xs:attribute name="targetFramework" type="xs:string" use="optional" />
            <xs:attribute name="allowedVersions" type="xs:string" use="optional" />
          </xs:complexType>
        </xs:element>
      </xs:sequence>
    </xs:complexType>
  </xs:element>
</xs:schema>

Location of this file (two options)

  • In the same folder as 'packages.config' file,
  • If you want to share packages.xsd across multiple projects, move it to the Visual Studio Schemas folder (the path may slightly differ, it's D:\Program Files (x86)\Microsoft Visual Studio 10.0\Xml\Schemas for me).

Then, edit <packages> tag in packages.config file (add xmlns attribute):

<packages xmlns="urn:packages">

Now the warning should disappear (even if packages.config file is open in Visual Studio).

Use grep to report back only line numbers

All of these answers require grep to generate the entire matching lines, then pipe it to another program. If your lines are very long, it might be more efficient to use just sed to output the line numbers:

sed -n '/pattern/=' filename

fe_sendauth: no password supplied

I just put --password flag into my command and after hitting Enter it asked me for password, which I supplied.

How to fill background image of an UIView

The colorWithPattern: method is really for generating patterns from images. Thus, the customization you require is most likely not possible, nor is it meant to be.

Indeed you need to use a UIImageView to center and scale an image. The fact that you have a UIScrollView does not prevent this:

Make self.view a generic view, then add both the UIImageView and the UIScrollView as subviews. Make sure all is wired up correctly in Interface Builder, and make the background color of the scroll view transparent.

This is IMHO the simplest and most flexible design for future changes.

How to search contents of multiple pdf files?

I had the same problem and thus I wrote a script which searches all pdf files in the specified folder for a string and prints the PDF files wich matched the query string.

Maybe this will be helpful to you.

You can download it here

How do you create a temporary table in an Oracle database?

Just a tip.. Temporary tables in Oracle are different to SQL Server. You create it ONCE and only ONCE, not every session. The rows you insert into it are visible only to your session, and are automatically deleted (i.e., TRUNCATE, not DROP) when you end you session ( or end of the transaction, depending on which "ON COMMIT" clause you use).

Setting a checkbox as checked with Vue.js

I experienced this issue and couldn't figure out a fix for a few hours, until I realised I had incorrectly prevented native events from occurring with:

<input type="checkbox" @click.prevent="toggleConfirmedStatus(render.uuid)"
    :checked="confirmed.indexOf(render.uuid) > -1"
    :value="render.uuid"
/>

removing the .prevent from the @click handler fixed my issue.

How to use Apple's new .p8 certificate for APNs in firebase console

Firebase console is now accepting .p8 file, in fact, it's recommending to upload .p8 file.

You can see in below-attached screenshot

Setting DEBUG = False causes 500 Error

Django 1.5 introduced the allowed hosts setting that is required for security reasons. A settings file created with Django 1.5 has this new section which you need to add:

# Hosts/domain names that are valid for this site; required if DEBUG is False
# See https://docs.djangoproject.com/en/1.9/ref/settings/#allowed-hosts
ALLOWED_HOSTS = []

Add your host here like ['www.beta800.net'] or ['*'] for a quick test, but don't use ['*'] for production.

Bootstrap 3 Glyphicons CDN

An alternative would be to use Font-Awesome for icons:

Including Font-Awesome

Open Font-Awesome on CDNJS and copy the CSS url of the latest version:

<link rel="stylesheet" href="<url>">

Or in CSS

@import url("<url>");

For example (note, the version will change):

<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.css">

Usage:

<i class="fa fa-bed"></i>

It contains a lot of icons!

What's the best way to set a single pixel in an HTML5 canvas?

Draw a rectangle like sdleihssirhc said!

ctx.fillRect (10, 10, 1, 1);

^-- should draw a 1x1 rectangle at x:10, y:10

How to prevent caching of my Javascript file?

You can append a queryString to your src and change it only when you will release an updated version:

<script src="test.js?v=1"></script>

In this way the browser will use the cached version until a new version will be specified (v=2, v=3...)

CSS: transition opacity on mouse-out?

I managed to find a solution using css/jQuery that I'm comfortable with. The original issue: I had to force the visibility to be shown while animating as I have elements hanging outside the area. Doing so, made large blocks of text now hang outside the content area during animation as well.

The solution was to start the main text elements with an opacity of 0 and use addClass to inject and transition to an opacity of 1. Then removeClass when clicked on again.

I'm sure there's an all jQquery way to do this. I'm just not the guy to do it. :)

So in it's most basic form...

.slideDown().addClass("load");
.slideUp().removeClass("load");

Thanks for the help everyone.

IIS: Where can I find the IIS logs?

The 100% correct answer for the default location of the log files is...

%SystemDrive%\inetpub\logs\LogFiles

Yes you can enter this into the explorer address bar it'll work.

To be 100% sure, you need to look at the logging for the web site in IIS.

https://docs.microsoft.com/en-us/iis/get-started/whats-new-in-iis-85/enhanced-logging-for-iis85

i.e.

  1. Open IIS Manager.
  2. Select the site or server in the Connections pane,
  3. Double-click Logging.
  4. The location of log files for the site can be found within the Directory field

EDIT: As pointed out by Andy in the comments below you need to ensure when installing IIS that you elected to enable HTTP logging, otherwise HTTP logging won't be available.

Enable HTTP Logging

ArrayList: how does the size increase?

It will depend on the implementation, but from the Sun Java 6 source code:

int newCapacity = (oldCapacity * 3)/2 + 1;

That's in the ensureCapacity method. Other JDK implementations may vary.

Unable to Connect to GitHub.com For Cloning

I had the same error because I was using proxy. As the answer is given but in case you are using proxy then please set your proxy first using these commands:

git config --global http.proxy http://proxy_username:proxy_password@proxy_ip:port
git config --global https.proxy https://proxy_username:proxy_password@proxy_ip:port

What is com.sun.proxy.$Proxy

What are they?

Nothing special. Just as same as common Java Class Instance.

But those class are Synthetic proxy classes created by java.lang.reflect.Proxy#newProxyInstance

What is there relationship to the JVM? Are they JVM implementation specific?

Introduced in 1.3

http://docs.oracle.com/javase/1.3/docs/relnotes/features.html#reflection

It is a part of Java. so each JVM should support it.

How are they created (Openjdk7 source)?

In short : they are created using JVM ASM tech ( defining javabyte code at runtime )

something using same tech:

What happens after calling java.lang.reflect.Proxy#newProxyInstance

  1. reading the source you can see newProxyInstance call getProxyClass0 to obtain a `Class

    `

  2. after lots of cache or sth it calls the magic ProxyGenerator.generateProxyClass which return a byte[]
  3. call ClassLoader define class to load the generated $Proxy Class (the classname you have seen)
  4. just instance it and ready for use

What happens in magic sun.misc.ProxyGenerator

  1. draw a class(bytecode) combining all methods in the interfaces into one
  2. each method is build with same bytecode like

    1. get calling Method meth info (stored while generating)
    2. pass info into invocation handler's invoke()
    3. get return value from invocation handler's invoke()
    4. just return it
  3. the class(bytecode) represent in form of byte[]

How to draw a class

Thinking your java codes are compiled into bytecodes, just do this at runtime

Talk is cheap show you the code

core method in sun/misc/ProxyGenerator.java

generateClassFile

/**
 * Generate a class file for the proxy class.  This method drives the
 * class file generation process.
 */
private byte[] generateClassFile() {

    /* ============================================================
     * Step 1: Assemble ProxyMethod objects for all methods to
     * generate proxy dispatching code for.
     */

    /*
     * Record that proxy methods are needed for the hashCode, equals,
     * and toString methods of java.lang.Object.  This is done before
     * the methods from the proxy interfaces so that the methods from
     * java.lang.Object take precedence over duplicate methods in the
     * proxy interfaces.
     */
    addProxyMethod(hashCodeMethod, Object.class);
    addProxyMethod(equalsMethod, Object.class);
    addProxyMethod(toStringMethod, Object.class);

    /*
     * Now record all of the methods from the proxy interfaces, giving
     * earlier interfaces precedence over later ones with duplicate
     * methods.
     */
    for (int i = 0; i < interfaces.length; i++) {
        Method[] methods = interfaces[i].getMethods();
        for (int j = 0; j < methods.length; j++) {
            addProxyMethod(methods[j], interfaces[i]);
        }
    }

    /*
     * For each set of proxy methods with the same signature,
     * verify that the methods' return types are compatible.
     */
    for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
        checkReturnTypes(sigmethods);
    }

    /* ============================================================
     * Step 2: Assemble FieldInfo and MethodInfo structs for all of
     * fields and methods in the class we are generating.
     */
    try {
        methods.add(generateConstructor());

        for (List<ProxyMethod> sigmethods : proxyMethods.values()) {
            for (ProxyMethod pm : sigmethods) {

                // add static field for method's Method object
                fields.add(new FieldInfo(pm.methodFieldName,
                    "Ljava/lang/reflect/Method;",
                     ACC_PRIVATE | ACC_STATIC));

                // generate code for proxy method and add it
                methods.add(pm.generateMethod());
            }
        }

        methods.add(generateStaticInitializer());

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    if (methods.size() > 65535) {
        throw new IllegalArgumentException("method limit exceeded");
    }
    if (fields.size() > 65535) {
        throw new IllegalArgumentException("field limit exceeded");
    }

    /* ============================================================
     * Step 3: Write the final class file.
     */

    /*
     * Make sure that constant pool indexes are reserved for the
     * following items before starting to write the final class file.
     */
    cp.getClass(dotToSlash(className));
    cp.getClass(superclassName);
    for (int i = 0; i < interfaces.length; i++) {
        cp.getClass(dotToSlash(interfaces[i].getName()));
    }

    /*
     * Disallow new constant pool additions beyond this point, since
     * we are about to write the final constant pool table.
     */
    cp.setReadOnly();

    ByteArrayOutputStream bout = new ByteArrayOutputStream();
    DataOutputStream dout = new DataOutputStream(bout);

    try {
        /*
         * Write all the items of the "ClassFile" structure.
         * See JVMS section 4.1.
         */
                                    // u4 magic;
        dout.writeInt(0xCAFEBABE);
                                    // u2 minor_version;
        dout.writeShort(CLASSFILE_MINOR_VERSION);
                                    // u2 major_version;
        dout.writeShort(CLASSFILE_MAJOR_VERSION);

        cp.write(dout);             // (write constant pool)

                                    // u2 access_flags;
        dout.writeShort(ACC_PUBLIC | ACC_FINAL | ACC_SUPER);
                                    // u2 this_class;
        dout.writeShort(cp.getClass(dotToSlash(className)));
                                    // u2 super_class;
        dout.writeShort(cp.getClass(superclassName));

                                    // u2 interfaces_count;
        dout.writeShort(interfaces.length);
                                    // u2 interfaces[interfaces_count];
        for (int i = 0; i < interfaces.length; i++) {
            dout.writeShort(cp.getClass(
                dotToSlash(interfaces[i].getName())));
        }

                                    // u2 fields_count;
        dout.writeShort(fields.size());
                                    // field_info fields[fields_count];
        for (FieldInfo f : fields) {
            f.write(dout);
        }

                                    // u2 methods_count;
        dout.writeShort(methods.size());
                                    // method_info methods[methods_count];
        for (MethodInfo m : methods) {
            m.write(dout);
        }

                                     // u2 attributes_count;
        dout.writeShort(0); // (no ClassFile attributes for proxy classes)

    } catch (IOException e) {
        throw new InternalError("unexpected I/O Exception");
    }

    return bout.toByteArray();
}

addProxyMethod

/**
 * Add another method to be proxied, either by creating a new
 * ProxyMethod object or augmenting an old one for a duplicate
 * method.
 *
 * "fromClass" indicates the proxy interface that the method was
 * found through, which may be different from (a subinterface of)
 * the method's "declaring class".  Note that the first Method
 * object passed for a given name and descriptor identifies the
 * Method object (and thus the declaring class) that will be
 * passed to the invocation handler's "invoke" method for a given
 * set of duplicate methods.
 */
private void addProxyMethod(Method m, Class fromClass) {
    String name = m.getName();
    Class[] parameterTypes = m.getParameterTypes();
    Class returnType = m.getReturnType();
    Class[] exceptionTypes = m.getExceptionTypes();

    String sig = name + getParameterDescriptors(parameterTypes);
    List<ProxyMethod> sigmethods = proxyMethods.get(sig);
    if (sigmethods != null) {
        for (ProxyMethod pm : sigmethods) {
            if (returnType == pm.returnType) {
                /*
                 * Found a match: reduce exception types to the
                 * greatest set of exceptions that can thrown
                 * compatibly with the throws clauses of both
                 * overridden methods.
                 */
                List<Class<?>> legalExceptions = new ArrayList<Class<?>>();
                collectCompatibleTypes(
                    exceptionTypes, pm.exceptionTypes, legalExceptions);
                collectCompatibleTypes(
                    pm.exceptionTypes, exceptionTypes, legalExceptions);
                pm.exceptionTypes = new Class[legalExceptions.size()];
                pm.exceptionTypes =
                    legalExceptions.toArray(pm.exceptionTypes);
                return;
            }
        }
    } else {
        sigmethods = new ArrayList<ProxyMethod>(3);
        proxyMethods.put(sig, sigmethods);
    }
    sigmethods.add(new ProxyMethod(name, parameterTypes, returnType,
                                   exceptionTypes, fromClass));
}

Full code about gen the proxy method

    private MethodInfo generateMethod() throws IOException {
        String desc = getMethodDescriptor(parameterTypes, returnType);
        MethodInfo minfo = new MethodInfo(methodName, desc,
            ACC_PUBLIC | ACC_FINAL);

        int[] parameterSlot = new int[parameterTypes.length];
        int nextSlot = 1;
        for (int i = 0; i < parameterSlot.length; i++) {
            parameterSlot[i] = nextSlot;
            nextSlot += getWordsPerType(parameterTypes[i]);
        }
        int localSlot0 = nextSlot;
        short pc, tryBegin = 0, tryEnd;

        DataOutputStream out = new DataOutputStream(minfo.code);

        code_aload(0, out);

        out.writeByte(opc_getfield);
        out.writeShort(cp.getFieldRef(
            superclassName,
            handlerFieldName, "Ljava/lang/reflect/InvocationHandler;"));

        code_aload(0, out);

        out.writeByte(opc_getstatic);
        out.writeShort(cp.getFieldRef(
            dotToSlash(className),
            methodFieldName, "Ljava/lang/reflect/Method;"));

        if (parameterTypes.length > 0) {

            code_ipush(parameterTypes.length, out);

            out.writeByte(opc_anewarray);
            out.writeShort(cp.getClass("java/lang/Object"));

            for (int i = 0; i < parameterTypes.length; i++) {

                out.writeByte(opc_dup);

                code_ipush(i, out);

                codeWrapArgument(parameterTypes[i], parameterSlot[i], out);

                out.writeByte(opc_aastore);
            }
        } else {

            out.writeByte(opc_aconst_null);
        }

        out.writeByte(opc_invokeinterface);
        out.writeShort(cp.getInterfaceMethodRef(
            "java/lang/reflect/InvocationHandler",
            "invoke",
            "(Ljava/lang/Object;Ljava/lang/reflect/Method;" +
                "[Ljava/lang/Object;)Ljava/lang/Object;"));
        out.writeByte(4);
        out.writeByte(0);

        if (returnType == void.class) {

            out.writeByte(opc_pop);

            out.writeByte(opc_return);

        } else {

            codeUnwrapReturnValue(returnType, out);
        }

        tryEnd = pc = (short) minfo.code.size();

        List<Class<?>> catchList = computeUniqueCatchList(exceptionTypes);
        if (catchList.size() > 0) {

            for (Class<?> ex : catchList) {
                minfo.exceptionTable.add(new ExceptionTableEntry(
                    tryBegin, tryEnd, pc,
                    cp.getClass(dotToSlash(ex.getName()))));
            }

            out.writeByte(opc_athrow);

            pc = (short) minfo.code.size();

            minfo.exceptionTable.add(new ExceptionTableEntry(
                tryBegin, tryEnd, pc, cp.getClass("java/lang/Throwable")));

            code_astore(localSlot0, out);

            out.writeByte(opc_new);
            out.writeShort(cp.getClass(
                "java/lang/reflect/UndeclaredThrowableException"));

            out.writeByte(opc_dup);

            code_aload(localSlot0, out);

            out.writeByte(opc_invokespecial);

            out.writeShort(cp.getMethodRef(
                "java/lang/reflect/UndeclaredThrowableException",
                "<init>", "(Ljava/lang/Throwable;)V"));

            out.writeByte(opc_athrow);
        }

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

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

array_push() with key value pair

For Example:

$data = array('firstKey' => 'firstValue', 'secondKey' => 'secondValue');

For changing key value:

$data['firstKey'] = 'changedValue'; 
//this will change value of firstKey because firstkey is available in array

output:

Array ( [firstKey] => changedValue [secondKey] => secondValue )

For adding new key value pair:

$data['newKey'] = 'newValue'; 
//this will add new key and value because newKey is not available in array

output:

Array ( [firstKey] => firstValue [secondKey] => secondValue [newKey] => newValue )

PHP array printing using a loop

Use a foreach loop, it loops through all the key=>value pairs:

 foreach($array as $key=>$value){
     print "$key holds $value\n";
 }

Or to answer your question completely:

 foreach($array as $value){
     print $value."\n";
 }

Using onBackPressed() in Android Fragments

In the fragment where you would like to handle your back button you should attach stuff to your view in the oncreateview

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View v = inflater.inflate(R.layout.second_fragment, container, false);
    v.setOnKeyListener(pressed);
    return v;
}



@Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
    // TODO Auto-generated method stub
    if( keyCode == KeyEvent.KEYCODE_BACK ){
            // back to previous fragment by tag
            myfragmentclass fragment = (myfragmentclass) getActivity().getSupportFragmentManager().findFragmentByTag(TAG);
            if(fragment != null){
                (getActivity().getSupportFragmentManager().beginTransaction()).replace(R.id.cf_g1_mainframe_fm, fragment).commit();
            }
            return true;
        }
        return false;
    }
};

Convert char * to LPWSTR

You may use CString, CStringA, CStringW to do automatic conversions and convert between these types. Further, you may also use CStrBuf, CStrBufA, CStrBufW to get RAII pattern modifiable strings

Gradle version 2.2 is required. Current version is 2.10

I Had similar issue. Every project has his own gradle folder, check if in your project root there's another gradle folder:

/my_projects_root_folder/project/gradle
/my_projects_root_folder/gradle

If so, in every folder you'll find /gradle/wrapper/gradle-wrapper.properties.

Check if in /my_projects_root_folder/gradle/gradle-wrapper.properties gradle version at least match /my_projects_root_folder/ project/ gradle/ gradle-wrapper.properties gradle version

Or just delete/rename your /my_projects_root_folder/gradle and restart android studio and let Gradle sync work and download required gradle.

jquery .on() method with load event

Refer to http://api.jquery.com/on/

It says

In all browsers, the load, scroll, and error events (e.g., on an <img> element) do not bubble. In Internet Explorer 8 and lower, the paste and reset events do not bubble. Such events are not supported for use with delegation, but they can be used when the event handler is directly attached to the element generating the event.

If you want to do something when a new input box is added then you can simply write the code after appending it.

$('#add').click(function(){
        $('body').append(x);
        // Your code can be here
    });

And if you want the same code execute when the first input box within the document is loaded then you can write a function and call it in both places i.e. $('#add').click and document's ready event

Convert from MySQL datetime to another format with PHP

An easier way would be to format the date directly in the MySQL query, instead of PHP. See the MySQL manual entry for DATE_FORMAT.

If you'd rather do it in PHP, then you need the date function, but you'll have to convert your database value into a timestamp first.

Using Java 8's Optional with Stream::flatMap

You cannot do it more concise as you are already doing.

You claim that you do not want .filter(Optional::isPresent) and .map(Optional::get).

This has been resolved by the method @StuartMarks describes, however as a result you now map it to an Optional<T>, so now you need to use .flatMap(this::streamopt) and a get() in the end.

So it still consists of two statements and you can now get exceptions with the new method! Because, what if every optional is empty? Then the findFirst() will return an empty optional and your get() will fail!

So what you have:

things.stream()
    .map(this::resolve)
    .filter(Optional::isPresent)
    .map(Optional::get)
    .findFirst();

is actually the best way to accomplish what you want, and that is you want to save the result as a T, not as an Optional<T>.

I took the liberty of creating a CustomOptional<T> class that wraps the Optional<T> and provides an extra method, flatStream(). Note that you cannot extend Optional<T>:

class CustomOptional<T> {
    private final Optional<T> optional;

    private CustomOptional() {
        this.optional = Optional.empty();
    }

    private CustomOptional(final T value) {
        this.optional = Optional.of(value);
    }

    private CustomOptional(final Optional<T> optional) {
        this.optional = optional;
    }

    public Optional<T> getOptional() {
        return optional;
    }

    public static <T> CustomOptional<T> empty() {
        return new CustomOptional<>();
    }

    public static <T> CustomOptional<T> of(final T value) {
        return new CustomOptional<>(value);
    }

    public static <T> CustomOptional<T> ofNullable(final T value) {
        return (value == null) ? empty() : of(value);
    }

    public T get() {
        return optional.get();
    }

    public boolean isPresent() {
        return optional.isPresent();
    }

    public void ifPresent(final Consumer<? super T> consumer) {
        optional.ifPresent(consumer);
    }

    public CustomOptional<T> filter(final Predicate<? super T> predicate) {
        return new CustomOptional<>(optional.filter(predicate));
    }

    public <U> CustomOptional<U> map(final Function<? super T, ? extends U> mapper) {
        return new CustomOptional<>(optional.map(mapper));
    }

    public <U> CustomOptional<U> flatMap(final Function<? super T, ? extends CustomOptional<U>> mapper) {
        return new CustomOptional<>(optional.flatMap(mapper.andThen(cu -> cu.getOptional())));
    }

    public T orElse(final T other) {
        return optional.orElse(other);
    }

    public T orElseGet(final Supplier<? extends T> other) {
        return optional.orElseGet(other);
    }

    public <X extends Throwable> T orElseThrow(final Supplier<? extends X> exceptionSuppier) throws X {
        return optional.orElseThrow(exceptionSuppier);
    }

    public Stream<T> flatStream() {
        if (!optional.isPresent()) {
            return Stream.empty();
        }
        return Stream.of(get());
    }

    public T getTOrNull() {
        if (!optional.isPresent()) {
            return null;
        }
        return get();
    }

    @Override
    public boolean equals(final Object obj) {
        return optional.equals(obj);
    }

    @Override
    public int hashCode() {
        return optional.hashCode();
    }

    @Override
    public String toString() {
        return optional.toString();
    }
}

You will see that I added flatStream(), as here:

public Stream<T> flatStream() {
    if (!optional.isPresent()) {
        return Stream.empty();
    }
    return Stream.of(get());
}

Used as:

String result = Stream.of("a", "b", "c", "de", "fg", "hij")
        .map(this::resolve)
        .flatMap(CustomOptional::flatStream)
        .findFirst()
        .get();

You still will need to return a Stream<T> here, as you cannot return T, because if !optional.isPresent(), then T == null if you declare it such, but then your .flatMap(CustomOptional::flatStream) would attempt to add null to a stream and that is not possible.

As example:

public T getTOrNull() {
    if (!optional.isPresent()) {
        return null;
    }
    return get();
}

Used as:

String result = Stream.of("a", "b", "c", "de", "fg", "hij")
        .map(this::resolve)
        .map(CustomOptional::getTOrNull)
        .findFirst()
        .get();

Will now throw a NullPointerException inside the stream operations.

Conclusion

The method you used, is actually the best method.

ImportError: DLL load failed: The specified module could not be found

(I found this answer from a video: http://www.youtube.com/watch?v=xmvRF7koJ5E)

  1. Download msvcp71.dll and msvcr71.dll from the web.

  2. Save them to your C:\Windows\System32 folder.

  3. Save them to your C:\Windows\SysWOW64 folder as well (if you have a 64-bit operating system).

Now try running your code file in Python and it will load the graph in couple of seconds.

Tools to generate database tables diagram with Postgresql?

I love schemaspy for schema visualisations. Look at the sample output they provide, and drool. Note the tabs!

You'll need to download the JDBC driver here, then your command should look something like:

java -jar schemaspy-6.0.0-rc2.jar -t pgsql -db database_name -host myhost -u username -p password -o ./schemaspy -dp postgresql-9.3-1100.jdbc3.jar -s public -noads

Sometimes using options -port will not working if your database has diferrent port, so you have to add manual port after host parameter, for example:

java -jar schemaspy-6.0.0-rc2.jar -t pgsql -db database_name -host myhost:myport -u username -p password -o ./schemaspy -dp postgresql-9.3-1100.jdbc3.jar -s public -noads

You'll need to install graphviz as well if you want graphics (apt-get install graphviz for debian based distros).

What does double question mark (??) operator mean in PHP

It's the "null coalescing operator", added in php 7.0. The definition of how it works is:

It returns its first operand if it exists and is not NULL; otherwise it returns its second operand.

So it's actually just isset() in a handy operator.

Those two are equivalent1:

$foo = $bar ?? 'something';
$foo = isset($bar) ? $bar : 'something';

Documentation: http://php.net/manual/en/language.operators.comparison.php#language.operators.comparison.coalesce

In the list of new PHP7 features: http://php.net/manual/en/migration70.new-features.php#migration70.new-features.null-coalesce-op

And original RFC https://wiki.php.net/rfc/isset_ternary


EDIT: As this answer gets a lot of views, little clarification:

1There is a difference: In case of ??, the first expression is evaluated only once, as opposed to ? :, where the expression is first evaluated in the condition section, then the second time in the "answer" section.

"Bitmap too large to be uploaded into a texture"

Addition of the following 2 attributes in (AndroidManifest.xml) worked for me:

android:largeHeap="true"
android:hardwareAccelerated="false"

Rename multiple files in a folder, add a prefix (Windows)

Free Software 'Bulk Rename Utility' also works well (and is powerful for advanced tasks also). Download and installation takes a minute.

See screenshots and tutorial on original website.

--

I cannot provide step-by-step screenshots as the images will have to be released under Creative Commons License, and I do not own the screenshots of the software.

Disclaimer: I am not associated with the said software/company in any way. I liked the product for my own task, it serves OP's and similar requirements, thus recommending.

How to fix "containing working copy admin area is missing" in SVN?

I tried svn rm --force /path/to/dir to no avail but ended up just running svn up and it fixed it for me.

How to install pip for Python 3.6 on Ubuntu 16.10?

This answer assumes that you have python3.6 installed. For python3.7, replace 3.6 with 3.7. For python3.8, replace 3.6 with 3.8, but it may also first require the python3.8-distutils package.

Installation with sudo

With regard to installing pip, using curl (instead of wget) avoids writing the file to disk.

curl https://bootstrap.pypa.io/get-pip.py | sudo -H python3.6

The -H flag is evidently necessary with sudo in order to prevent errors such as the following when installing pip for an updated python interpreter:

The directory '/home/someuser/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

The directory '/home/someuser/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag.

Installation without sudo

curl https://bootstrap.pypa.io/get-pip.py | python3.6 - --user

This may sometimes give a warning such as:

WARNING: The script wheel is installed in '/home/ubuntu/.local/bin' which is not on PATH. Consider adding this directory to PATH or, if you prefer to suppress this warning, use --no-warn-script-location.

Verification

After this, pip, pip3, and pip3.6 can all be expected to point to the same target:

$ (pip -V && pip3 -V && pip3.6 -V) | uniq
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

Of course you can alternatively use python3.6 -m pip as well.

$ python3.6 -m pip -V
pip 18.0 from /usr/local/lib/python3.6/dist-packages (python 3.6)

How to disable an Android button?

first in xml make the button as android:clickable="false"

<Button
        android:id="@+id/btn_send"
        android:clickable="false"/>

then in your code, inside oncreate() method set the button property as

btn.setClickable(true);

then inside the button click change the code into

btn.setClickable(false);

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    btnSend = (Button) findViewById(R.id.btn_send);
    btnSend.setClickable(true);
    btnSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            btnSend.setClickable(false);

        }
    });
}

VBA vlookup reference in different sheet

Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.

To handle this case, try

Sub Demo()
    Dim MyStringVar1 As Variant
    On Error Resume Next
    MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
      Worksheets("Sheet1").Range("A:C"), 1, False)
    On Error GoTo 0
    If IsEmpty(MyStringVar1) Then
        MsgBox "Value not found!"
    End If

    Range("E2") = MyStringVar1

End Sub

Navigation Controller Push View Controller

    UIStoryboard* storyboard = [UIStoryboard storyboardWithName:@"storyBoardName" bundle:nil];
    MemberDetailsViewController* controller = [storyboard instantiateViewControllerWithIdentifier:@"viewControllerIdentiferInStoryBoard"];
[self.navigationController pushViewController:viewControllerName animated:YES];

Swift 4:

let storyBoard = UIStoryboard(name: "storyBoardName", bundle:nil)
let memberDetailsViewController = storyBoard.instantiateViewController(withIdentifier: "viewControllerIdentiferInStoryBoard") as! MemberDetailsViewController
self.navigationController?.pushViewController(memberDetailsViewController, animated:true)

Fatal error: Call to undefined function mb_detect_encoding()

Under Windows / WAMP there doesn't seem to be any php_mbstring.dll dependencies on the GD2 extension, the MySQL extensions, nor on external dlls/libs:

deplister.exe ext\php_mbstring.dll

php5ts.dll,OK
MSVCR110.dll,OK
KERNEL32.dll,OK

deplister.exe ext\php_gd2.dll

php5ts.dll,OK
USER32.dll,OK
GDI32.dll,OK
KERNEL32.dll,OK
MSVCR110.dll,OK

Whatever php_mbstring already needs, it's built-in (statically compiled right into the DLL).

Call to undefined function mb_detect_encoding()

This error is also very specific and deterministic...

The function mb_detect_encoding() didn't fail because php_gd, php_mysql, php_mysqli, or another extension was not loaded; it simply was NOT found.

I'm guessing that all the answers that are reported as valid (for Windows / WAMP), that say to load other extensions, to change php.ini extension_dir paths (if this one was wrong to begin with, NO extensions would load), etc, work more due to a) un-commenting the extension = php_mbstring.dll line, or b) restarting Apache or the computer (for changes to take effect).

On Windows, most of the time the problem is that php_mbstring.dll is either:

  • Blocked by Windows. Unblock it by right-clicking it, check Properties.

  • Or PHP can't load php_mbstring.dll due to another version getting loaded (e.g., from some improper PHP DLLs install into C:\Windows\system32), some version mismatch, missing run-time DLLs, etc. Check Apache's and PHP's error log files first for clues.

More in-depth answer here: Call to undefined function mb_detect_encoding

What is the best way to remove a table row with jQuery?

Is the following acceptable:

$('#myTableRow').remove();

AngularJS dynamic routing

I think the easiest way to do such thing is to resolve the routes later, you could ask the routes via json, for example. Check out that I make a factory out of the $routeProvider during config phase, via $provide, so I can keep using the $routeProvider object in the run phase, and even in controllers.

'use strict';

angular.module('myapp', []).config(function($provide, $routeProvider) {
    $provide.factory('$routeProvider', function () {
        return $routeProvider;
    });
}).run(function($routeProvider, $http) {
    $routeProvider.when('/', {
        templateUrl: 'views/main.html',
        controller: 'MainCtrl'
    }).otherwise({
        redirectTo: '/'
    });

    $http.get('/dynamic-routes.json').success(function(data) {
        $routeProvider.when('/', {
            templateUrl: 'views/main.html',
            controller: 'MainCtrl'
        });
        // you might need to call $route.reload() if the route changed
        $route.reload();
    });
});

Read CSV with Scanner()

Split nextLine() by this delimiter: (?=([^\"]*\"[^\"]*\")*[^\"]*$)").

How to find out what group a given user has?

This one shows the user's uid as well as all the groups (with their gids) they belong to

id userid

Error after upgrading pip: cannot import name 'main'

I'm running on a system where I have sudo apt but no sudo pip. (And no su access.) I got myself into this same situation by following the advice from pip:

You are using pip version 8.1.1, however 18.0 is available. You should consider upgrading via the 'pip install --upgrade pip' command.

None of the other fixes worked for me, because I don't have enough admin privileges. However, a few things stuck with me from reading up on this:

  • I shouldn't have done this. Sure, pip told me to. It lied.
  • Using --user solves a lot of issues by focusing on the user-only directory.

So, I found this command line to work to revert me back to where I was. If you were using a different version than 8.1.1, you will obviously want to change that part of the line.

python -m pip install --force-reinstall pip==8.1.1 --user

That's the only thing that worked for me, but it worked perfectly!

Difference between File.separator and slash in paths

Using File.separator made Ubuntu generate files with "\" on it's name instead of directories. Maybe I am being lazy with how I am making files(and directories) and could have avoided it, regardless, use "/" every time to avoid files with "\" on it's name

How can I style even and odd elements?

Below is the example of even and odd css color apply

<html>
<head>
<style> 
p:nth-child(even) {
    background: red;
}
p:nth-child(odd) {
    background: green;
}
</style>
</head>
<body>

<p>The first Odd.</p>
<p>The second Even.</p>
<p>The third Odd.</p>
<p>The fourth Even.</p>


</body>
</html>

How to loop through a JSON object with typescript (Angular2)

ECMAScript 6 introduced the let statement. You can use it in a for statement.

var ids:string = [];

for(let result of this.results){
   ids.push(result.Id);
}

Reading InputStream as UTF-8

Solved my own problem. This line:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream()));

needs to be:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"));

or since Java 7:

BufferedReader in = new BufferedReader(new InputStreamReader(url.openStream(), StandardCharsets.UTF_8));

How can I parse a string with a comma thousand separator to a number?

Removing commas is potentially dangerous because, as others have mentioned in the comments, many locales use a comma to mean something different (like a decimal place).

I don't know where you got your string from, but in some places in the world "2,299.00" = 2.299

The Intl object could have been a nice way to tackle this problem, but somehow they managed to ship the spec with only a Intl.NumberFormat.format() API and no parse counterpart :(

The only way to parse a string with cultural numeric characters in it to a machine recognisable number in any i18n sane way is to use a library that leverages CLDR data to cover off all possible ways of formatting number strings http://cldr.unicode.org/

The two best JS options I've come across for this so far:

Build .NET Core console application to output an EXE

Here's my hacky workaround - generate a console application (.NET Framework) that reads its own name and arguments, and then calls dotnet [nameOfExe].dll [args].

Of course this assumes that .NET is installed on the target machine.

Here's the code. Feel free to copy!

using System;
using System.Diagnostics;
using System.Text;

namespace dotNetLauncher
{
    class Program
    {
        /*
            If you make .NET Core applications, they have to be launched like .NET blah.dll args here
            This is a convenience EXE file that launches .NET Core applications via name.exe
            Just rename the output exe to the name of the .NET Core DLL file you wish to launch
        */
        static void Main(string[] args)
        {
            var exePath = AppDomain.CurrentDomain.BaseDirectory;
            var exeName = AppDomain.CurrentDomain.FriendlyName;
            var assemblyName = exeName.Substring(0, exeName.Length - 4);
            StringBuilder passInArgs = new StringBuilder();
            foreach(var arg in args)
            {
                bool needsSurroundingQuotes = false;
                if (arg.Contains(" ") || arg.Contains("\""))
                {
                    passInArgs.Append("\"");
                    needsSurroundingQuotes = true;
                }
                passInArgs.Append(arg.Replace("\"","\"\""));
                if (needsSurroundingQuotes)
                {
                    passInArgs.Append("\"");
                }

                passInArgs.Append(" ");
            }
            string callingArgs = $"\"{exePath}{assemblyName}.dll\" {passInArgs.ToString().Trim()}";

            var p = new Process
            {
                StartInfo = new ProcessStartInfo("dotnet", callingArgs)
                {
                    UseShellExecute = false
                }
            };

            p.Start();
            p.WaitForExit();
        }
    }
}

Copying files from server to local computer using SSH

Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r.

So here in your case it'd be something like

local> scp -r [email protected]:/path/to/dir local/path 

If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.

How to loop through file names returned by find?

Filenames can include spaces and even control characters. Spaces are (default) delimiters for shell expansion in bash and as a result of that x=$(find . -name "*.txt") from the question is not recommended at all. If find gets a filename with spaces e.g. "the file.txt" you will get 2 separated strings for processing, if you process x in a loop. You can improve this by changing delimiter (bash IFS Variable) e.g. to \r\n, but filenames can include control characters - so this is not a (completely) safe method.

From my point of view, there are 2 recommended (and safe) patterns for processing files:

1. Use for loop & filename expansion:

for file in ./*.txt; do
    [[ ! -e $file ]] && continue  # continue, if file does not exist
    # single filename is in $file
    echo "$file"
    # your code here
done

2. Use find-read-while & process substitution

while IFS= read -r -d '' file; do
    # single filename is in $file
    echo "$file"
    # your code here
done < <(find . -name "*.txt" -print0)

Remarks

on Pattern 1:

  1. bash returns the search pattern ("*.txt") if no matching file is found - so the extra line "continue, if file does not exist" is needed. see Bash Manual, Filename Expansion
  2. shell option nullglob can be used to avoid this extra line.
  3. "If the failglob shell option is set, and no matches are found, an error message is printed and the command is not executed." (from Bash Manual above)
  4. shell option globstar: "If set, the pattern ‘**’ used in a filename expansion context will match all files and zero or more directories and subdirectories. If the pattern is followed by a ‘/’, only directories and subdirectories match." see Bash Manual, Shopt Builtin
  5. other options for filename expansion: extglob, nocaseglob, dotglob & shell variable GLOBIGNORE

on Pattern 2:

  1. filenames can contain blanks, tabs, spaces, newlines, ... to process filenames in a safe way, find with -print0 is used: filename is printed with all control characters & terminated with NUL. see also Gnu Findutils Manpage, Unsafe File Name Handling, safe File Name Handling, unusual characters in filenames. See David A. Wheeler below for detailed discussion of this topic.

  2. There are some possible patterns to process find results in a while loop. Others (kevin, David W.) have shown how to do this using pipes:

    files_found=1
    find . -name "*.txt" -print0 | 
       while IFS= read -r -d '' file; do
           # single filename in $file
           echo "$file"
           files_found=0   # not working example
           # your code here
       done
    [[ $files_found -eq 0 ]] && echo "files found" || echo "no files found"
    

    When you try this piece of code, you will see, that it does not work: files_found is always "true" & the code will always echo "no files found". Reason is: each command of a pipeline is executed in a separate subshell, so the changed variable inside the loop (separate subshell) does not change the variable in the main shell script. This is why I recommend using process substitution as the "better", more useful, more general pattern.
    See I set variables in a loop that's in a pipeline. Why do they disappear... (from Greg's Bash FAQ) for a detailed discussion on this topic.

Additional References & Sources:

How can I add an empty directory to a Git repository?

Maybe adding an empty directory seems like it would be the path of least resistance because you have scripts that expect that directory to exist (maybe because it is a target for generated binaries). Another approach would be to modify your scripts to create the directory as needed.

mkdir --parents .generated/bin ## create a folder for storing generated binaries
mv myprogram1 myprogram2 .generated/bin ## populate the directory as needed

In this example, you might check in a (broken) symbolic link to the directory so that you can access it without the ".generated" prefix (but this is optional).

ln -sf .generated/bin bin
git add bin

When you want to clean up your source tree you can just:

rm -rf .generated ## this should be in a "clean" script or in a makefile

If you take the oft-suggested approach of checking in an almost-empty folder, you have the minor complexity of deleting the contents without also deleting the ".gitignore" file.

You can ignore all of your generated files by adding the following to your root .gitignore:

.generated

Drawable-hdpi, Drawable-mdpi, Drawable-ldpi Android

To declare different layouts and bitmaps you'd like to use for the different screens, you must place these alternative resources in separate directories/folders.

This means that if you generate a 200x200 image for xhdpi devices, you should generate the same resource in 150x150 for hdpi, 100x100 for mdpi, and 75x75 for ldpi devices.

Then, place the files in the appropriate drawable resource directory:

MyProject/
    res/
        drawable-xhdpi/
            awesomeimage.png
        drawable-hdpi/
            awesomeimage.png
        drawable-mdpi/
            awesomeimage.png
        drawable-ldpi/
            awesomeimage.png

Any time you reference @drawable/awesomeimage, the system selects the appropriate bitmap based on the screen's density.

T-SQL How to create tables dynamically in stored procedures?

You will need to build that CREATE TABLE statement from the inputs and then execute it.

A simple example:

declare @cmd nvarchar(1000), @TableName nvarchar(100);

set @TableName = 'NewTable';

set @cmd = 'CREATE TABLE dbo.' + quotename(@TableName, '[') + '(newCol int not null);';

print @cmd;

--exec(@cmd);

SQL : BETWEEN vs <= and >=

Disclaimer: Everything below is only anecdotal and drawn directly from my personal experience. Anyone that feels up to conducting a more empirically rigorous analysis is welcome to carry it out and down vote if I'm. I am also aware that SQL is a declarative language and you're not supposed to have to consider HOW your code is processed when you write it, but, because I value my time, I do.

There are infinite logically equivalent statements, but I'll consider three(ish).

Case 1: Two Comparisons in a standard order (Evaluation order fixed)

A >= MinBound AND A <= MaxBound

Case 2: Syntactic sugar (Evaluation order is not chosen by author)

A BETWEEN MinBound AND MaxBound

Case 3: Two Comparisons in an educated order (Evaluation order chosen at write time)

A >= MinBound AND A <= MaxBound

Or

A <= MaxBound AND A >= MinBound

In my experience, Case 1 and Case 2 do not have any consistent or notable differences in performance as they are dataset ignorant.

However, Case 3 can greatly improve execution times. Specifically, if you're working with a large data set and happen to have some heuristic knowledge about whether A is more likely to be greater than the MaxBound or lesser than the MinBound you can improve execution times noticeably by using Case 3 and ordering the comparisons accordingly.

One use case I have is querying a large historical dataset with non-indexed dates for records within a specific interval. When writing the query, I will have a good idea of whether or not more data exists BEFORE the specified interval or AFTER the specified interval and can order my comparisons accordingly. I've had execution times cut by as much as half depending on the size of the dataset, the complexity of the query, and the amount of records filtered by the first comparison.

Get Context in a Service

Since Service is a Context, the variable context must be this:

DataBaseManager dbm = Utils.getDataManager(this);   

Java string split with "." (dot)

The dot "." is a special character in java regex engine, so you have to use "\\." to escape this character:

final String extensionRemoved = filename.split("\\.")[0];

I hope this helps

Insert line at middle of file with Python?

You don't show us what the output should look like, so one possible interpretation is that you want this as the output:

  1. Alfred
  2. Bill
  3. Charlie
  4. Donald

(Insert Charlie, then add 1 to all subsequent lines.) Here's one possible solution:

def insert_line(input_stream, pos, new_name, output_stream):
  inserted = False
  for line in input_stream:
    number, name = parse_line(line)
    if number == pos:
      print >> output_stream, format_line(number, new_name)
      inserted = True
    print >> output_stream, format_line(number if not inserted else (number + 1), name)

def parse_line(line):
  number_str, name = line.strip().split()
  return (get_number(number_str), name)

def get_number(number_str):
  return int(number_str.split('.')[0])

def format_line(number, name):
  return add_dot(number) + ' ' + name

def add_dot(number):
  return str(number) + '.'

input_stream = open('input.txt', 'r')
output_stream = open('output.txt', 'w')

insert_line(input_stream, 3, 'Charlie', output_stream)

input_stream.close()
output_stream.close()

Difference in days between two dates in Java?

Illustration of the problem: (My code is computing delta in weeks, but same issue applies with delta in days)

Here is a very reasonable-looking implementation:

public static final long MILLIS_PER_WEEK = 7L * 24L * 60L * 60L * 1000L;

static public int getDeltaInWeeks(Date latterDate, Date earlierDate) {
    long deltaInMillis = latterDate.getTime() - earlierDate.getTime();
    int deltaInWeeks = (int)(deltaInMillis / MILLIS_PER_WEEK);
    return deltaInWeeks; 
}

But this test will fail:

public void testGetDeltaInWeeks() {
    delta = AggregatedData.getDeltaInWeeks(dateMar09, dateFeb23);
    assertEquals("weeks between Feb23 and Mar09", 2, delta);
}

The reason is:

Mon Mar 09 00:00:00 EDT 2009 = 1,236,571,200,000
Mon Feb 23 00:00:00 EST 2009 = 1,235,365,200,000
MillisPerWeek = 604,800,000
Thus,
(Mar09 - Feb23) / MillisPerWeek =
1,206,000,000 / 604,800,000 = 1.994...

but anyone looking at a calendar would agree that the answer is 2.

Node.js: Python not found exception due to node-sass and node-gyp

I had node 15.x.x , and "node-sass": "^4.11.0". I saw in the release notes from node-sass and saw the node higest version compatible with node-sass 4.11.0 was 11, so I uninstalled node and reinstall 11.15.0 version (I'm working with Windows). Check node-sass releases. (this is what you should see in the node-sass releases.)

Hope that helps and sorry for my english :)

Bootstrap 3 breakpoints and media queries

for bootstrap 3 I have the following code in my navbar component

/**
 * Navbar styling.
 */
@mobile:          ~"screen and (max-width: @{screen-xs-max})";
@tablet:          ~"screen and (min-width: @{screen-sm-min})";
@normal:          ~"screen and (min-width: @{screen-md-min})";
@wide:            ~"screen and (min-width: @{screen-lg-min})";
@grid-breakpoint: ~"screen and (min-width: @{grid-float-breakpoint})";

then you can use something like

@media wide { selector: style }

This uses whatever value you have the variables set to.

Escaping allows you to use any arbitrary string as property or variable value. Anything inside ~"anything" or ~'anything' is used as is with no changes except interpolation.

http://lesscss.org

How to hide a column (GridView) but still access its value?

You can do it code behind.

Set visible= false for columns after data binding . After that you can again do visibility "true" in row_selection function from grid view .It will work!!

What is the size of ActionBar in pixels?

To retrieve the height of the ActionBar in XML, just use

?android:attr/actionBarSize

or if you're an ActionBarSherlock or AppCompat user, use this

?attr/actionBarSize

If you need this value at runtime, use this

final TypedArray styledAttributes = getContext().getTheme().obtainStyledAttributes(
                    new int[] { android.R.attr.actionBarSize });
mActionBarSize = (int) styledAttributes.getDimension(0, 0);
styledAttributes.recycle();

If you need to understand where this is defined:

  1. The attribute name itself is defined in the platform's /res/values/attrs.xml
  2. The platform's themes.xml picks this attribute and assigns a value to it.
  3. The value assigned in step 2 depends on different device sizes, which are defined in various dimens.xml files in the platform, ie. core/res/res/values-sw600dp/dimens.xml

How to kill a thread instantly in C#?

thread will be killed when it finish it's work, so if you are using loops or something else you should pass variable to the thread to stop the loop after that the thread will be finished.

XAMPP Start automatically on Windows 7 startup

Go to the Config button (up right) and select the Autostart for Apache.enter image description here

Move to another EditText when Soft Keyboard Next is clicked on Android

Try Using android:imeOptions="actionNext" tag for every editText in the View it will automatically focus to the next edittext when you click on Next of the softKeyboard.

How do I get the HTTP status code with jQuery?

this is possible with jQuery $.ajax() method

$.ajax(serverUrl, {
   type: OutageViewModel.Id() == 0 ? "POST" : "PUT",
   data: dataToSave,
   statusCode: {
      200: function (response) {
         alert('1');
         AfterSavedAll();
      },
      201: function (response) {
         alert('1');
         AfterSavedAll();
      },
      400: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      },
      404: function (response) {
         alert('1');
         bootbox.alert('<span style="color:Red;">Error While Saving Outage Entry Please Check</span>', function () { });
      }
   }, success: function () {
      alert('1');
   },
});

What does "dereferencing" a pointer mean?

A pointer is a "reference" to a value.. much like a library call number is a reference to a book. "Dereferencing" the call number is physically going through and retrieving that book.

int a=4 ;
int *pA = &a ;
printf( "The REFERENCE/call number for the variable `a` is %p\n", pA ) ;

// The * causes pA to DEREFERENCE...  `a` via "callnumber" `pA`.
printf( "%d\n", *pA ) ; // prints 4.. 

If the book isn't there, the librarian starts shouting, shuts the library down, and a couple of people are set to investigate the cause of a person going to find a book that isn't there.

Why not use Double or Float to represent currency?

Most answers have highlighted the reasons why one should not use doubles for money and currency calculations. And I totally agree with them.

It doesn't mean though that doubles can never be used for that purpose.

I have worked on a number of projects with very low gc requirements, and having BigDecimal objects was a big contributor to that overhead.

It's the lack of understanding about double representation and lack of experience in handling the accuracy and precision that brings about this wise suggestion.

You can make it work if you are able to handle the precision and accuracy requirements of your project, which has to be done based on what range of double values is one dealing with.

You can refer to guava's FuzzyCompare method to get more idea. The parameter tolerance is the key. We dealt with this problem for a securities trading application and we did an exhaustive research on what tolerances to use for different numerical values in different ranges.

Also, there might be situations when you're tempted to use Double wrappers as a map key with hash map being the implementation. It is very risky because Double.equals and hash code for example values "0.5" & "0.6 - 0.1" will cause a big mess.

How to get Database Name from Connection String using SqlConnectionStringBuilder

See MSDN documentation for InitialCatalog Property:

Gets or sets the name of the database associated with the connection...

This property corresponds to the "Initial Catalog" and "database" keys within the connection string...

Git merge reports "Already up-to-date" though there is a difference

This often happens to me when I know there are changes on the remote master, so I try to merge them using git merge master. However, this doesn't merge with the remote master, but with your local master.

So before doing the merge, checkout master, and then git pull there. Then you will be able to merge the new changes into your branch.

javascript Unable to get property 'value' of undefined or null reference

The issue is how you're attempting to get the value. Things like...

if ( document.frm_new_user_request.u_isid.value == '' )

won't work. You need to find the element you want to get the value of first. It's not quite like a server side language where you can type in an object's reference name and a period to get or assign values.

document.getElementById('[id goes here]').value;

will work. Note: JavaScript is case-sensitive

I would recommend using:

var variablename = document.getElementById('[id goes here]');

or

var variablename = document.getElementById('[id goes here]').value;

Add a thousands separator to a total with Javascript or jQuery?

Use toLocaleString()
In your case do:

return "Total Pounds Entered : " + tot.toLocaleString(); 

Difference between float and decimal data type

mysql> CREATE TABLE num(id int ,fl float,dc dec(5,2));
Query OK, 0 rows affected (0.00 sec)


mysql> INSERT INTO num VALUES(1,13.75,13.75);
Query OK, 1 row affected (0.00 sec)

mysql> INSERT INTO num VALUES(2,13.15,13.15);
Query OK, 1 row affected (0.00 sec)

mysql> SELECT * FROM num WHERE fl = 13.15;
Empty set (0.00 sec)

mysql> SELECT * FROM num WHERE dc = 13.15;
+------+-------+-------+
| id   | fl    | dc    |
+------+-------+-------+
|    2 | 13.15 | 13.15 |
+------+-------+-------+
1 row in set (0.00 sec)

mysql> SELECT SUM(fl) ,SUM(dc)  FROM num;
+--------------------+---------+
| SUM(fl)            | SUM(dc) |
+--------------------+---------+
| 26.899999618530273 |   26.90 |
+--------------------+---------+
1 row in set (0.00 sec)


mysql> SELECT * FROM num WHERE ABS(fl -  13.15)<0.01;
+------+-------+-------+
| id   | fl    | dc    |
+------+-------+-------+
|    2 | 13.15 | 13.15 |
+------+-------+-------+
1 row in set (0.00 sec)

How to get a subset of a javascript object's properties

I am adding this answer because none of the answer used Comma operator.

It's very easy with destructuring assignment and , operator

_x000D_
_x000D_
const object = { a: 5, b: 6, c: 7  };
const picked = ({a,c} = object, {a,c})

console.log(picked);
_x000D_
_x000D_
_x000D_

What range of values can integer types store in C++

The size of the numerical types is not defined in the C++ standard, although the minimum sizes are. The way to tell what size they are on your platform is to use numeric limits

For example, the maximum value for a int can be found by:

std::numeric_limits<int>::max();

Computers don't work in base 10, which means that the maximum value will be in the form of 2n-1 because of how the numbers of represent in memory. Take for example eight bits (1 byte)

  0100 1000

The right most bit (number) when set to 1 represents 20, the next bit 21, then 22 and so on until we get to the left most bit which if the number is unsigned represents 27.

So the number represents 26 + 23 = 64 + 8 = 72, because the 4th bit from the right and the 7th bit right the left are set.

If we set all values to 1:

11111111

The number is now (assuming unsigned)
128 + 64 + 32 + 16 + 8 + 4 + 2 + 1 = 255 = 28 - 1
And as we can see, that is the largest possible value that can be represented with 8 bits.

On my machine and int and a long are the same, each able to hold between -231 to 231 - 1. In my experience the most common size on modern 32 bit desktop machine.

Javascript-Setting background image of a DIV via a function and function parameter

You need to concatenate your string.

document.getElementById(tabName).style.backgroundImage = 'url(buttons/' + imagePrefix + '.png)';

The way you had it, it's just making 1 long string and not actually interpreting imagePrefix.

I would even suggest creating the string separate:

function ChangeBackgroungImageOfTab(tabName, imagePrefix)
{
    var urlString = 'url(buttons/' + imagePrefix + '.png)';
    document.getElementById(tabName).style.backgroundImage =  urlString;
}

As mentioned by David Thomas below, you can ditch the double quotes in your string. Here is a little article to get a better idea of how strings and quotes/double quotes are related: http://www.quirksmode.org/js/strings.html

How to generate Javadoc HTML files in Eclipse?

You can also do it from command line much easily.

  1. Open command line from the folder/package.
  2. From command line run:

    javadoc YourClassName.java

  3. To batch generate docs for multiple Class:

    javadoc *.java

CSS: How to align vertically a "label" and "input" inside a "div"?

Use padding on the div (top and bottom) and vertical-align:middle on the label and input.

example at http://jsfiddle.net/VLFeV/1/

Concatenating strings doesn't work as expected

std::string a = "Hello ";
a += "World";

How do I make a dotted/dashed line in Android?

I liked the solution from Ruidge, but I needed more control from XML. So I changed it to Kotlin and added attributes.

1) Copy the Kotlin class:

import android.content.Context
import android.graphics.*
import android.util.AttributeSet
import android.view.View

class DashedDividerView : View {
constructor(context: Context) : this(context, null, 0)
constructor(context: Context, attributeSet: AttributeSet) : this(context, attributeSet, 0)

companion object {
    const val DIRECTION_VERTICAL = 0
    const val DIRECTION_HORIZONTAL = 1
}

private var dGap = 5.25f
private var dWidth = 5.25f
private var dColor = Color.parseColor("#EE0606")
private var direction = DIRECTION_HORIZONTAL
private val paint = Paint()
private val path = Path()

constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int) : super(
    context,
    attrs,
    defStyleAttr
) {
    val typedArray = context.obtainStyledAttributes(
        attrs,
        R.styleable.DashedDividerView,
        defStyleAttr,
        R.style.DashedDividerDefault
    )

    dGap = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashGap, dGap)
    dWidth = typedArray.getDimension(R.styleable.DashedDividerView_dividerDashWidth, dWidth)
    dColor = typedArray.getColor(R.styleable.DashedDividerView_dividerDashColor, dColor)
    direction =
        typedArray.getInt(R.styleable.DashedDividerView_dividerDirection, DIRECTION_HORIZONTAL)

    paint.color = dColor
    paint.style = Paint.Style.STROKE
    paint.pathEffect = DashPathEffect(floatArrayOf(dWidth, dGap), 0f)
    paint.strokeWidth = dWidth

    typedArray.recycle()
}

override fun onDraw(canvas: Canvas) {
    super.onDraw(canvas)
    path.moveTo(0f, 0f)

    if (direction == DIRECTION_HORIZONTAL) {
        path.lineTo(measuredWidth.toFloat(), 0f)
    } else {
        path.lineTo(0f, measuredHeight.toFloat())
    }
    canvas.drawPath(path, paint)
}

}

2) Create an attr file in the /res directory and add this

 <declare-styleable name="DashedDividerView">
    <attr name="dividerDashGap" format="dimension" />
    <attr name="dividerDashWidth" format="dimension" />
    <attr name="dividerDashColor" format="reference|color" />
    <attr name="dividerDirection" format="enum">
        <enum name="vertical" value="0" />
        <enum name="horizontal" value="1" />
    </attr>
</declare-styleable>

3) Add a style to the styles file

 <style name="DashedDividerDefault">
    <item name="dividerDashGap">2dp</item>
    <item name="dividerDashWidth">2dp</item>
    <!-- or any color -->
    <item name="dividerDashColor">#EE0606</item>
    <item name="dividerDirection">horizontal</item>
</style>

4) Now you can use the default style

<!-- here will be your path to the class -->
<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    />

or set attributes in XML

<com.your.package.app.DashedDividerView
    android:layout_width="match_parent"
    android:layout_height="2dp"
    app:dividerDirection="horizontal"
    app:dividerDashGap="2dp"
    app:dividerDashWidth="2dp"
    app:dividerDashColor="@color/light_gray"/>

How can I set the opacity or transparency of a Panel in WinForms?

Yes, opacity can only work on top-level windows. It uses a hardware feature of the video adapter, that doesn't support child windows, like Panel. The only top-level Control derived class in Winforms is Form.

Several of the 'pure' Winform controls, the ones that do their own painting instead of letting a native Windows control do the job, do however support a transparent BackColor. Panel is one of them. It uses a trick, it asks the Parent to draw itself to produce the background pixels. One side-effect of this trick is that overlapping controls doesn't work, you only see the parent pixels, not the overlapped controls.

This sample form shows it at work:

public partial class Form1 : Form {
    public Form1() {
        InitializeComponent();
        this.BackColor = Color.White;
        panel1.BackColor = Color.FromArgb(25, Color.Black);
    }
    protected override void OnPaint(PaintEventArgs e) {
        e.Graphics.DrawLine(Pens.Yellow, 0, 0, 100, 100);
    }
}

If that's not good enough then you need to consider stacking forms on top of each other. Like this.

Notable perhaps is that this restriction is lifted in Windows 8. It no longer uses the video adapter overlay feature and DWM (aka Aero) cannot be turned off anymore. Which makes opacity/transparency on child windows easy to implement. Relying on this is of course future-music for a while to come. Windows 7 will be the next XP :)

Variably modified array at file scope

It is also possible to use enumeration.

typedef enum {
    typeNo1 = 1,
    typeNo2,
    typeNo3,
    typeNo4,
    NumOfTypes = typeNo4
}  TypeOfSomething;

Is there a CSS selector by class prefix?

This is not possible with CSS selectors. But you could use two classes instead of one, e.g. status and important instead of status-important.

Extract a page from a pdf as a jpeg

GhostScript performs much faster than Poppler for a Linux based system.

Following is the code for pdf to image conversion.

def get_image_page(pdf_file, out_file, page_num):
    page = str(page_num + 1)
    command = ["gs", "-q", "-dNOPAUSE", "-dBATCH", "-sDEVICE=png16m", "-r" + str(RESOLUTION), "-dPDFFitPage",
               "-sOutputFile=" + out_file, "-dFirstPage=" + page, "-dLastPage=" + page,
               pdf_file]
    f_null = open(os.devnull, 'w')
    subprocess.call(command, stdout=f_null, stderr=subprocess.STDOUT)

GhostScript can be installed on macOS using brew install ghostscript

Installation information for other platforms can be found here. If it is not already installed on your system.

What is the difference between %g and %f in C?

As Unwind points out f and g provide different default outputs.

Roughly speaking if you care more about the details of what comes after the decimal point I would do with f and if you want to scale for large numbers go with g. From some dusty memories f is very nice with small values if your printing tables of numbers as everything stays lined up but something like g is needed if you stand a change of your numbers getting large and your layout matters. e is more useful when your numbers tend to be very small or very large but never near ten.

An alternative is to specify the output format so that you get the same number of characters representing your number every time.

Sorry for the woolly answer but it is a subjective out put thing that only gets hard answers if the number of characters generated is important or the precision of the represented value.

Return outside function error in Python

You have a return statement that isn't in a function. Functions are started by the def keyword:

def function(argument):
    return "something"

print function("foo")  #prints "something"

return has no meaning outside of a function, and so python raises an error.

How to import csv file in PHP?

$row = 1;
    $arrResult  = array();
    if (($handle = fopen("ifsc_code.csv", "r")) !== FALSE) {
        while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
            $num = count($data);
            DB::table('banks')->insert(
                array('bank_name' => $data[1], 'ifsc' => $data[2], 'micr' => $data[3], 'branch_name' => $data[4],'address' => $data[5], 'contact' => $data[6], 'city' => $data[7],'district' => $data[8],'state' => $data[9])
            );
        }
        fclose($handle);
    }

TensorFlow ValueError: Cannot feed value of shape (64, 64, 3) for Tensor u'Placeholder:0', which has shape '(?, 64, 64, 3)'

image has a shape of (64,64,3).

Your input placeholder _x have a shape of (?, 64,64,3).

The problem is that you're feeding the placeholder with a value of a different shape.

You have to feed it with a value of (1, 64, 64, 3) = a batch of 1 image.

Just reshape your image value to a batch with size one.

image = array(img).reshape(1, 64,64,3)

P.S: the fact that the input placeholder accepts a batch of images, means that you can run predicions for a batch of images in parallel. You can try to read more than 1 image (N images) and than build a batch of N image, using a tensor with shape (N, 64,64,3)

creating batch script to unzip a file without additional zip tools

Another approach to this issue could be to create a self extracting executable (.exe) using something like winzip and use this as the install vector rather than the zip file. Similarly, you could use NSIS to create an executable installer and use that instead of the zip.

How many socket connections can a web server handle?

This question is a fairly difficult one. There is no real software limitation on the number of active connections a machine can have, though some OS's are more limited than others. The problem becomes one of resources. For example, let's say a single machine wants to support 64,000 simultaneous connections. If the server uses 1MB of RAM per connection, it would need 64GB of RAM. If each client needs to read a file, the disk or storage array access load becomes much larger than those devices can handle. If a server needs to fork one process per connection then the OS will spend the majority of its time context switching or starving processes for CPU time.

The C10K problem page has a very good discussion of this issue.

Java - How to convert type collection into ArrayList?

As other people have mentioned, ArrayList has a constructor that takes a collection of items, and adds all of them. Here's the documentation:

http://java.sun.com/javase/6/docs/api/java/util/ArrayList.html#ArrayList%28java.util.Collection%29

So you need to do:

ArrayList<MyNode> myNodeList = new ArrayList<MyNode>(this.getVertices());

However, in another comment you said that was giving you a compiler error. It looks like your class MyGraph is a generic class. And so getVertices() actually returns type V, not type myNode.

I think your code should look like this:

public V getNode(int nodeId){
        ArrayList<V> myNodeList = new ArrayList<V>(this.getVertices());
        return myNodeList(nodeId);
}

But, that said it's a very inefficient way to extract a node. What you might want to do is store the nodes in a binary tree, then when you get a request for the nth node, you do a binary search.

Ctrl+click doesn't work in Eclipse Juno

I'm having the same issue in Eclipse Luna in my Ubuntu VM, but I just tried to Ctrl+click on a method and it worked (even though my mouse cursor didn't change to a pointer).

Path to MSBuild

This works for Visual Studio 2015 and 2017:

function Get-MSBuild-Path {

    $vs14key = "HKLM:\SOFTWARE\Microsoft\MSBuild\ToolsVersions\14.0"
    $vs15key = "HKLM:\SOFTWARE\wow6432node\Microsoft\VisualStudio\SxS\VS7"

    $msbuildPath = ""

    if (Test-Path $vs14key) {
        $key = Get-ItemProperty $vs14key
        $subkey = $key.MSBuildToolsPath
        if ($subkey) {
            $msbuildPath = Join-Path $subkey "msbuild.exe"
        }
    }

    if (Test-Path $vs15key) {
        $key = Get-ItemProperty $vs15key
        $subkey = $key."15.0"
        if ($subkey) {
            $msbuildPath = Join-Path $subkey "MSBuild\15.0\bin\amd64\msbuild.exe"
        }
    }

    return $msbuildPath

}

How to set an environment variable from a Gradle build?

This one is working for me for settings environment variable for the test plugin

test {
    systemProperties = [
        'catalina.home': 'c:/test'
    ]
    println "Starting Tests"
    beforeTest { descriptor ->
       logger.lifecycle("Running test: " + descriptor)                
    }    
}

How do I fix the Visual Studio compile error, "mismatch between processor architecture"?

In addition to David Sacks answer, you may also need to go to the Build tab of the Project Properties and set Platform Target to x86 for the project that is giving you these warnings. Though you might expect it to be, this setting does not seem to be perfectly synchronized with the setting in the configuration manager.

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

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

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

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

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

How to join two sets in one line without using "|"

You could use or_ alias:

>>> from operator import or_
>>> from functools import reduce # python3 required
>>> reduce(or_, [{1, 2, 3, 4}, {3, 4, 5, 6}])
set([1, 2, 3, 4, 5, 6])

What is the difference between function and procedure in PL/SQL?

In the few words - function returns something. You can use function in SQL query. Procedure is part of code to do something with data but you can not invoke procedure from query, you have to run it in PL/SQL block.

How do you run a js file using npm scripts?

You should use npm run-script build or npm build <project_folder>. More info here: https://docs.npmjs.com/cli/build.

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

There's a lot of functionality you can get from the Random class.

Below are some extension methods I use from time to time. With these, in addition to Next and NextDouble, the Random class gives you NextBool, NextChar, NextDateTime, NextTimeSpan, NextDouble (accepting minValue and maxValue parameters), and my personal favorite: NextString. There are more (NextByte, NextShort, NextLong, etc.); but those are mostly for completeness and don't get used as much. So I didn't include them here (this code is long enough as it is!).

// todo: implement additional CharType values (e.g., AsciiAny)
public enum CharType {
    AlphabeticLower,
    AlphabeticUpper,
    AlphabeticAny,
    AlphanumericLower,
    AlphanumericUpper,
    AlphanumericAny,
    Numeric
}

public static class RandomExtensions {
    // 10 digits vs. 52 alphabetic characters (upper & lower);
    // probability of being numeric: 10 / 62 = 0.1612903225806452
    private const double AlphanumericProbabilityNumericAny = 10.0 / 62.0;

    // 10 digits vs. 26 alphabetic characters (upper OR lower);
    // probability of being numeric: 10 / 36 = 0.2777777777777778
    private const double AlphanumericProbabilityNumericCased = 10.0 / 36.0;

    public static bool NextBool(this Random random, double probability) {
        return random.NextDouble() <= probability;
    }

    public static bool NextBool(this Random random) {
        return random.NextDouble() <= 0.5;
    }

    public static char NextChar(this Random random, CharType mode) {
        switch (mode) {
            case CharType.AlphabeticAny:
                return random.NextAlphabeticChar();
            case CharType.AlphabeticLower:
                return random.NextAlphabeticChar(false);
            case CharType.AlphabeticUpper:
                return random.NextAlphabeticChar(true);
            case CharType.AlphanumericAny:
                return random.NextAlphanumericChar();
            case CharType.AlphanumericLower:
                return random.NextAlphanumericChar(false);
            case CharType.AlphanumericUpper:
                return random.NextAlphanumericChar(true);
            case CharType.Numeric:
                return random.NextNumericChar();
            default:
                return random.NextAlphanumericChar();
        }
    }

    public static char NextChar(this Random random) {
        return random.NextChar(CharType.AlphanumericAny);
    }

    private static char NextAlphanumericChar(this Random random, bool uppercase) {
        bool numeric = random.NextBool(AlphanumericProbabilityNumericCased);

        if (numeric)
            return random.NextNumericChar();
        else
            return random.NextAlphabeticChar(uppercase);
    }

    private static char NextAlphanumericChar(this Random random) {
        bool numeric = random.NextBool(AlphanumericProbabilityNumericAny);

        if (numeric)
            return random.NextNumericChar();
        else
            return random.NextAlphabeticChar(random.NextBool());
    }

    private static char NextAlphabeticChar(this Random random, bool uppercase) {
        if (uppercase)
            return (char)random.Next(65, 91);
        else
            return (char)random.Next(97, 123);
    }

    private static char NextAlphabeticChar(this Random random) {
        return random.NextAlphabeticChar(random.NextBool());
    }

    private static char NextNumericChar(this Random random) {
        return (char)random.Next(48, 58);
    }

    public static DateTime NextDateTime(this Random random, DateTime minValue, DateTime maxValue) {
        return DateTime.FromOADate(
            random.NextDouble(minValue.ToOADate(), maxValue.ToOADate())
        );
    }

    public static DateTime NextDateTime(this Random random) {
        return random.NextDateTime(DateTime.MinValue, DateTime.MaxValue);
    }

    public static double NextDouble(this Random random, double minValue, double maxValue) {
        if (maxValue < minValue)
            throw new ArgumentException("Minimum value must be less than maximum value.");

        double difference = maxValue - minValue;
        if (!double.IsInfinity(difference))
            return minValue + (random.NextDouble() * difference);

        else {
            // to avoid evaluating to Double.Infinity, we split the range into two halves:
            double halfDifference = (maxValue * 0.5) - (minValue * 0.5);

            // 50/50 chance of returning a value from the first or second half of the range
            if (random.NextBool())
                return minValue + (random.NextDouble() * halfDifference);
            else
                return (minValue + halfDifference) + (random.NextDouble() * halfDifference);
        }
    }

    public static string NextString(this Random random, int numChars, CharType mode) {
        char[] chars = new char[numChars];

        for (int i = 0; i < numChars; ++i)
            chars[i] = random.NextChar(mode);

        return new string(chars);
    }

    public static string NextString(this Random random, int numChars) {
        return random.NextString(numChars, CharType.AlphanumericAny);
    }

    public static TimeSpan NextTimeSpan(this Random random, TimeSpan minValue, TimeSpan maxValue) {
        return TimeSpan.FromMilliseconds(
            random.NextDouble(minValue.TotalMilliseconds, maxValue.TotalMilliseconds)
        );
    }

    public static TimeSpan NextTimeSpan(this Random random) {
        return random.NextTimeSpan(TimeSpan.MinValue, TimeSpan.MaxValue);
    }
}

How to compare arrays in JavaScript?

While this only works for scalar arrays (see note below), it is short:

array1.length === array2.length && array1.every(function(value, index) { return value === array2[index]})

Rr, in ECMAScript 6 / CoffeeScript / TypeScript with Arrow Functions:

array1.length === array2.length && array1.every((value, index) => value === array2[index])

(Note: 'scalar' here means values that can be compared directly using === . So: numbers, strings, objects by reference, functions by reference. See the MDN reference for more info about the comparison operators).

UPDATE

From what I read from the comments, sorting the array and comparing may give accurate result:

const array2Sorted = array2.slice().sort();
array1.length === array2.length && array1.slice().sort().every(function(value, index) {
    return value === array2Sorted[index];
});

Eg:

array1 = [2,3,1,4];
array2 = [1,2,3,4];

Then the above code would give true

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Broken references in Virtualenvs

I recently faced this. None of the above solutions worked for me. Seems it wasn't actually Python's problem. When I was running

aws s3 ls

I was getting following error:

dyld: Library not loaded: @executable_path/../.Python

This means, the library aws executable is pointing towards is either doesn't exist or is corrupted, thus I uninstalled and reinstalled aws-cli following instructions from this link and it worked!!

Redirecting to another page in ASP.NET MVC using JavaScript/jQuery

You can use:

window.location.href = '/Branch/Details/' + id;

But your Ajax code is incomplete without success or error functions.

How to give a time delay of less than one second in excel vba?

No answer helped me, so I build this.

'   function Timestamp return current time in milliseconds.
'   compatible with JSON or JavaScript Date objects.

Public Function Timestamp () As Currency
    timestamp = (Round(Now(), 0) * 24 * 60 * 60 + Timer()) * 1000
End Function

'   function Sleep let system execute other programs while the milliseconds are not elapsed.

Public Function Sleep(milliseconds As Currency)

    If milliseconds < 0 Then Exit Function

    Dim start As Currency
    start = Timestamp ()

    While (Timestamp () < milliseconds + start)
        DoEvents
    Wend
End Function

Note : In Excel 2007, Now() send Double with decimals to seconds, so i use Timer() to get milliseconds.

Note : Application.Wait() accept seconds and no under (i.e. Application.Wait(Now()) ? Application.Wait(Now()+100*millisecond)))

Note : Application.Wait() doesn't let system execute other program but hardly reduce performance. Prefer usage of DoEvents.

Error converting data types when importing from Excel to SQL Server 2008

There seems to be a really easy solution when dealing with data type issues.

Basically, at the end of Excel connection string, add ;IMEX=1;"

Provider=Microsoft.Jet.OLEDB.4.0;Data Source=\\YOURSERVER\shared\Client Projects\FOLDER\Data\FILE.xls;Extended Properties="EXCEL 8.0;HDR=YES;IMEX=1";

This will resolve data type issues such as columns where values are mixed with text and numbers.

To get to connection property, right click on Excel connection manager below control flow and hit properties. It'll be to the right under solution explorer. Hope that helps.

Add days Oracle SQL

If you want to add N days to your days. You can use the plus operator as follows -

SELECT ( SYSDATE + N ) FROM DUAL;

Return positions of a regex match() in Javascript?

_x000D_
_x000D_
var str = 'my string here';

var index = str.match(/hre/).index;

alert(index); // <- 10
_x000D_
_x000D_
_x000D_

React - Component Full Screen (with height 100%)

try <div style = {{height:"100vh"}}> </div>

How can I solve a connection pool problem between ASP.NET and SQL Server?

You can specify minimum and maximum pool size by specifying MinPoolSize=xyz and/or MaxPoolSize=xyz in the connection string. This cause of the problem could be a different thing however.

Upload files with HTTPWebrequest (multipart/form-data)

Check out the MyToolkit library:

var request = new HttpPostRequest("http://www.server.com");
request.Data.Add("name", "value"); // POST data
request.Files.Add(new HttpPostFile("name", "file.jpg", "path/to/file.jpg")); 

await Http.PostAsync(request, OnRequestFinished);

http://mytoolkit.codeplex.com/wikipage?title=Http

Round up double to 2 decimal places

Just single line of code:

 let obj = self.arrayResult[indexPath.row]
 let str = String(format: "%.2f", arguments: [Double((obj.mainWeight)!)!])

How to change an element's title attribute using jQuery

In jquery ui modal dialogs you need to use this construct:

$( "#my_dialog" ).dialog( "option", "title", "my new title" );

File Permissions and CHMOD: How to set 777 in PHP upon file creation?

PHP has a built in function called bool chmod(string $filename, int $mode )

http://php.net/function.chmod

private function writeFileContent($file, $content){
    $fp = fopen($file, 'w');
    fwrite($fp, $content);
    fclose($fp);
    chmod($file, 0777);  //changed to add the zero
    return true;
}

How to make a JSONP request from Javascript without JQuery?

I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.

https://github.com/Fresheyeball/micro-jsonp

function jsonp(url, key, callback) {

    var appendParam = function(url, key, param){
            return url
                + (url.indexOf("?") > 0 ? "&" : "?")
                + key + "=" + param;
        },

        createScript = function(url, callback){
            var doc = document,
                head = doc.head,
                script = doc.createElement("script");

            script
            .setAttribute("src", url);

            head
            .appendChild(script);

            callback(function(){
                setTimeout(function(){
                    head
                    .removeChild(script);
                }, 0);
            });
        },

        q =
            "q" + Math.round(Math.random() * Date.now());

    createScript(
        appendParam(url, key, q), function(remove){
            window[q] =
                function(json){
                    window[q] = undefined;
                    remove();
                    callback(json);
                };
        });
}

How do I parse JSON with Ruby on Rails?

require 'json'

hash = JSON.parse string

work with the hash and do what you want to do.

USB Debugging option greyed out

Try selecting the default mode as Internet connection.

Go to Settings -> Connectivity -> Default Mode -> Internet Connection.

Now enable the USB Debugging mode under Applications -> Development -> USB Debugging.

It worked for me.

The name 'ConfigurationManager' does not exist in the current context

You may also get this error if you add a reference to a different, unrelated project by mistake. Check if that applies to you.

How to read from input until newline is found using scanf()?

use getchar and a while that look like this

while(x = getchar())
{   
    if(x == '\n'||x == '\0')
       do what you need when space or return is detected
    else
        mystring.append(x)
}

Sorry if I wrote a pseudo-code but I don't work with C language from a while.

CakePHP 3.0 installation: intl extension missing from system

MAKE this

In XAMPP, intl extension is included but you have to uncomment extension=php_intl.dll in php.ini and restart the server through the XAMPP Control Panel. In WAMP, the intl extension is “activated” by default but not working. To make it work you have to go to php folder (by default) C:\wamp\bin\php\php{version}, copy all the files that looks like icu*.dll and paste them into the apache bin directory C:\wamp\bin\apache\apache{version}\bin. Then restart all services and it should be OK.

if you use XAMPP do this 1. turn off XAMPP 2. Modifed the php.ini is located in c/:xampp/php/php.ini 3. intl extension is included but you have to uncomment extension=php_intl.dll in php.ini and restart the server through the XAMPP Control Panel.

What are the valid Style Format Strings for a Reporting Services [SSRS] Expression?

You can check the schema at http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition/ReportDefinition.xsd

Search for xsd:complexType name="StyleType"

This will list out all the possible Styles you can use.

Specific to your question however, you can use the Format style.

Format

Specify the data format to use for values that appear in the textbox.

Valid values include Default, Number, Date, Time, Percentage, and Currency.

Link to MSDN: http://msdn.microsoft.com/en-us/library/ms251684(VS.80).aspx

how to prevent adding duplicate keys to a javascript array

The logic is wrong. Consider this:

x = ["a","b","c"]
x[0]     // "a"
x["0"]   // "a"
0 in x   // true
"0" in x // true
x.hasOwnProperty(0)   // true
x.hasOwnProperty("0") // true

There is no reason to loop to check for key (or indices for arrays) existence. Now, values are a different story...

Happy coding

How to implement OnFragmentInteractionListener

Answers posted here did not help, but the following link did:

http://developer.android.com/training/basics/fragments/communicating.html

Define an Interface

public class HeadlinesFragment extends ListFragment {
    OnHeadlineSelectedListener mCallback;

    // Container Activity must implement this interface
    public interface OnHeadlineSelectedListener {
        public void onArticleSelected(int position);
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);

        // This makes sure that the container activity has implemented
        // the callback interface. If not, it throws an exception
        try {
            mCallback = (OnHeadlineSelectedListener) activity;
        } catch (ClassCastException e) {
            throw new ClassCastException(activity.toString()
                    + " must implement OnHeadlineSelectedListener");
        }
    }

    ...
}

For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    // Send the event to the host activity
    mCallback.onArticleSelected(position);
}

Implement the Interface

For example, the following activity implements the interface from the above example.

public static class MainActivity extends Activity
        implements HeadlinesFragment.OnHeadlineSelectedListener{
    ...

    public void onArticleSelected(int position) {
        // The user selected the headline of an article from the HeadlinesFragment
        // Do something here to display that article
    }
}

Update for API 23: 8/31/2015

Overrided method onAttach(Activity activity) is now deprecated in android.app.Fragment, code should be upgraded to onAttach(Context context)

@Override
public void onAttach(Context context) {
    super.onAttach(context);
}


@Override
public void onStart() {
    super.onStart();
    try {
        mListener = (OnFragmentInteractionListener) getActivity();
    } catch (ClassCastException e) {
        throw new ClassCastException(getActivity().toString()
                + " must implement OnFragmentInteractionListener");
    }
}

Class JavaLaunchHelper is implemented in both. One of the two will be used. Which one is undefined

From what I've found online, this is a bug introduced in JDK 1.7.0_45. It appears to also be present in JDK 1.7.0_60. A bug report on Oracle's website states that, while there was a fix, it was removed before the JDK was released. I do not know why the fix was removed, but it confirms what we've already suspected -- the JDK is still broken.

The bug report claims that the error is benign and should not cause any run-time problems, though one of the comments disagrees with that. In my own experience, I have been able to work without any problems using JDK 1.7.0_60 despite seeing the message.

If this issue is causing serious problems, here are a few things I would suggest:

  • Revert back to JDK 1.7.0_25 until a fix is added to the JDK.

  • Keep an eye on the bug report so that you are aware of any work being done on this issue. Maybe even add your own comment so Oracle is aware of the severity of the issue.

  • Try the JDK early releases as they come out. One of them might fix your problem.

Instructions for installing the JDK on Mac OS X are available at JDK 7 Installation for Mac OS X. It also contains instructions for removing the JDK.

mysql_config not found when installing mysqldb python interface

For Alpine Linux:

$ apk add mariadb-dev mariadb-client mariadb-libs

MariaDB is a drop-in replacement for MySQL and became the new standard as of Alpine 3.2. See https://bugs.alpinelinux.org/issues/4264

Finding three elements in an array whose sum is closest to a given number

Program to get those three elements. I have just sorted the array/list first and them updated minCloseness based upon each triplet.

public int[] threeSumClosest(ArrayList<Integer> A, int B) {
    Collections.sort(A);
    int ansSum = 0;
    int ans[] = new int[3];
    int minCloseness = Integer.MAX_VALUE;
    for (int i = 0; i < A.size()-2; i++){
        int j = i+1;
        int k = A.size()-1;
        while (j < k){
            int sum = A.get(i) + A.get(j) + A.get(k);
            if (sum < B){
                j++;
            }else{
                k--;
            }
            if (minCloseness >  Math.abs(sum - B)){
                minCloseness = Math.abs(sum - B);
                ans[0] = A.get(i); ans[1] = A.get(j); ans[2] = A.get(k);
            }
        }
    }
    return ans;
}

Source file not compiled Dev C++

I found a solution. Please follow the following steps:

  1. Right Click the My comp. Icon

  2. Click Advanced Setting.

  3. CLick Environment Variable. On the top part of Environment Variable Click New

  4. Set Variable name as: PATH then Set Variable Value as: (" the location of g++ .exe" ) For ex. C:\Program Files (x86)\Dev-Cpp\MinGW64\bin

  5. Click OK

Ordering by specific field value first

Generally you can do

select * from your_table
order by case when name = 'core' then 1 else 2 end,
         priority 

Especially in MySQL you can also do

select * from your_table
order by name <> 'core',
         priority 

Since the result of a comparision in MySQL is either 0 or 1 and you can sort by that result.

Java Delegates?

I know this post is old, but Java 8 has added lambdas, and the concept of a functional interface, which is any interface with only one method. Together these offer similar functionality to C# delegates. See here for more info, or just google Java Lambdas. http://cr.openjdk.java.net/~briangoetz/lambda/lambda-state-final.html

Bash syntax error: unexpected end of file

on cygwin I needed:-

 export SHELLOPTS
 set -o igncr

in .bash_profile . This way I didn't need to run unix2dos

How do you send an HTTP Get Web Request in Python?

You can use urllib2

import urllib2
content = urllib2.urlopen(some_url).read()
print content

Also you can use httplib

import httplib
conn = httplib.HTTPConnection("www.python.org")
conn.request("HEAD","/index.html")
res = conn.getresponse()
print res.status, res.reason
# Result:
200 OK

or the requests library

import requests
r = requests.get('https://api.github.com/user', auth=('user', 'pass'))
r.status_code
# Result:
200

Selenium Webdriver submit() vs click()

submit() method can be used to click on the button present in the form and Type attribute should be "submit".

click() method is used to click on the button in the webpage.

Correct me if i am wrong.

Simple way to check if a string contains another string in C?

if (strstr(request, "favicon") != NULL) {
    // contains
}

Difference between EXISTS and IN in SQL?

If you are using the IN operator, the SQL engine will scan all records fetched from the inner query. On the other hand if we are using EXISTS, the SQL engine will stop the scanning process as soon as it found a match.

Reading in from System.in - Java

In Java, console input is accomplished by reading from System.in. To obtain a character based stream that is attached to the console, wrap System.in in a BufferedReader object. BufferedReader supports a buffered input stream. Its most commonly used constructor is shown here:

BufferedReader(Reader inputReader)

Here, inputReader is the stream that is linked to the instance of BufferedReader that is being created. Reader is an abstract class. One of its concrete subclasses is InputStreamReader, which converts bytes to characters.

To obtain an InputStreamReader object that is linked to System.in, use the following constructor:

InputStreamReader(InputStream inputStream)

Because System.in refers to an object of type InputStream, it can be used for inputStream. Putting it all together, the following line of code creates a BufferedReader that is connected to the keyboard:

BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

After this statement executes, br is a character-based stream that is linked to the console through System.in.

This is taken from the book Java- The Complete Reference by Herbert Schildt

TypeError: unhashable type: 'numpy.ndarray'

Your variable energies probably has the wrong shape:

>>> from numpy import array
>>> set([1,2,3]) & set(range(2, 10))
set([2, 3])
>>> set(array([1,2,3])) & set(range(2,10))
set([2, 3])
>>> set(array([[1,2,3],])) & set(range(2,10))
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'numpy.ndarray'

And that's what happens if you read columnar data using your approach:

>>> data
array([[  1.,   2.,   3.],
       [  3.,   4.,   5.],
       [  5.,   6.,   7.],
       [  8.,   9.,  10.]])
>>> hsplit(data,3)[0]
array([[ 1.],
       [ 3.],
       [ 5.],
       [ 8.]])

Probably you can simply use

>>> data[:,0]
array([ 1.,  3.,  5.,  8.])

instead.

(P.S. Your code looks like it's undecided about whether it's data or elementdata. I've assumed it's simply a typo.)

What is char ** in C?

It is a pointer to a pointer, so yes, in a way it's a 2D character array. In the same way that a char* could indicate an array of chars, a char** could indicate that it points to and array of char*s.

How to POST URL in data of a curl request

Perhaps you don't have to include the single quotes:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/&fileName=1.doc"

Update: Reading curl's manual, you could actually separate both fields with two --data:

curl --request POST 'http://localhost/Service' --data "path=/xyz/pqr/test/" --data "fileName=1.doc"

You could also try --data-binary:

curl --request POST 'http://localhost/Service' --data-binary "path=/xyz/pqr/test/" --data-binary "fileName=1.doc"

And --data-urlencode:

curl --request POST 'http://localhost/Service' --data-urlencode "path=/xyz/pqr/test/" --data-urlencode "fileName=1.doc"

MySQL "between" clause not inclusive?

Set the upper date to date + 1 day, so in your case, set it to 2011-02-01.

How to draw circle in html page?

  • No width and height requirement (specify just whichever you prefer)
  • No SVG, canvas or Unicode

_x000D_
_x000D_
.circle {
    background: green;
    border-radius: 50%;
    width: 1rem;
    aspect-ratio: 1/1;
}
_x000D_
<div class="circle"></div>
_x000D_
_x000D_
_x000D_

Borwser support:

  • Chrome/Edge 88+
  • Firefox 83+ behind a flag

Comparing chars in Java

You can just write your chars as Strings and use the equals method.

For Example:

String firstChar = "A";
String secondChar = "B";
String thirdChar = "C";

if (firstChar.equalsIgnoreCase(secondChar) ||
        (firstChar.equalsIgnoreCase(thirdChar))) // As many equals as you want
{
    System.out.println(firstChar + " is the same as " + secondChar);
} else {
    System.out.println(firstChar + " is different than " + secondChar);
}

How do I check my gcc C++ compiler version for my Eclipse?

The answer is:

gcc --version

Rather than searching on forums, for any possible option you can always type:

gcc --help

haha! :)

What's the difference between display:inline-flex and display:flex?

Display:flex apply flex layout to the flex items or children of the container only. So, the container itself stays a block level element and thus takes up the entire width of the screen.

This causes every flex container to move to a new line on the screen.

Display:inline-flex apply flex layout to the flex items or children as well as to the container itself. As a result the container behaves as an inline flex element just like the children do and thus takes up the width required by its items/children only and not the entire width of the screen.

This causes two or more flex containers one after another, displayed as inline-flex, align themselves side by side on the screen until the whole width of the screen is taken.

JQuery create a form and add elements to it programmatically

The tag is not closed:

$form.append("<input type=button value=button");

Should be:

$form.append('<input type="button" value="button">');

How do I create a local database inside of Microsoft SQL Server 2014?

As per comments, First you need to install an instance of SQL Server if you don't already have one - https://msdn.microsoft.com/en-us/library/ms143219.aspx

Once this is installed you must connect to this instance (server) and then you can create a database here - https://msdn.microsoft.com/en-US/library/ms186312.aspx

Closing database connections in Java

Actually, it is best if you use a try-with-resources block and Java will close all of the connections for you when you exit the try block.

You should do this with any object that implements AutoClosable.

try (Connection connection = getDatabaseConnection(); Statement statement = connection.createStatement()) {
    String sqlToExecute = "SELECT * FROM persons";
    try (ResultSet resultSet = statement.execute(sqlToExecute)) {
        if (resultSet.next()) {
            System.out.println(resultSet.getString("name");
        }
    }
} catch (SQLException e) {
    System.out.println("Failed to select persons.");
}

The call to getDatabaseConnection is just made up. Replace it with a call that gets you a JDBC SQL connection or a connection from a pool.

http post - how to send Authorization header?

you need RequestOptions

 let headers = new Headers({'Content-Type': 'application/json'});  
 headers.append('Authorization','Bearer ')
 let options = new RequestOptions({headers: headers});
 return this.http.post(APIname,body,options)
  .map(this.extractData)
  .catch(this.handleError);

for more check this link

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

If you have AVPlayer object with played video you have to pause video first.

Google Maps: Set Center, Set Center Point and Set more points

Try using this code for v3:

gMap = new google.maps.Map(document.getElementById('map')); 
gMap.setZoom(13);      // This will trigger a zoom_changed on the map
gMap.setCenter(new google.maps.LatLng(37.4419, -122.1419));
gMap.setMapTypeId(google.maps.MapTypeId.ROADMAP);

How to apply color in Markdown?

While Markdown doesn't support color, if you don't need too many, you could always sacrifice some of the supported styles and redefine the related tag using CSS to make it color, and also remove the formatting, or not.

Example:

// resets
s { text-decoration:none; } //strike-through
em { font-style: normal; font-weight: bold; } //italic emphasis


// colors
s { color: green }
em { color: blue }

See also: How to restyle em tag to be bold instead of italic

Then in your markdown text

~~This is green~~
_this is blue_

Is there a “not in” operator in JavaScript for checking object properties?

Personally I find

if (id in tutorTimes === false) { ... }

easier to read than

if (!(id in tutorTimes)) { ... }

but both will work.

@selector() in Swift?

When using performSelector()

/addtarget()/NStimer.scheduledTimerWithInterval() methods your method (matching the selector) should be marked as

@objc
For Swift 2.0:
    {  
        //...
        self.performSelector(“performMethod”, withObject: nil , afterDelay: 0.5)
        //...


    //...
    btnHome.addTarget(self, action: “buttonPressed:", forControlEvents: UIControlEvents.TouchUpInside)
    //...

    //...
     NSTimer.scheduledTimerWithTimeInterval(0.5, target: self, selector : “timerMethod”, userInfo: nil, repeats: false)
    //...

}

@objc private func performMethod() {
…
}
@objc private func buttonPressed(sender:UIButton){
….
}
@objc private func timerMethod () {
….
}

For Swift 2.2, you need to write '#selector()' instead of string and selector name so the possibilities of spelling error and crash due to that will not be there anymore. Below is example

self.performSelector(#selector(MyClass.performMethod), withObject: nil , afterDelay: 0.5)

Simple CSS: Text won't center in a button

Testing this in Chrome, you need to add

padding: 0px;

To the CSS.

Heap space out of memory

Are you keeping references to variables that you no longer need (e.g. data from the previous simulations)? If so, you have a memory leak. You just need to find where that is happening and make sure that you remove the references to the variables when they are no longer needed (this would automatically happen if they go out of scope).

If you actually need all that data from previous simulations in memory, you need to increase the heap size or change your algorithm.

How to pass parameters to a modal?

Alternatively you can create a new scope and pass through params via the scope option

var scope = $rootScope.$new();
 scope.params = {editId: $scope.editId};
    $modal.open({
        scope: scope,
        templateUrl: 'template.html',
        controller: 'Controller',
    });

In your modal controller pass in $scope, you then do not need to pass in and itemsProvider or what ever resolve you named it

modalController = function($scope) {
    console.log($scope.params)
}

How can I tell how many objects I've stored in an S3 bucket?

None of the APIs will give you a count because there really isn't any Amazon specific API to do that. You have to just run a list-contents and count the number of results that are returned.

Querying Windows Active Directory server using ldapsearch from command line

The short answer is "yes". A sample ldapsearch command to query an Active Directory server is:

ldapsearch \
    -x -h ldapserver.mydomain.com \
    -D "[email protected]" \
    -W \
    -b "cn=users,dc=mydomain,dc=com" \
    -s sub "(cn=*)" cn mail sn

This would connect to an AD server at hostname ldapserver.mydomain.com as user [email protected], prompt for the password on the command line and show name and email details for users in the cn=users,dc=mydomain,dc=com subtree.

See Managing LDAP from the Command Line on Linux for more samples. See LDAP Query Basics for Microsoft Exchange documentation for samples using LDAP queries with Active Directory.

Getting coordinates of marker in Google Maps API

var lat = homeMarker.getPosition().lat();
var lng = homeMarker.getPosition().lng();

See the google.maps.LatLng docs and google.maps.Marker getPosition().

Stylesheet not loaded because of MIME-type

I have changed my 'href' -> 'src'. So from this:

<link rel="stylesheet" href="dist/photoswipe.css">

to this:

<link rel="stylesheet" src="dist/photoswipe.css">

It worked. I don't know why, but it did the job.

Comment shortcut Android Studio

In Android studio CTRL + SHIFT + / for windows.

How to check if a column exists in a datatable

You can look at the Columns property of a given DataTable, it is a list of all columns in the table.

private void PrintValues(DataTable table)
{
    foreach(DataRow row in table.Rows)
    {
        foreach(DataColumn column in table.Columns)
        {
            Console.WriteLine(row[column]);
        }
    }
}

http://msdn.microsoft.com/en-us/library/system.data.datatable.columns.aspx

How do I extract data from a DataTable?

You can set the datatable as a datasource to many elements.

For eg

gridView

repeater

datalist

etc etc

If you need to extract data from each row then you can use

table.rows[rowindex][columnindex]

or

if you know the column name

table.rows[rowindex][columnname]

If you need to iterate the table then you can either use a for loop or a foreach loop like

for ( int i = 0; i < table.rows.length; i ++ )
{
    string name = table.rows[i]["columnname"].ToString();
}

foreach ( DataRow dr in table.Rows )
{
    string name = dr["columnname"].ToString();
}

How to join two tables by multiple columns in SQL?

Yes: You can use Inner Join to join on multiple columns.

SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
    E.FileNum = V.FileNum AND 
    E.ActivityNum = V.ActivityNum

Create table

CREATE TABLE MyNewTab(CaseNum int, FileNum int,
    ActivityNum int, Grade int, Score varchar(100))

Insert values

INSERT INTO MyNewTab Values(CaseNum, FileNum, ActivityNum, Grade, Score)
SELECT E.CaseNum, E.FileNum, E.ActivityNum, E.Grade, V.Score from Evaluation E
INNER JOIN Value V
ON E.CaseNum = V.CaseNum AND
    E.FileNum = V.FileNum AND 
    E.ActivityNum = V.ActivityNum

Convert np.array of type float64 to type uint8 scaling values

Considering that you are using OpenCV, the best way to convert between data types is to use normalize function.

img_n = cv2.normalize(src=img, dst=None, alpha=0, beta=255, norm_type=cv2.NORM_MINMAX, dtype=cv2.CV_8U)

However, if you don't want to use OpenCV, you can do this in numpy

def convert(img, target_type_min, target_type_max, target_type):
    imin = img.min()
    imax = img.max()

    a = (target_type_max - target_type_min) / (imax - imin)
    b = target_type_max - a * imax
    new_img = (a * img + b).astype(target_type)
    return new_img

And then use it like this

imgu8 = convert(img16u, 0, 255, np.uint8)

This is based on the answer that I found on crossvalidated board in comments under this solution https://stats.stackexchange.com/a/70808/277040

Angular 2 http post params and body

And it works, thanks @trichetriche. The problem was in my RequestOptions, apparently, you can not pass params or body to the RequestOptions while using the post. Removing one of them gives me an error, removing both and it works. Still no final solution to my problem, but I now have something to work with. Final working code.

public post(cmd: string, data: string): Observable<any> {

    const options = new RequestOptions({
      headers: this.getAuthorizedHeaders(),
      responseType: ResponseContentType.Json,
      withCredentials: false
    });

    console.log('Options: ' + JSON.stringify(options));

    return this.http.post(this.BASE_URL, JSON.stringify({
      cmd: cmd,
      data: data}), options)
      .map(this.handleData)
      .catch(this.handleError);
  }

Error : getaddrinfo ENOTFOUND registry.npmjs.org registry.npmjs.org:443

First you need to use this command

npm config set registry https://registry.your-registry.npme.io/

This we are doing to set our companies Enterprise registry as our default registry.

You can try other given solutions also.

redistributable offline .NET Framework 3.5 installer for Windows 8

Microsoft .NET framework 3.5 can be installed on windows 10 without having installation media. The file you need is called microsoft-windows-netfx3-ondemand-package.cab. Just google it and you will get the download links. After downloading it, copy that file to C:\dotnet35 and run the following command.

Dism.exe /online /enable-feature /featurename:NetFX3 /All /Source:c:\dotnet35 /LimitAccess

Tested and worked in Windows 10 without any issue.