Programs & Examples On #Image stitching

References the process of combining, or stitching together, one or more images.

Responsive css background images

CSS:

background-size: 100%;

That should do the trick! :)

How can I one hot encode in Python?

You can use numpy.eye function.

import numpy as np

def one_hot_encode(x, n_classes):
    """
    One hot encode a list of sample labels. Return a one-hot encoded vector for each label.
    : x: List of sample Labels
    : return: Numpy array of one-hot encoded labels
     """
    return np.eye(n_classes)[x]

def main():
    list = [0,1,2,3,4,3,2,1,0]
    n_classes = 5
    one_hot_list = one_hot_encode(list, n_classes)
    print(one_hot_list)

if __name__ == "__main__":
    main()

Result

D:\Desktop>python test.py
[[ 1.  0.  0.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  0.  0.  1.]
 [ 0.  0.  0.  1.  0.]
 [ 0.  0.  1.  0.  0.]
 [ 0.  1.  0.  0.  0.]
 [ 1.  0.  0.  0.  0.]]

How to hide the title bar for an Activity in XML with existing custom theme

First answer is amphibole. here is my explain: add:

this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);

in oncreate() method.

before:

super.onCreate(savedInstanceState);
setContentView(R.layout.activity_start);

(not just before setContentView) if don't do this u will get forceclose. +1 this answer.

Java NIO: What does IOException: Broken pipe mean?

What causes a "broken pipe", and more importantly, is it possible to recover from that state?

It is caused by something causing the connection to close. (It is not your application that closed the connection: that would have resulted in a different exception.)

It is not possible to recover the connection. You need to open a new one.

If it cannot be recovered, it seems this would be a good sign that an irreversible problem has occurred and that I should simply close this socket connection. Is that a reasonable assumption?

Yes it is. Once you've received that exception, the socket won't ever work again. Closing it is is the only sensible thing to do.

Is there ever a time when this IOException would occur while the socket connection is still being properly connected in the first place (rather than a working connection that failed at some point)?

No. (Or at least, not without subverting proper behavior of the OS'es network stack, the JVM and/or your application.)


Is it wise to always call SocketChannel.isConnected() before attempting a SocketChannel.write() ...

In general, it is a bad idea to call r.isXYZ() before some call that uses the (external) resource r. There is a small chance that the state of the resource will change between the two calls. It is a better idea to do the action, catch the IOException (or whatever) resulting from the failed action and take whatever remedial action is required.

In this particular case, calling isConnected() is pointless. The method is defined to return true if the socket was connected at some point in the past. It does not tell you if the connection is still live. The only way to determine if the connection is still alive is to attempt to use it; e.g. do a read or write.

How does "FOR" work in cmd batch file?

for /f iterates per line input, so in your program will only output first path.

your program treats %PATH% as one-line input, and deliminate by ;, put first result to %%g, then output %%g (first deliminated path).

"Connection for controluser as defined in your configuration failed" with phpMyAdmin in XAMPP

"For me to make it work again I just deleted the files

ib_logfile0 and

ib_logfile1 .

from :

/Applications/MAMP/db/mysql56/ib_logfile0 "

On XAMPP its Xampp/xamppfiles/var/mysql

Got this from PHP Warning: mysqli_connect(): (HY000/2002): Connection refused

How to search text using php if ($text contains "World")

The best solution is my method:

In my method, only full words are detected,But in other ways it is not.

for example:

$text='hello world!'; 

if(strpos($text, 'wor') === FALSE) { 
   echo '"wor" not found in string'; 
}

Result: strpos returned true!!! but in my method return false.

My method:

public function searchInLine($txt,$word){

    $txt=strtolower($txt);
    $word=strtolower($word);
    $word_length=strlen($word);
    $string_length=strlen($txt);
    if(strpos($txt,$word)!==false){
        $indx=strpos($txt,$word);
        $last_word=$indx+$word_length;
        if($indx==0){
            if(strpos($txt,$word." ")!==false){
                return true;
            }
            if(strpos($txt,$word.".")!==false){
                return true;
            }
            if(strpos($txt,$word.",")!==false){
                return true;
            }
            if(strpos($txt,$word."?")!==false){
                return true;
            }
            if(strpos($txt,$word."!")!==false){
                return true;
            }
        }else if($last_word==$string_length){
            if(strpos($txt," ".$word)!==false){
                return true;
            }
            if(strpos($txt,".".$word)!==false){
                return true;
            }
            if(strpos($txt,",".$word)!==false){
                return true;
            }
            if(strpos($txt,"?".$word)!==false){
                return true;
            }
            if(strpos($txt,"!".$word)!==false){
                return true;
            }

        }else{
            if(strpos($txt," ".$word." ")!==false){
                return true;
            }
            if(strpos($txt," ".$word.".")!==false){
                return true;
            }
            if(strpos($txt," ".$word.",")!==false){
                return true;
            }
            if(strpos($txt," ".$word."!")!==false){
                return true;
            }
            if(strpos($txt," ".$word."?")!==false){
                return true;
            }
        }
        }

    return false;
}

Leave only two decimal places after the dot

// just two decimal places
String.Format("{0:0.00}", 123.4567);      // "123.46"
String.Format("{0:0.00}", 123.4);         // "123.40"
String.Format("{0:0.00}", 123.0);         // "123.00"

http://www.csharp-examples.net/string-format-double/

edit

No idea why they used "String" instead of "string", but the rest is correct.

How can I make a DateTimePicker display an empty string?

Obfuscating the value by using the CustomFormat property, using checkbox cbEnableEndDate as the flag to indicate whether other code should ignore the value:

If dateTaskEnd > Date.FromOADate(0) Then
    dtTaskEnd.Format = DateTimePickerFormat.Custom
    dtTaskEnd.CustomFormat = "yyyy-MM-dd"
    dtTaskEnd.Value = dateTaskEnd 
    dtTaskEnd.Enabled = True
    cbEnableEndDate.Checked = True
Else
    dtTaskEnd.Format = DateTimePickerFormat.Custom
    dtTaskEnd.CustomFormat = " "
    dtTaskEnd.Value = Date.FromOADate(0)
    dtTaskEnd.Enabled = False
    cbEnableEndDate.Checked = False
End If

How to time Java program execution speed

I created a higher order function which takes the code you want to measure in/as a lambda:

class Utils {

    public static <T> T timeIt(String msg, Supplier<T> s) {
        long startTime = System.nanoTime();
        T t = s.get();
        long endTime = System.nanoTime();
        System.out.println(msg + ": " + (endTime - startTime) + " ns");
        return t;
    }

    public static void timeIt(String msg, Runnable r) {
       timeIt(msg, () -> {r.run(); return null; });
    }
}

Call it like that:

Utils.timeIt("code 0", () ->
        System.out.println("Hallo")
);

// in case you need the result of the lambda
int i = Utils.timeIt("code 1", () ->
        5 * 5
);

Output:

code 0: 180528 ns
code 1: 12003 ns

Special thanks to Andy Turner who helped me cut down the redundancy. See here.

Java Enum return Int

In my opinion the most readable version

public enum PIN_PULL_RESISTANCE {
    PULL_UP {
        @Override
        public int getValue() {
            return 1;
        }
    },
    PULL_DOWN {
        @Override
        public int getValue() {
            return 0;
        }
    };

    public abstract int getValue();
}

jQuery Find and List all LI elements within a UL within a specific DIV

$('li[rel=7]').siblings().andSelf();

// or:

$('li[rel=7]').parent().children();

Now that you added that comment explaining that you want to "form an array of rels per column", you should do this:

var rels = [];

$('ul').each(function() {
    var localRels = [];

    $(this).find('li').each(function(){
        localRels.push( $(this).attr('rel') );
    });

    rels.push(localRels);
});

Cannot invoke an expression whose type lacks a call signature

I had the same issue with numeral, a JS library. The fix was to install the typings again with this command:

npm install --save @types/numeral

How do I format axis number format to thousands with a comma in matplotlib?

I always find myself on this same page everytime I try to do this. Sure, the other answers get the job done, but aren't easy to remember for next time! ex: import ticker and use lambda, custom def, etc.

Here's a simple solution if you have an axes named ax:

ax.set_yticklabels(['{:,}'.format(int(x)) for x in ax.get_yticks().tolist()])

How do I convert a String to an InputStream in Java?

There are two ways we can convert String to InputStream in Java,

  1. Using ByteArrayInputStream

Example :-

String str = "String contents";
InputStream is = new ByteArrayInputStream(str.getBytes(StandardCharsets.UTF_8));
  1. Using Apache Commons IO

Example:-

String str = "String contents"
InputStream is = IOUtils.toInputStream(str, StandardCharsets.UTF_8);

Guid.NewGuid() vs. new Guid()

new Guid() makes an "empty" all-0 guid (00000000-0000-0000-0000-000000000000 is not very useful).

Guid.NewGuid() makes an actual guid with a unique value, what you probably want.

AngularJS: Service vs provider vs factory

For me, the revelation came when I realized that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through dependency injection.

Say we have:

app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);

The difference between the three is that:

  1. a's stored value comes from running fn.
  2. b’s stored value comes from newing fn.
  3. c’s stored value comes from first getting an instance by newing fn, and then running a $get method of the instance.

Which means there’s something like a cache object inside AngularJS, whose value of each injection is only assigned once, when they've been injected the first time, and where:

cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()

This is why we use this in services, and define a this.$get in providers.

Rendering raw html with reactjs

export class ModalBody extends Component{
    rawMarkup(){
        var rawMarkup = this.props.content
        return { __html: rawMarkup };
    }
    render(){
        return(
                <div className="modal-body">
                     <span dangerouslySetInnerHTML={this.rawMarkup()} />

                </div>
            )
    }
}

Working Soap client example

Calculator SOAP service test from SoapUI, Online SoapClient Calculator

Generate the SoapMessage object form the input SoapEnvelopeXML and SoapDataXml.

SoapEnvelopeXML

<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/">
   <soapenv:Header/>
   <soapenv:Body>
      <tem:Add xmlns:tem="http://tempuri.org/">
         <tem:intA>3</tem:intA>
         <tem:intB>4</tem:intB>
      </tem:Add>
   </soapenv:Body>
</soapenv:Envelope>

use the following code to get SoapMessage Object.

MessageFactory messageFactory = MessageFactory.newInstance();
    MimeHeaders headers = new MimeHeaders();
    ByteArrayInputStream xmlByteStream = new ByteArrayInputStream(SoapEnvelopeXML.getBytes());
SOAPMessage soapMsg = messageFactory.createMessage(headers, xmlByteStream);

SoapDataXml

<tem:Add xmlns:tem="http://tempuri.org/">
    <tem:intA>3</tem:intA>
    <tem:intB>4</tem:intB>
</tem:Add>

use below code to get SoapMessage Object.

public static SOAPMessage getSOAPMessagefromDataXML(String saopBodyXML) throws Exception {
    DocumentBuilderFactory dbFactory = DocumentBuilderFactory.newInstance();
    dbFactory.setNamespaceAware(true);
    dbFactory.setIgnoringComments(true);
    DocumentBuilder dBuilder = dbFactory.newDocumentBuilder();
    InputSource ips = new org.xml.sax.InputSource(new StringReader(saopBodyXML));
    Document docBody = dBuilder.parse(ips);
    System.out.println("Data Document: "+docBody.getDocumentElement());
    
    MessageFactory messageFactory = MessageFactory.newInstance(SOAPConstants.SOAP_1_2_PROTOCOL);
    SOAPMessage soapMsg = messageFactory.createMessage();
    
    SOAPBody soapBody = soapMsg.getSOAPPart().getEnvelope().getBody();
    soapBody.addDocument(docBody);
    
    return soapMsg;
}

By getting the SoapMessage Object. It is clear that the Soap XML is valid. Then prepare to hit the service to get response. It can be done in many ways.

  1. Using Client Code Generated form WSDL.
java.net.URL endpointURL = new java.net.URL(endPointUrl);
javax.xml.rpc.Service service = new org.apache.axis.client.Service();
((org.apache.axis.client.Service) service).setTypeMappingVersion("1.2");
CalculatorSoap12Stub obj_axis = new CalculatorSoap12Stub(endpointURL, service);
int add = obj_axis.add(10, 20);
System.out.println("Response: "+ add);
  1. Using javax.xml.soap.SOAPConnection.
public static void getSOAPConnection(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== SOAPConnection =====");
    MimeHeaders headers = soapMsg.getMimeHeaders(); // new MimeHeaders();
    headers.addHeader("SoapBinding",   serverDetails.get("SoapBinding") );
    headers.addHeader("MethodName",    serverDetails.get("MethodName") );
    headers.addHeader("SOAPAction",    serverDetails.get("SOAPAction") );
    headers.addHeader("Content-Type",  serverDetails.get("Content-Type"));
    headers.addHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    if (soapMsg.saveRequired()) {
        soapMsg.saveChanges();
    }
    
    SOAPConnectionFactory newInstance = SOAPConnectionFactory.newInstance();
    javax.xml.soap.SOAPConnection connection = newInstance.createConnection();
    SOAPMessage soapMsgResponse = connection.call(soapMsg, getURL( serverDetails.get("SoapServerURI"), 5*1000 ));
    
    getSOAPXMLasString(soapMsgResponse);
}
  1. Form HTTP Connection Classes org.apache.commons.httpclient.
public static void getHttpConnection(SOAPMessage soapMsg) throws SOAPException, IOException {
    System.out.println("===== HttpClient =====");
    HttpClient httpClient = new HttpClient();
    HttpConnectionManagerParams params = httpClient.getHttpConnectionManager().getParams();
    params.setConnectionTimeout(3 * 1000); // Connection timed out
    params.setSoTimeout(3 * 1000);         // Request timed out
    params.setParameter("http.useragent", "Web Service Test Client");

    PostMethod methodPost = new PostMethod( serverDetails.get("SoapServerURI") );
    methodPost.setRequestBody( getSOAPXMLasString(soapMsg) );
    methodPost.setRequestHeader("Content-Type", serverDetails.get("Content-Type") );
    methodPost.setRequestHeader("SoapBinding",  serverDetails.get("SoapBinding") );
    methodPost.setRequestHeader("MethodName",   serverDetails.get("MethodName") );
    methodPost.setRequestHeader("SOAPAction",   serverDetails.get("SOAPAction") );

    methodPost.setRequestHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));

    try {
        int returnCode = httpClient.executeMethod(methodPost);
        if (returnCode == HttpStatus.SC_NOT_IMPLEMENTED) {
            System.out.println("The Post method is not implemented by this URI");
            methodPost.getResponseBodyAsString();
        } else {
            BufferedReader br = new BufferedReader(new InputStreamReader(methodPost.getResponseBodyAsStream()));
            String readLine;
            while (((readLine = br.readLine()) != null)) {
                System.out.println(readLine);
            }
            br.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
    } finally {
        methodPost.releaseConnection();
    }
}
public static void accessResource_AppachePOST(SOAPMessage soapMsg) throws Exception {
    System.out.println("===== HttpClientBuilder =====");
    CloseableHttpClient httpClient = HttpClientBuilder.create().build();
    URIBuilder builder = new URIBuilder( serverDetails.get("SoapServerURI") );
    HttpPost methodPost = new HttpPost(builder.build());
    RequestConfig config = RequestConfig.custom()
            .setConnectTimeout(5 * 1000)
            .setConnectionRequestTimeout(5 * 1000)
            .setSocketTimeout(5 * 1000)
            .build();
    methodPost.setConfig(config);
        HttpEntity xmlEntity = new StringEntity(getSOAPXMLasString(soapMsg), "utf-8");
    methodPost.setEntity(xmlEntity);
        
    methodPost.setHeader("Content-Type", serverDetails.get("Content-Type"));
    methodPost.setHeader("SoapBinding", serverDetails.get("SoapBinding") );
    methodPost.setHeader("MethodName", serverDetails.get("MethodName") );
    methodPost.setHeader("SOAPAction", serverDetails.get("SOAPAction") );
    methodPost.setHeader("Accept-Encoding", serverDetails.get("Accept-Encoding"));
    
    // Create a custom response handler
    ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
        @Override
        public String handleResponse( final HttpResponse response) throws ClientProtocolException, IOException {
            int status = response.getStatusLine().getStatusCode();
            if (status >= 200 && status <= 500) {
                HttpEntity entity = response.getEntity();
                return entity != null ? EntityUtils.toString(entity) : null;
            }
            return "";
        }
    };
    String execute = httpClient.execute( methodPost, responseHandler );
    System.out.println("AppachePOST : "+execute);
}

Full Example:

public class SOAP_Calculator {
    static HashMap<String, String> serverDetails = new HashMap<>();
    static {
        // Calculator
        serverDetails.put("SoapServerURI", "http://www.dneonline.com/calculator.asmx");
        serverDetails.put("SoapWSDL", "http://www.dneonline.com/calculator.asmx?wsdl");
        serverDetails.put("SoapBinding", "CalculatorSoap");        // <wsdl:binding name="CalculatorSoap12" type="tns:CalculatorSoap">
        serverDetails.put("MethodName", "Add");                    // <wsdl:operation name="Add">
        serverDetails.put("SOAPAction", "http://tempuri.org/Add"); // <soap12:operation soapAction="http://tempuri.org/Add" style="document"/>
        serverDetails.put("SoapXML", "<tem:Add xmlns:tem=\"http://tempuri.org/\"><tem:intA>2</tem:intA><tem:intB>4</tem:intB></tem:Add>");
        
        serverDetails.put("Accept-Encoding", "gzip,deflate");
        serverDetails.put("Content-Type", "");
    }
    public static void callSoapService( ) throws Exception {
        String xmlData = serverDetails.get("SoapXML");
        
        SOAPMessage soapMsg = getSOAPMessagefromDataXML(xmlData);
        System.out.println("Requesting SOAP Message:\n"+ getSOAPXMLasString(soapMsg) +"\n");
        
        SOAPEnvelope envelope = soapMsg.getSOAPPart().getEnvelope();
        if (envelope.getElementQName().getNamespaceURI().equals("http://schemas.xmlsoap.org/soap/envelope/")) {
            System.out.println("SOAP 1.1 NamespaceURI: http://schemas.xmlsoap.org/soap/envelope/");
            serverDetails.put("Content-Type", "text/xml; charset=utf-8");
        } else {
            System.out.println("SOAP 1.2 NamespaceURI: http://www.w3.org/2003/05/soap-envelope");
            serverDetails.put("Content-Type", "application/soap+xml; charset=utf-8");
        }
        
        getHttpConnection(soapMsg);
        getSOAPConnection(soapMsg);
        accessResource_AppachePOST(soapMsg);
    }
    public static void main(String[] args) throws Exception {
        callSoapService();
    }

    private static URL getURL(String endPointUrl, final int timeOutinSeconds) throws MalformedURLException {
        URL endpoint = new URL(null, endPointUrl, new URLStreamHandler() {
            protected URLConnection openConnection(URL url) throws IOException {
                URL clone = new URL(url.toString());
                URLConnection connection = clone.openConnection();
                connection.setConnectTimeout(timeOutinSeconds);
                connection.setReadTimeout(timeOutinSeconds);
                //connection.addRequestProperty("Developer-Mood", "Happy"); // Custom header
                return connection;
            }
        });
        return endpoint;
    }
    public static String getSOAPXMLasString(SOAPMessage soapMsg) throws SOAPException, IOException {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        soapMsg.writeTo(out);
        // soapMsg.writeTo(System.out);
        String strMsg = new String(out.toByteArray());
        System.out.println("Soap XML: "+ strMsg);
        return strMsg;
    }
}

@See list of some WebServices at http://sofa.uqam.ca/soda/webservices.php

explode string in jquery

What is row?

Either of these could be correct.

1) I assume that you capture your ajax response in a javascript variable 'row'. If that is the case, this would hold true.

var result=row.split('|');
    alert(result[2]);

otherwise

2) Use this where $(row) is a jQuery object.

var result=$(row).val().split('|');
    alert(result[2]);

[As mentioned in the other answer, you may have to use $(row).val() or $(row).text() or $(row).html() etc. depending on what $(row) is.]

Python CSV error: line contains NULL byte

I got the same error. Saved the file in UTF-8 and it worked.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

I solved this question by unInstalled ndk, becasuse I dont't need it

Angular - Can't make ng-repeat orderBy work

in Eike Thies's response above, if we use underscore.js, filter could be simplified to :

var app = angular.module('myApp', []).filter('object2Array', function() {
  return function(input) {
    return _.toArray(input);
  }
});

Could not find a declaration file for module 'module-name'. '/path/to/module-name.js' implicitly has an 'any' type

This way works for me:

1. add your own declaration in a declaration file such as index.d.ts(maybe under the project root)
declare module 'Injector';
2. add your index.d.ts to tsconfig.json
  {
    "compilerOptions": {
        "strictNullChecks": true,
        "moduleResolution": "node",
        "jsx": "react",
        "noUnusedParameters": true,
        "noUnusedLocals": true,
        "allowSyntheticDefaultImports":true,
        "target": "es5",
        "module": "ES2015",
        "declaration": true,
        "outDir": "./lib",
        "noImplicitAny": true,
        "importHelpers": true
      },
      "include": [
        "src/**/*",
        "index.d.ts",   // declaration file path
      ],
      "compileOnSave": false
    }

-- edit: needed quotation marks around module name

How to create a property for a List<T>

You could do this but the T generic parameter needs to be declared at the containing class:

public class Foo<T>
{
    public List<T> NewList { get; set; }
}

How to get last inserted row ID from WordPress database?

Straight after the $wpdb->insert() that does the insert, do this:

$lastid = $wpdb->insert_id;

More information about how to do things the WordPress way can be found in the WordPress codex. The details above were found here on the wpdb class page

How to have multiple colors in a Windows batch file?

jeb's edited answer comes close to solving all the issues. But it has problems with the following strings:

"a\b\"
"a/b/"
"\"
"/"
"."
".."
"c:"

I've modified his technique to something that I think can truly handle any string of printable characters, except for length limitations.

Other improvements:

  • Uses the %TEMP% location for the temp file, so no longer need write access to the current directory.

  • Created 2 variants, one takes a string literal, the other the name of a variable containing the string. The variable version is generally less convenient, but it eliminates some special character escape issues.

  • Added the /n option as an optional 3rd parameter to append a newline at the end of the output.

Backspace does not work across a line break, so the technique can have problems if the line wraps. For example, printing a string with length between 74 - 79 will not work properly if the console has a line width of 80.

@echo off
setlocal

call :initColorPrint

call :colorPrint 0a "a"
call :colorPrint 0b "b"
set "txt=^" & call :colorPrintVar 0c txt
call :colorPrint 0d "<"
call :colorPrint 0e ">"
call :colorPrint 0f "&"
call :colorPrint 1a "|"
call :colorPrint 1b " "
call :colorPrint 1c "%%%%"
call :colorPrint 1d ^"""
call :colorPrint 1e "*"
call :colorPrint 1f "?"
call :colorPrint 2a "!"
call :colorPrint 2b "."
call :colorPrint 2c ".."
call :colorPrint 2d "/"
call :colorPrint 2e "\"
call :colorPrint 2f "q:" /n
echo(
set complex="c:\hello world!/.\..\\a//^<%%>&|!" /^^^<%%^>^&^|!\
call :colorPrintVar 74 complex /n

call :cleanupColorPrint

exit /b

:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:colorPrint Color  Str  [/n]
setlocal
set "str=%~2"
call :colorPrintVar %1 str %3
exit /b

:colorPrintVar  Color  StrVar  [/n]
if not defined %~2 exit /b
setlocal enableDelayedExpansion
set "str=a%DEL%!%~2:\=a%DEL%\..\%DEL%%DEL%%DEL%!"
set "str=!str:/=a%DEL%/..\%DEL%%DEL%%DEL%!"
set "str=!str:"=\"!"
pushd "%temp%"
findstr /p /A:%1 "." "!str!\..\x" nul
if /i "%~3"=="/n" echo(
exit /b

:initColorPrint
for /F "tokens=1,2 delims=#" %%a in ('"prompt #$H#$E# & echo on & for %%b in (1) do rem"') do set "DEL=%%a"
<nul >"%temp%\x" set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%.%DEL%"
exit /b

:cleanupColorPrint
del "%temp%\x"
exit /b


UPDATE 2012-11-27

This method fails on XP because FINDSTR displays backspace as a period on the screen. jeb's original answer works on XP, albeit with the limitations already noted


UPDATE 2012-12-14

There has been a lot of development activity at DosTips and SS64. It turns out that FINDSTR also corrupts file names containing extended ASCII if supplied on the command line. I've updated my FINDSTR Q&A.

Below is a version that works on XP and supports ALL single byte characters except 0x00 (nul), 0x0A (linefeed), and 0x0D (carriage return). However, when running on XP, most control characters will display as dots. This is an inherent feature of FINDSTR on XP that cannot be avoided.

Unfortunately, adding support for XP and for extended ASCII characters slows the routine down :-(

Just for fun, I grabbed some color ASCII art from joan stark's ASCII Art Gallery and adapted it for use with ColorPrint. I added a :c entry point just for shorthand, and to handle an issue with quote literals.

@echo off
setlocal disableDelayedExpansion
set q=^"
echo(
echo(
call :c 0E "                ,      .-;" /n
call :c 0E "             ,  |\    / /  __," /n
call :c 0E "             |\ '.`-.|  |.'.-'" /n
call :c 0E "              \`'-:  `; : /" /n
call :c 0E "               `-._'.  \'|" /n
call :c 0E "              ,_.-=` ` `  ~,_" /n
call :c 0E "               '--,.    "&call :c 0c ".-. "&call :c 0E ",=!q!." /n
call :c 0E "                 /     "&call :c 0c "{ "&call :c 0A "* "&call :c 0c ")"&call :c 0E "`"&call :c 06 ";-."&call :c 0E "}" /n
call :c 0E "                 |      "&call :c 0c "'-' "&call :c 06 "/__ |" /n
call :c 0E "                 /          "&call :c 06 "\_,\|" /n
call :c 0E "                 |          (" /n
call :c 0E "             "&call :c 0c "__ "&call :c 0E "/ '          \" /n
call :c 02 "     /\_    "&call :c 0c "/,'`"&call :c 0E "|     '   "&call :c 0c ".-~!q!~~-." /n
call :c 02 "     |`.\_ "&call :c 0c "|   "&call :c 0E "/  ' ,    "&call :c 0c "/        \" /n
call :c 02 "   _/  `, \"&call :c 0c "|  "&call :c 0E "; ,     . "&call :c 0c "|  ,  '  . |" /n
call :c 02 "   \   `,  "&call :c 0c "|  "&call :c 0E "|  ,  ,   "&call :c 0c "|  :  ;  : |" /n
call :c 02 "   _\  `,  "&call :c 0c "\  "&call :c 0E "|.     ,  "&call :c 0c "|  |  |  | |" /n
call :c 02 "   \`  `.   "&call :c 0c "\ "&call :c 0E "|   '     "&call :c 0A "|"&call :c 0c "\_|-'|_,'\|" /n
call :c 02 "   _\   `,   "&call :c 0A "`"&call :c 0E "\  '  . ' "&call :c 0A "| |  | |  |           "&call :c 02 "__" /n
call :c 02 "   \     `,   "&call :c 0E "| ,  '    "&call :c 0A "|_/'-|_\_/     "&call :c 02 "__ ,-;` /" /n
call :c 02 "    \    `,    "&call :c 0E "\ .  , ' .| | | | |   "&call :c 02 "_/' ` _=`|" /n
call :c 02 "     `\    `,   "&call :c 0E "\     ,  | | | | |"&call :c 02 "_/'   .=!q!  /" /n
call :c 02 "     \`     `,   "&call :c 0E "`\      \/|,| ;"&call :c 02 "/'   .=!q!    |" /n
call :c 02 "      \      `,    "&call :c 0E "`\' ,  | ; "&call :c 02 "/'    =!q!    _/" /n
call :c 02 "       `\     `,  "&call :c 05 ".-!q!!q!-. "&call :c 0E "': "&call :c 02 "/'    =!q!     /" /n
call :c 02 "    jgs _`\    ;"&call :c 05 "_{  '   ; "&call :c 02 "/'    =!q!      /" /n
call :c 02 "       _\`-/__"&call :c 05 ".~  `."&call :c 07 "8"&call :c 05 ".'.!q!`~-. "&call :c 02 "=!q!     _,/" /n
call :c 02 "    __\      "&call :c 05 "{   '-."&call :c 07 "|"&call :c 05 ".'.--~'`}"&call :c 02 "    _/" /n
call :c 02 "    \    .=!q!` "&call :c 05 "}.-~!q!'"&call :c 0D "u"&call :c 05 "'-. '-..'  "&call :c 02 "__/" /n
call :c 02 "   _/  .!q!    "&call :c 05 "{  -'.~('-._,.'"&call :c 02 "\_,/" /n
call :c 02 "  /  .!q!    _/'"&call :c 05 "`--; ;  `.  ;" /n
call :c 02 "   .=!q!  _/'      "&call :c 05 "`-..__,-'" /n
call :c 02 "    __/'" /n
echo(

exit /b

:c
setlocal enableDelayedExpansion
:::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::

:colorPrint Color  Str  [/n]
setlocal
set "s=%~2"
call :colorPrintVar %1 s %3
exit /b

:colorPrintVar  Color  StrVar  [/n]
if not defined DEL call :initColorPrint
setlocal enableDelayedExpansion
pushd .
':
cd \
set "s=!%~2!"
:: The single blank line within the following IN() clause is critical - DO NOT REMOVE
for %%n in (^"^

^") do (
  set "s=!s:\=%%~n\%%~n!"
  set "s=!s:/=%%~n/%%~n!"
  set "s=!s::=%%~n:%%~n!"
)
for /f delims^=^ eol^= %%s in ("!s!") do (
  if "!" equ "" setlocal disableDelayedExpansion
  if %%s==\ (
    findstr /a:%~1 "." "\'" nul
    <nul set /p "=%DEL%%DEL%%DEL%"
  ) else if %%s==/ (
    findstr /a:%~1 "." "/.\'" nul
    <nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%"
  ) else (
    >colorPrint.txt (echo %%s\..\')
    findstr /a:%~1 /f:colorPrint.txt "."
    <nul set /p "=%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%%DEL%"
  )
)
if /i "%~3"=="/n" echo(
popd
exit /b


:initColorPrint
for /f %%A in ('"prompt $H&for %%B in (1) do rem"') do set "DEL=%%A %%A"
<nul >"%temp%\'" set /p "=."
subst ': "%temp%" >nul
exit /b


:cleanupColorPrint
2>nul del "%temp%\'"
2>nul del "%temp%\colorPrint.txt"
>nul subst ': /d
exit /b

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

This is a likely a linker error. Add the -lm switch to specify that you want to link against the standard C math library (libm) which has the definition for those functions (the header just has the declaration for them - worth looking up the difference.)

change cursor from block or rectangle to line?

You're in replace mode. Press the Insert key on your keyboard to switch back to insert mode. Many applications that handle text have this in common.

How to store JSON object in SQLite database

There is no data types for that.. You need to store it as VARCHAR or TEXT only.. jsonObject.toString();

javascript get child by id

This works well:

function test(el){
  el.childNodes.item("child").style.display = "none";
}

If the argument of item() function is an integer, the function will treat it as an index. If the argument is a string, then the function searches for name or ID of element.

Check if number is decimal

If you are working with form validation. Then in this case form send string. I used following code to check either form input is a decimal number or not. I hope this will work for you too.

function is_decimal($input = '') {

    $alphabets = str_split($input);
    $find = array('0','1','2','3','4','5','6','7','8','9','.'); // Please note: All intiger numbers are decimal. If you want to check numbers without point "." then you can remove '.' from array. 

    foreach ($alphabets as $key => $alphabet) {
        if (!in_array($alphabet, $find)) {
            return false;
        }
    }

    // Check if user has enter "." point more then once.
    if (substr_count($input, ".") > 1) {
        return false;
    }

    return true;
}

How to resolve the C:\fakepath?

Use file readers:

$(document).ready(function() {
        $("#input-file").change(function() {
            var length = this.files.length;
            if (!length) {
                return false;
            }
            useImage(this);
        });
    });

    // Creating the function
    function useImage(img) {
        var file = img.files[0];
        var imagefile = file.type;
        var match = ["image/jpeg", "image/png", "image/jpg"];
        if (!((imagefile == match[0]) || (imagefile == match[1]) || (imagefile == match[2]))) {
            alert("Invalid File Extension");
        } else {
            var reader = new FileReader();
            reader.onload = imageIsLoaded;
            reader.readAsDataURL(img.files[0]);
        }

        function imageIsLoaded(e) {
            $('div.withBckImage').css({ 'background-image': "url(" + e.target.result + ")" });

        }
    }

R - Markdown avoiding package loading messages

My best solution on R Markdown was to create a code chunk only to load libraries and exclude everything in the chunk.

{r results='asis', echo=FALSE, include=FALSE,}
knitr::opts_chunk$set(echo = TRUE, warning=FALSE)
#formating tables
library(xtable)

#data wrangling
library(dplyr)

#text processing
library(stringi)

What's the bad magic number error?

I just faced the same issue with Fedora26 where many tools such as dnf were broken due to bad magic number for six. For an unknown reason i've got a file /usr/bin/six.pyc, with the unexpected magic number. Deleting this file fix the problem

Read the current full URL with React?

this.props.location is a react-router feature, you'll have to install if you want to use it.

Note: doesn't return the full url.

How can I let a user download multiple files when a button is clicked?

This is the easiest way I have found to download multiple files.

$('body').on('click','.download_btn',function(){
    downloadFiles([
        ['File1.pdf', 'File1-link-here'],
        ['File2.pdf', 'File2-link-here'],
        ['File3.pdf', 'File3-link-here'],
        ['File4.pdf', 'File4-link-here']
    ]);
})
function downloadFiles(files){
    if(files.length == 0){
        return;
    }
    file = files.pop();
    var Link = $('body').append('<a href="'+file[1]+'" download="file[0]"></a>');
    Link[0].click(); 
    Link.remove();
    downloadFiles(files);
}

This should be work for you. Thank You.

How do I push a local Git branch to master branch in the remote?

As people mentioned in the comments you probably don't want to do that... The answer from mipadi is absolutely correct if you know what you're doing.

I would say:

git checkout master
git pull               # to update the state to the latest remote master state
git merge develop      # to bring changes to local master from your develop branch
git push origin master # push current HEAD to remote master branch

 

How to sleep for five seconds in a batch file/cmd

Can't we do waitfor /T 180?

waitfor /T 180 pause will result in "ERROR: Timed out waiting for 'pause'."

waitfor /T 180 pause >nul will sweep that "error" under the rug

The waitfor command should be there in Windows OS after Win95

In the past I've downloaded a executable named sleep that will work on the command line after you put it in your path.

For example: sleep shutdown -r -f /m \\yourmachine although shutdown now has -t option built in

What's the foolproof way to tell which version(s) of .NET are installed on a production Windows Server?

I went into Windows Update & looked at the update history, knowing the server patching is kept up-to-date. I scanned down for .NET updates and it showed me exactly which versions had had updates, which allowed me to conclude which versions were installed.

Saving and loading objects and using pickle

You didn't open the file in binary mode.

open("Fruits.obj",'rb')

Should work.

For your second error, the file is most likely empty, which mean you inadvertently emptied it or used the wrong filename or something.

(This is assuming you really did close your session. If not, then it's because you didn't close the file between the write and the read).

I tested your code, and it works.

if condition in sql server update query

this worked great:

UPDATE
    table_Name
SET 
  column_A = CASE WHEN @flag = '1' THEN column_A + @new_value ELSE column_A END,
  column_B = CASE WHEN @flag = '0' THEN column_B + @new_value ELSE column_B END
WHERE
    ID = @ID

How to create a temporary table in SSIS control flow task and then use it in data flow task?

Solution:

Set the property RetainSameConnection on the Connection Manager to True so that temporary table created in one Control Flow task can be retained in another task.

Here is a sample SSIS package written in SSIS 2008 R2 that illustrates using temporary tables.

Walkthrough:

Create a stored procedure that will create a temporary table named ##tmpStateProvince and populate with few records. The sample SSIS package will first call the stored procedure and then will fetch the temporary table data to populate the records into another database table. The sample package will use the database named Sora Use the below create stored procedure script.

USE Sora;
GO

CREATE PROCEDURE dbo.PopulateTempTable
AS
BEGIN
    
    SET NOCOUNT ON;

    IF OBJECT_ID('TempDB..##tmpStateProvince') IS NOT NULL
        DROP TABLE ##tmpStateProvince;

    CREATE TABLE ##tmpStateProvince
    (
            CountryCode     nvarchar(3)         NOT NULL
        ,   StateCode       nvarchar(3)         NOT NULL
        ,   Name            nvarchar(30)        NOT NULL
    );

    INSERT INTO ##tmpStateProvince 
        (CountryCode, StateCode, Name)
    VALUES
        ('CA', 'AB', 'Alberta'),
        ('US', 'CA', 'California'),
        ('DE', 'HH', 'Hamburg'),
        ('FR', '86', 'Vienne'),
        ('AU', 'SA', 'South Australia'),
        ('VI', 'VI', 'Virgin Islands');
END
GO

Create a table named dbo.StateProvince that will be used as the destination table to populate the records from temporary table. Use the below create table script to create the destination table.

USE Sora;
GO

CREATE TABLE dbo.StateProvince
(
        StateProvinceID int IDENTITY(1,1)   NOT NULL
    ,   CountryCode     nvarchar(3)         NOT NULL
    ,   StateCode       nvarchar(3)         NOT NULL
    ,   Name            nvarchar(30)        NOT NULL
    CONSTRAINT [PK_StateProvinceID] PRIMARY KEY CLUSTERED
        ([StateProvinceID] ASC)
) ON [PRIMARY];
GO

Create an SSIS package using Business Intelligence Development Studio (BIDS). Right-click on the Connection Managers tab at the bottom of the package and click New OLE DB Connection... to create a new connection to access SQL Server 2008 R2 database.

Connection Managers - New OLE DB Connection

Click New... on Configure OLE DB Connection Manager.

Configure OLE DB Connection Manager - New

Perform the following actions on the Connection Manager dialog.

  • Select Native OLE DB\SQL Server Native Client 10.0 from Provider since the package will connect to SQL Server 2008 R2 database
  • Enter the Server name, like MACHINENAME\INSTANCE
  • Select Use Windows Authentication from Log on to the server section or whichever you prefer.
  • Select the database from Select or enter a database name, the sample uses the database name Sora.
  • Click Test Connection
  • Click OK on the Test connection succeeded message.
  • Click OK on Connection Manager

Connection Manager

The newly created data connection will appear on Configure OLE DB Connection Manager. Click OK.

Configure OLE DB Connection Manager - Created

OLE DB connection manager KIWI\SQLSERVER2008R2.Sora will appear under the Connection Manager tab at the bottom of the package. Right-click the connection manager and click Properties

Connection Manager Properties

Set the property RetainSameConnection on the connection KIWI\SQLSERVER2008R2.Sora to the value True.

RetainSameConnection Property on Connection Manager

Right-click anywhere inside the package and then click Variables to view the variables pane. Create the following variables.

  • A new variable named PopulateTempTable of data type String in the package scope SO_5631010 and set the variable with the value EXEC dbo.PopulateTempTable.

  • A new variable named FetchTempData of data type String in the package scope SO_5631010 and set the variable with the value SELECT CountryCode, StateCode, Name FROM ##tmpStateProvince

Variables

Drag and drop an Execute SQL Task on to the Control Flow tab. Double-click the Execute SQL Task to view the Execute SQL Task Editor.

On the General page of the Execute SQL Task Editor, perform the following actions.

  • Set the Name to Create and populate temp table
  • Set the Connection Type to OLE DB
  • Set the Connection to KIWI\SQLSERVER2008R2.Sora
  • Select Variable from SQLSourceType
  • Select User::PopulateTempTable from SourceVariable
  • Click OK

Execute SQL Task Editor

Drag and drop a Data Flow Task onto the Control Flow tab. Rename the Data Flow Task as Transfer temp data to database table. Connect the green arrow from the Execute SQL Task to the Data Flow Task.

Control Flow Tab

Double-click the Data Flow Task to switch to Data Flow tab. Drag and drop an OLE DB Source onto the Data Flow tab. Double-click OLE DB Source to view the OLE DB Source Editor.

On the Connection Manager page of the OLE DB Source Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select SQL command from variable from Data access mode
  • Select User::FetchTempData from Variable name
  • Click Columns page

OLE DB Source Editor - Connection Manager

Clicking Columns page on OLE DB Source Editor will display the following error because the table ##tmpStateProvince specified in the source command variable does not exist and SSIS is unable to read the column definition.

Error message

To fix the error, execute the statement EXEC dbo.PopulateTempTable using SQL Server Management Studio (SSMS) on the database Sora so that the stored procedure will create the temporary table. After executing the stored procedure, click Columns page on OLE DB Source Editor, you will see the column information. Click OK.

OLE DB Source Editor - Columns

Drag and drop OLE DB Destination onto the Data Flow tab. Connect the green arrow from OLE DB Source to OLE DB Destination. Double-click OLE DB Destination to open OLE DB Destination Editor.

On the Connection Manager page of the OLE DB Destination Editor, perform the following actions.

  • Select KIWI\SQLSERVER2008R2.Sora from OLE DB Connection Manager
  • Select Table or view - fast load from Data access mode
  • Select [dbo].[StateProvince] from Name of the table or the view
  • Click Mappings page

OLE DB Destination Editor - Connection Manager

Click Mappings page on the OLE DB Destination Editor would automatically map the columns if the input and output column names are same. Click OK. Column StateProvinceID does not have a matching input column and it is defined as an IDENTITY column in database. Hence, no mapping is required.

OLE DB Destination Editor - Mappings

Data Flow tab should look something like this after configuring all the components.

Data Flow tab

Click the OLE DB Source on Data Flow tab and press F4 to view Properties. Set the property ValidateExternalMetadata to False so that SSIS would not try to check for the existence of the temporary table during validation phase of the package execution.

Set ValidateExternalMetadata

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the number of rows in the table. It should be empty before executing the package.

Rows in table before package execution

Execute the package. Control Flow shows successful execution.

Package Execution  - Control Flow tab

In Data Flow tab, you will notice that the package successfully processed 6 rows. The stored procedure created early in this posted inserted 6 rows into the temporary table.

Package Execution  - Data Flow tab

Execute the query select * from dbo.StateProvince in the SQL Server Management Studio (SSMS) to find the 6 rows successfully inserted into the table. The data should match with rows founds in the stored procedure.

Rows in table after package execution

The above example illustrated how to create and use temporary table within a package.

Select row with most recent date per user

I have done same thing like below

SELECT t1.* FROM lms_attendance t1 WHERE t1.id in (SELECT max(t2.id) as id FROM lms_attendance t2 group BY t2.user)

This will also reduce memory utilization.

Thanks.

How to update a menu item shown in the ActionBar?

To refresh menu from Fragment simply call:

getActivity().invalidateOptionsMenu();

Iterating through a range of dates in Python

Why are there two nested iterations? For me it produces the same list of data with only one iteration:

for single_date in (start_date + timedelta(n) for n in range(day_count)):
    print ...

And no list gets stored, only one generator is iterated over. Also the "if" in the generator seems to be unnecessary.

After all, a linear sequence should only require one iterator, not two.

Update after discussion with John Machin:

Maybe the most elegant solution is using a generator function to completely hide/abstract the iteration over the range of dates:

from datetime import timedelta, date

def daterange(start_date, end_date):
    for n in range(int((end_date - start_date).days)):
        yield start_date + timedelta(n)

start_date = date(2013, 1, 1)
end_date = date(2015, 6, 2)
for single_date in daterange(start_date, end_date):
    print(single_date.strftime("%Y-%m-%d"))

NB: For consistency with the built-in range() function this iteration stops before reaching the end_date. So for inclusive iteration use the next day, as you would with range().

Versioning SQL Server database

Every database should be under source-code control. What is lacking is a tool to automatically script all database objects - and "configuration data" - to file, which then can be added to any source control system. If you are using SQL Server, then my solution is here : http://dbsourcetools.codeplex.com/ . Have fun. - Nathan.

How do I do an insert with DATETIME now inside of SQL server mgmt studioÜ

Just use GETDATE() or GETUTCDATE() (if you want to get the "universal" UTC time, instead of your local server's time-zone related time).

INSERT INTO [Business]
           ([IsDeleted]
           ,[FirstName]
           ,[LastName]
           ,[LastUpdated]
           ,[LastUpdatedBy])
     VALUES
           (0, 'Joe', 'Thomas', 
           GETDATE(),  <LastUpdatedBy, nvarchar(50),>)

Equivalent of SQL ISNULL in LINQ?

Looks like the type is boolean and therefore can never be null and should be false by default.

Difference between Ctrl+Shift+F and Ctrl+I in Eclipse

Reformat affects the whole source code and may rebreak your lines, while Correct Indentation only affects the whitespace at the beginning of the lines.

HashMap - getting First Key value

Improving whoami's answer. Since findFirst() returns an Optional, it is a good practice to check if there is a value.

 var optional = pair.keySet().stream().findFirst();

 if (!optional.isPresent()) {
    return;
 }

 var key = optional.get();

Also, some commented that finding first key of a HashSet is unreliable. But sometimes we have HashMap pairs; i.e. in each map we have one key and one value. In such cases finding the first key of such a pair quickly is convenient.

How to execute a program or call a system command from Python

Update:

subprocess.run is the recommended approach as of Python 3.5 if your code does not need to maintain compatibility with earlier Python versions. It's more consistent and offers similar ease-of-use as Envoy. (Piping isn't as straightforward though. See this question for how.)

Here's some examples from the documentation.

Run a process:

>>> subprocess.run(["ls", "-l"])  # Doesn't capture output
CompletedProcess(args=['ls', '-l'], returncode=0)

Raise on failed run:

>>> subprocess.run("exit 1", shell=True, check=True)
Traceback (most recent call last):
  ...
subprocess.CalledProcessError: Command 'exit 1' returned non-zero exit status 1

Capture output:

>>> subprocess.run(["ls", "-l", "/dev/null"], stdout=subprocess.PIPE)
CompletedProcess(args=['ls', '-l', '/dev/null'], returncode=0,
stdout=b'crw-rw-rw- 1 root root 1, 3 Jan 23 16:23 /dev/null\n')

Original answer:

I recommend trying Envoy. It's a wrapper for subprocess, which in turn aims to replace the older modules and functions. Envoy is subprocess for humans.

Example usage from the README:

>>> r = envoy.run('git config', data='data to pipe in', timeout=2)

>>> r.status_code
129
>>> r.std_out
'usage: git config [options]'
>>> r.std_err
''

Pipe stuff around too:

>>> r = envoy.run('uptime | pbcopy')

>>> r.command
'pbcopy'
>>> r.status_code
0

>>> r.history
[<Response 'uptime'>]

Imported a csv-dataset to R but the values becomes factors

This only worked right for me when including strip.white = TRUE in the read.csv command.

(I found the solution here.)

How do I increase memory on Tomcat 7 when running as a Windows Service?

//ES/tomcat -> This may not work if you have changed the service name during the installation.

Either run the command without any service name

.\bin\tomcat7w.exe //ES

or with exact service name

.\bin\tomcat7w.exe //ES/YourServiceName

How to create bitmap from byte array?

In addition, you can simply convert byte array to Bitmap.

var bmp = new Bitmap(new MemoryStream(imgByte));

You can also get Bitmap from file Path directly.

Bitmap bmp = new Bitmap(Image.FromFile(filePath));

How to cast an Object to an int

Assuming the object is an Integer object, then you can do this:

int i = ((Integer) obj).intValue();

If the object isn't an Integer object, then you have to detect the type and convert it based on its type.

Create a folder inside documents folder in iOS apps

Swift 4.0

let paths = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)
// Get documents folder
let documentsDirectory: String = paths.first ?? ""
// Get your folder path
let dataPath = documentsDirectory + "/yourFolderName"
if !FileManager.default.fileExists(atPath: dataPath) {
    // Creates that folder if not exists
    try? FileManager.default.createDirectory(atPath: dataPath, withIntermediateDirectories: false, attributes: nil)
}

How to Sort Multi-dimensional Array by Value?

function aasort (&$array, $key) {
    $sorter=array();
    $ret=array();
    reset($array);
    foreach ($array as $ii => $va) {
        $sorter[$ii]=$va[$key];
    }
    asort($sorter);
    foreach ($sorter as $ii => $va) {
        $ret[$ii]=$array[$ii];
    }
    $array=$ret;
}

aasort($your_array,"order");

Generic Interface

As an answer strictly in line with your question, I support cleytus's proposal.


You could also use a marker interface (with no method), say DistantCall, with several several sub-interfaces that have the precise signatures you want.

  • The general interface would serve to mark all of them, in case you want to write some generic code for all of them.
  • The number of specific interfaces can be reduced by using cleytus's generic signature.

Examples of 'reusable' interfaces:

    public interface DistantCall {
    }

    public interface TUDistantCall<T,U> extends DistantCall {
      T execute(U... us);
    }

    public interface UDistantCall<U> extends DistantCall {
      void execute(U... us);
    }

    public interface TDistantCall<T> extends DistantCall {
      T execute();
    }

    public interface TUVDistantCall<T, U, V> extends DistantCall {
      T execute(U u, V... vs);
    }
    ....

UPDATED in response to OP comment

I wasn't thinking of any instanceof in the calling. I was thinking your calling code knew what it was calling, and you just needed to assemble several distant call in a common interface for some generic code (for example, auditing all distant calls, for performance reasons). In your question, I have seen no mention that the calling code is generic :-(

If so, I suggest you have only one interface, only one signature. Having several would only bring more complexity, for nothing.

However, you need to ask yourself some broader questions :
how you will ensure that caller and callee do communicate correctly?

That could be a follow-up on this question, or a different question...

Add Favicon with React and Webpack

The correct answer in the present if you dont use Create React App is the next:

new HtmlWebpackPlugin({
   favicon: "./public/fav-icon.ico"
})

If you use CRA then you can modificate the manifest.json in the public directory

Array of PHP Objects

Arrays can hold pointers so when I want an array of objects I do that.

$a = array();
$o = new Whatever_Class();
$a[] = &$o;
print_r($a);

This will show that the object is referenced and accessible through the array.

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

DISABLE the Horizontal Scroll

this is the nasty child of your code :)

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 1170px;
}

replace it with

.container, .navbar-static-top .container, .navbar-fixed-top .container, .navbar-fixed-bottom .container {
width: 100%;
}

Change the borderColor of the TextBox

try this

bool focus = false;
private void Form1_Paint(object sender, PaintEventArgs e)
{
    if (focus)
    {
        textBox1.BorderStyle = BorderStyle.None;
        Pen p = new Pen(Color.Red);
        Graphics g = e.Graphics;
        int variance = 3;
        g.DrawRectangle(p, new Rectangle(textBox1.Location.X - variance, textBox1.Location.Y - variance, textBox1.Width + variance, textBox1.Height +variance ));
    }
    else
    {
        textBox1.BorderStyle = BorderStyle.FixedSingle;
    }
}

private void textBox1_Enter(object sender, EventArgs e)
{
    focus = true;
    this.Refresh();
}

private void textBox1_Leave(object sender, EventArgs e)
{
    focus = false;
    this.Refresh();
}

What are the differences between normal and slim package of jquery?

I could see $.ajax is removed from jQuery slim 3.2.1

From the jQuery docs

You can also use the slim build, which excludes the ajax and effects modules

Below is the comment from the slim version with the features removed

/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */

Load a WPF BitmapImage from a System.Drawing.Bitmap

I came to this question because I was trying to do the same, but in my case the Bitmap is from a resource/file. I found the best solution is as described in the following link:

http://msdn.microsoft.com/en-us/library/system.windows.media.imaging.bitmapimage.aspx

// Create the image element.
Image simpleImage = new Image();    
simpleImage.Width = 200;
simpleImage.Margin = new Thickness(5);

// Create source.
BitmapImage bi = new BitmapImage();
// BitmapImage.UriSource must be in a BeginInit/EndInit block.
bi.BeginInit();
bi.UriSource = new Uri(@"/sampleImages/cherries_larger.jpg",UriKind.RelativeOrAbsolute);
bi.EndInit();
// Set the image source.
simpleImage.Source = bi;

Android how to use Environment.getExternalStorageDirectory()

As described in Documentation Environment.getExternalStorageDirectory() :

Environment.getExternalStorageDirectory() Return the primary shared/external storage directory.

This is an example of how to use it reading an image :

String fileName = "stored_image.jpg";
 String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
 String pathDir = baseDir + "/Android/data/com.mypackage.myapplication/";

 File f = new File(pathDir + File.separator + fileName);

        if(f.exists()){
          Log.d("Application", "The file " + file.getName() + " exists!";
         }else{
          Log.d("Application", "The file no longer exists!";
         }

Easiest way to read/write a file's content in Python

Use pathlib.

Python 3.5 and above:

from pathlib import Path
contents = Path(file_path).read_text()

For lower versions of Python use pathlib2:

$ pip install pathlib2

Then

from pathlib2 import Path
contents = Path(file_path).read_text()

Writing is just as easy:

Path(file_path).write_text('my text')

how to draw a rectangle in HTML or CSS?

You need to identify your sections and then style them with CSS. In this case, this might work:

HTML

<div id="blueRectangle"></div>

CSS

#blueRectangle {
    background: #4679BD;
    min-height: 50px;
    //width: 100%;
}

http://jsfiddle.net/7PJ5q/

Make a div fill up the remaining width

Although a bit late in posting an answer, here is an alternative approach without using margins.

<style>
    #divMain { width: 500px; }
    #div1 { width: 100px; float: left; background-color: #fcc; }
    #div2 { overflow:hidden; background-color: #cfc; }
    #div3 { width: 100px; float: right; background-color: #ccf; }
</style>

<div id="divMain">
    <div id="div1">
        div 1
    </div>
    <div id="div3">
        div 3
    </div>
    <div id="div2">
        div 2<br />bit taller
    </div>
</div>

This method works like magic, but here is an explanation :)\

Fiddle with a similar sample here.

Setting values on a copy of a slice from a DataFrame

This warning comes because your dataframe x is a copy of a slice. This is not easy to know why, but it has something to do with how you have come to the current state of it.

You can either create a proper dataframe out of x by doing

x = x.copy()

This will remove the warning, but it is not the proper way

You should be using the DataFrame.loc method, as the warning suggests, like this:

x.loc[:,'Mass32s'] = pandas.rolling_mean(x.Mass32, 5).shift(-2)

Java Currency Number format

Yes. You can use java.util.formatter. You can use a formatting string like "%10.2f"

TypeError: $(...).on is not a function

In my case this code solved my error :

(function (window, document, $) {
            'use strict';
             var $html = $('html');
             $('input[name="myiCheck"]').on('ifClicked', function (event) {
             alert("You clicked " + this.value);
             });
})(window, document, jQuery);

You don't should put your function inside $(document).ready

How can I access and process nested objects, arrays or JSON?

You can use the syntax jsonObject.key to access the the value. And if you want access a value from an array, then you can use the syntax jsonObjectArray[index].key.

Here are the code examples to access various values to give you the idea.

_x000D_
_x000D_
        var data = {_x000D_
            code: 42,_x000D_
            items: [{_x000D_
                id: 1,_x000D_
                name: 'foo'_x000D_
            }, {_x000D_
                id: 2,_x000D_
                name: 'bar'_x000D_
            }]_x000D_
        };_x000D_
_x000D_
        // if you want 'bar'_x000D_
        console.log(data.items[1].name);_x000D_
_x000D_
        // if you want array of item names_x000D_
        console.log(data.items.map(x => x.name));_x000D_
_x000D_
        // get the id of the item where name = 'bar'_x000D_
        console.log(data.items.filter(x => (x.name == "bar") ? x.id : null)[0].id);
_x000D_
_x000D_
_x000D_

:first-child not working as expected

You could wrap your h1 tags in another div and then the first one would be the first-child. That div doesn't even need styles. It's just a way to segregate those children.

<div class="h1-holder">
    <h1>Title 1</h1>
    <h1>Title 2</h1>
</div>

Cannot open new Jupyter Notebook [Permission Denied]

Executing the script below worked for me.

sudo chown $USER /home/$USER/.jupyter

How can I upgrade specific packages using pip and a requirements file?

I ran the following command and it upgraded from 1.2.3 to 1.4.0

pip install Django --upgrade

Shortcut for upgrade:

pip install Django -U

Note: if the package you are upgrading has any requirements this command will additionally upgrade all the requirements to the latest versions available. In recent versions of pip, you can prevent this behavior by specifying --upgrade-strategy only-if-needed. With that flag, dependencies will not be upgraded unless the installed versions of the dependent packages no longer satisfy the requirements of the upgraded package.

Why doesn't Python have multiline comments?

There should only be one way to do a thing, is contradicted by the usage of multiline strings and single line strings or switch/case and if, different form of loops.

Multiline comments are a pretty common feature and lets face it the multiline string comment is a hack with negative sideffects! I have seen lots of code doing the multiline comment trick and even editors use it.

But I guess every language has its quirks where the devs insist on never fixing it. I know such quirks from the java side as well, which have been open since the late 90s, never to be fixed!

Display JSON as HTML

For the syntax highlighting, use code prettify. I believe this is what StackOverflow uses for its code highlighting.

  1. Wrap your formatted JSON in code blocks and give them the "prettyprint" class.
  2. Include prettify.js in your page.
  3. Make sure your document's body tag calls prettyPrint() when it loads

You will have syntax highlighted JSON in the format you have laid out in your page. See here for an example. So if you had a code block like this:

<code class="prettyprint">
    var jsonObj = {
        "height" : 6.2,
        "width" : 7.3,
        "length" : 9.1,
        "color" : {
            "r" : 255,
            "g" : 200,
            "b" : 10
        }
    }
</code>

It would look like this:

var jsonObj = {
    "height" : 6.2,
    "width" : 7.3,
    "length" : 9.1,
    "color" : {
        "r" : 255,
        "g" : 200,
        "b" : 10
    }
}

This doesn't help with the indenting, but the other answers seem to be addressing that.

Stopping Excel Macro executution when pressing Esc won't work

Use CRTL+BREAK to suspend execution at any point. You will be put into break mode and can press F5 to continue the execution or F8 to execute the code step-by-step in the visual debugger.

Of course this only works when there is no message box open, so if your VBA code constantly opens message boxes for some reason it will become a little tricky to press the keys at the right moment.

You can even edit most of the code while it is running.

Use Debug.Print to print out messages to the Immediate Window in the VBA editor, that's way more convenient than MsgBox.

Use breakpoints or the Stop keyword to automatically halt execution in interesting areas.

You can use Debug.Assert to halt execution conditionally.

javax.net.ssl.SSLException: Received fatal alert: protocol_version

On Java 1.8 default TLS protocol is v1.2. On Java 1.6 and 1.7 default is obsoleted TLS1.0. I get this error on Java 1.8, because url use old TLS1.0 (like Your - You see ClientHello, TLSv1). To resolve this error You need to use override defaults for Java 1.8.

System.setProperty("https.protocols", "TLSv1");

More info on the Oracle blog.

JSTL if tag for equal strings

I think the other answers miss one important detail regarding the property name to use in the EL expression. The rules for converting from the method names to property names are specified in 'Introspector.decpitalize` which is part of the java bean standard:

This normally means converting the first character from upper case to lower case, but in the (unusual) special case when there is more than one character and both the first and second characters are upper case, we leave it alone.

Thus "FooBah" becomes "fooBah" and "X" becomes "x", but "URL" stays as "URL".

So in your case the JSTL code should look like the following, note the capital 'P':

<c:if test = "${ansokanInfo.PSystem == 'NAT'}">

Get img thumbnails from Vimeo?

In javascript (uses jQuery):

function vimeoLoadingThumb(id){    
    var url = "http://vimeo.com/api/v2/video/" + id + ".json?callback=showThumb";

    var id_img = "#vimeo-" + id;

    var script = document.createElement( 'script' );
    script.src = url;

    $(id_img).before(script);
}


function showThumb(data){
    var id_img = "#vimeo-" + data[0].id;
    $(id_img).attr('src',data[0].thumbnail_medium);
}

To display it :

<img id="vimeo-{{ video.id_video }}" src="" alt="{{ video.title }}" />
<script type="text/javascript">
  vimeoLoadingThumb({{ video.id_video }});
</script>

What is reflection and why is it useful?

I want to answer this question by example. First of all Hibernate project uses Reflection API to generate CRUD statements to bridge the chasm between the running application and the persistence store. When things change in the domain, the Hibernate has to know about them to persist them to the data store and vice versa.

Alternatively works Lombok Project. It just injects code at compile time, result in code being inserted into your domain classes. (I think it is OK for getters and setters)

Hibernate chose reflection because it has minimal impact on the build process for an application.

And from Java 7 we have MethodHandles, which works as Reflection API. In projects, to work with loggers we just copy-paste the next code:

Logger LOGGER = Logger.getLogger(MethodHandles.lookup().lookupClass().getName());

Because it is hard to make typo-error in this case.

How can I use querySelector on to pick an input element by name?

So ... you need to change some things in your code

<form method="POST" id="form-pass">
Password: <input type="text" name="pwd" id="input-pwd">
<input type="submit" value="Submit">
</form>

<script>
var form = document.querySelector('#form-pass');
var pwd = document.querySelector('#input-pwd');
pwd.focus();
form.onsubmit = checkForm;

function checkForm() {
  alert(pwd.value);
}
</script>

Try this way.

How to add an element to a list?

import json

myDict = {'dict': [{'a': 'none', 'b': 'none', 'c': 'none'}]}
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}]}

myDict['dict'].append(({'a': 'aaaa', 'b': 'aaaa', 'c': 'aaaa'}))
test = json.dumps(myDict)
print(test)

{"dict": [{"a": "none", "b": "none", "c": "none"}, {"a": "aaaa", "b": "aaaa", "c": "aaaa"}]}

Why aren't Xcode breakpoints functioning?

I have a lot of problems with breakpoints in Xcode (2.4.1). I use a project that just contains other projects (like a Solution in Visual Studio). I find sometimes that breakpoints don't work at all unless there is at least one breakpoint set in the starting project (i.e. the one containing the entry point for my code). If the only breakpoints are in "lower level" projects, they just get ignored.

It also seems as if Xcode only handles breakpoint operations correctly if you act on the breakpoint when you're in the project that contains the source line the breakpoint's on.

If I try deleting or disabling breakpoints via another project, the action sometimes doesn't take effect, even though the debugger indicates that it has. So I will find myself breaking on disabled breakpoints, or on a (now invisible) breakpoint that I removed earlier.

HttpClient won't import in Android Studio

If you need sdk 23, add this to your gradle:

android {
    useLibrary 'org.apache.http.legacy'
}

What is the difference between signed and unsigned variables?

Signed variables use one bit to flag whether they are positive or negative. Unsigned variables don't have this bit, so they can store larger numbers in the same space, but only nonnegative numbers, e.g. 0 and higher.

For more: Unsigned and Signed Integers

How to include SCSS file in HTML

You can't have a link to SCSS File in your HTML page.You have to compile it down to CSS First. No there are lots of video tutorials you might want to check out. Lynda provides great video tutorials on SASS. there are also free screencasts you can google...

For official documentation visit this site http://sass-lang.com/documentation/file.SASS_REFERENCE.html And why have you chosen notepad to write Sass?? you can easily download some free text editors for better code handling.

To prevent a memory leak, the JDBC Driver has been forcibly unregistered

I found that implementing a simple destroy() method to de-register any JDBC drivers works nicely.

/**
 * Destroys the servlet cleanly by unloading JDBC drivers.
 * 
 * @see javax.servlet.GenericServlet#destroy()
 */
public void destroy() {
    String prefix = getClass().getSimpleName() +" destroy() ";
    ServletContext ctx = getServletContext();
    try {
        Enumeration<Driver> drivers = DriverManager.getDrivers();
        while(drivers.hasMoreElements()) {
            DriverManager.deregisterDriver(drivers.nextElement());
        }
    } catch(Exception e) {
        ctx.log(prefix + "Exception caught while deregistering JDBC drivers", e);
    }
    ctx.log(prefix + "complete");
}

How do you log content of a JSON object in Node.js?

This will for most of the objects for outputting in nodejs console

_x000D_
_x000D_
var util = require('util')_x000D_
function print (data){_x000D_
  console.log(util.inspect(data,true,12,true))_x000D_
  _x000D_
}_x000D_
_x000D_
print({name : "Your name" ,age : "Your age"})
_x000D_
_x000D_
_x000D_

Error: "Adb connection Error:An existing connection was forcibly closed by the remote host"

Looks like the installed driver was in bad state. Here is what I did to make it work:

  1. Delete the device from Device Manager.
  2. Rescan for hardware changes.
  3. "Slate 21" will show up with "Unknown driver" status.
  4. Click on "Update Driver" and select /extras/google/usb_driver
  5. Device Manager will find the driver and warn you about installing it. Select "Yes."

This time the device got installed properly.

Note that I didn't have to modify winusb.inf file or update any other driver.

Hope this helps.

How to import a csv file into MySQL workbench?

In case you have smaller data set, a way to achieve it by GUI is:

  1. Open a query window
  2. SELECT * FROM [table_name]
  3. Select Import from the menu bar
  4. Press Apply on the bottom right below the Result Grid

enter image description here

Reference: http://www.youtube.com/watch?v=tnhJa_zYNVY

Calling onclick on a radiobutton list using javascript

The problem here is that the rendering of a RadioButtonList wraps the individual radio buttons (ListItems) in span tags and even when you assign a client-side event handler to the list item directly using Attributes it assigns the event to the span. Assigning the event to the RadioButtonList assigns it to the table it renders in.

The trick here is to add the ListItems on the aspx page and not from the code behind. You can then assign the JavaScript function to the onClick property. This blog post; attaching client-side event handler to radio button list by Juri Strumpflohner explains it all.

This only works if you know the ListItems in advance and does not help where the items in the RadioButtonList need to be dynamically added using the code behind.

How do I remove a CLOSE_WAIT socket connection

I'm also having the same issue with a very latest Tomcat server (7.0.40). It goes non-responsive once for a couple of days.

To see open connections, you may use:

sudo netstat -tonp | grep jsvc | grep --regexp="127.0.0.1:443" --regexp="127.0.0.1:80" | grep CLOSE_WAIT

As mentioned in this post, you may use /proc/sys/net/ipv4/tcp_keepalive_time to view the values. The value seems to be in seconds and defaults to 7200 (i.e. 2 hours).

To change them, you need to edit /etc/sysctl.conf.

Open/create `/etc/sysctl.conf`
Add `net.ipv4.tcp_keepalive_time = 120` and save the file
Invoke `sysctl -p /etc/sysctl.conf`
Verify using `cat /proc/sys/net/ipv4/tcp_keepalive_time`

Can I obtain method parameter name using Java reflection?

In Java 8 you can do the following:

import java.lang.reflect.Method;
import java.lang.reflect.Parameter;
import java.util.ArrayList;
import java.util.List;

public final class Methods {

    public static List<String> getParameterNames(Method method) {
        Parameter[] parameters = method.getParameters();
        List<String> parameterNames = new ArrayList<>();

        for (Parameter parameter : parameters) {
            if(!parameter.isNamePresent()) {
                throw new IllegalArgumentException("Parameter names are not present!");
            }

            String parameterName = parameter.getName();
            parameterNames.add(parameterName);
        }

        return parameterNames;
    }

    private Methods(){}
}

So for your class Whatever we can do a manual test:

import java.lang.reflect.Method;

public class ManualTest {
    public static void main(String[] args) {
        Method[] declaredMethods = Whatever.class.getDeclaredMethods();

        for (Method declaredMethod : declaredMethods) {
            if (declaredMethod.getName().equals("aMethod")) {
                System.out.println(Methods.getParameterNames(declaredMethod));
                break;
            }
        }
    }
}

which should print [aParam] if you have passed -parameters argument to your Java 8 compiler.

For Maven users:

<properties>
    <!-- PLUGIN VERSIONS -->
    <maven-compiler-plugin.version>3.1</maven-compiler-plugin.version>

    <!-- OTHER PROPERTIES -->
    <java.version>1.8</java.version>
</properties>

<build>
    <plugins>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>${maven-compiler-plugin.version}</version>
            <configuration>
                <!-- Original answer -->
                <compilerArgument>-parameters</compilerArgument>
                <!-- Or, if you use the plugin version >= 3.6.2 -->
                <parameters>true</parameters>
                <testCompilerArgument>-parameters</testCompilerArgument>
                <source>${java.version}</source>
                <target>${java.version}</target>
            </configuration>
        </plugin>
    </plugins>
</build>

For more information see following links:

  1. Official Java Tutorial: Obtaining Names of Method Parameters
  2. JEP 118: Access to Parameter Names at Runtime
  3. Javadoc for Parameter class

How to stop a thread created by implementing runnable interface?

Stopping (Killing) a thread mid-way is not recommended. The API is actually deprecated.

However,you can get more details including workarounds here: How do you kill a thread in Java?

How do you connect localhost in the Android emulator?

This is what finally worked for me.

  • Backend running on localhost:8080
  • Fetch your IP address (ipconfig on Windows)

enter image description here

  • Configure your Android emulator's proxy to use your IP address as host name and the port your backend is running on as port (in my case: 192.168.1.86:8080 enter image description here

  • Have your Android app send requests to the same URL (192.168.1.86:8080) (sending requests to localhost, and http://10.0.2.2 did not work for me)

automatically execute an Excel macro on a cell change

Handle the Worksheet_Change event or the Workbook_SheetChange event.

The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.

header location not working in my php code

Create config.php and put the code it will work

How to print all key and values from HashMap in Android?

public void dumpMe(Map m) { dumpMe(m, ""); }

private void dumpMe(Map m, String padding) 
{
    Set s = m.keySet();
    java.util.Iterator ir = s.iterator();
    while (ir.hasNext()) 
    {
        String key = (String) ir.next();
        AttributeValue value = (AttributeValue)m.get(key);
        if (value == null) 
            continue;
        if (value.getM() != null)
        {
            System.out.println (padding + key + " = {");
            dumpMe((Map)value, padding + "  ");
            System.out.println(padding + "}");          
        }
        else if (value.getS() != null  ||
                 value.getN() != null ) 
        {
            System.out.println(padding + key + " = " + value.toString());
        }
        else 
        { 
            System.out.println(padding + key + " = UNKNOWN OBJECT: " + value.toString());
            // You could also throw an exception here
        }      
    } // while
}

//This code worked for me.

Parsing JSON using Json.net

I don't know about JSON.NET, but it works fine with JavaScriptSerializer from System.Web.Extensions.dll (.NET 3.5 SP1):

using System.Collections.Generic;
using System.Web.Script.Serialization;
public class NameTypePair
{
    public string OBJECT_NAME { get; set; }
    public string OBJECT_TYPE { get; set; }
}
public enum PositionType { none, point }
public class Ref
{
    public int id { get; set; }
}
public class SubObject
{
    public NameTypePair attributes { get; set; }
    public Position position { get; set; }
}
public class Position
{
    public int x { get; set; }
    public int y { get; set; }
}
public class Foo
{
    public Foo() { objects = new List<SubObject>(); }
    public string displayFieldName { get; set; }
    public NameTypePair fieldAliases { get; set; }
    public PositionType positionType { get; set; }
    public Ref reference { get; set; }
    public List<SubObject> objects { get; set; }
}
static class Program
{

    const string json = @"{
  ""displayFieldName"" : ""OBJECT_NAME"", 
  ""fieldAliases"" : {
    ""OBJECT_NAME"" : ""OBJECT_NAME"", 
    ""OBJECT_TYPE"" : ""OBJECT_TYPE""
  }, 
  ""positionType"" : ""point"", 
  ""reference"" : {
    ""id"" : 1111
  }, 
  ""objects"" : [
    {
      ""attributes"" : {
        ""OBJECT_NAME"" : ""test name"", 
        ""OBJECT_TYPE"" : ""test type""
      }, 
      ""position"" : 
      {
        ""x"" : 5, 
        ""y"" : 7
      }
    }
  ]
}";


    static void Main()
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();
        Foo foo = ser.Deserialize<Foo>(json);
    }


}

Edit:

Json.NET works using the same JSON and classes.

Foo foo = JsonConvert.DeserializeObject<Foo>(json);

Link: Serializing and Deserializing JSON with Json.NET

LPCSTR, LPCTSTR and LPTSTR

Quick and dirty:

LP == Long Pointer. Just think pointer or char*

C = Const, in this case, I think they mean the character string is a const, not the pointer being const.

STR is string

the T is for a wide character or char (TCHAR) depending on compile options.

ECMAScript 6 class destructor

I just came across this question in a search about destructors and I thought there was an unanswered part of your question in your comments, so I thought I would address that.

thank you guys. But what would be a good convention if ECMAScript doesn't have destructors? Should I create a method called destructor and call it manually when I'm done with the object? Any other idea?

If you want to tell your object that you are now done with it and it should specifically release any event listeners it has, then you can just create an ordinary method for doing that. You can call the method something like release() or deregister() or unhook() or anything of that ilk. The idea is that you're telling the object to disconnect itself from anything else it is hooked up to (deregister event listeners, clear external object references, etc...). You will have to call it manually at the appropriate time.

If, at the same time you also make sure there are no other references to that object, then your object will become eligible for garbage collection at that point.

ES6 does have weakMap and weakSet which are ways of keeping track of a set of objects that are still alive without affecting when they can be garbage collected, but it does not provide any sort of notification when they are garbage collected. They just disappear from the weakMap or weakSet at some point (when they are GCed).


FYI, the issue with this type of destructor you ask for (and probably why there isn't much of a call for it) is that because of garbage collection, an item is not eligible for garbage collection when it has an open event handler against a live object so even if there was such a destructor, it would never get called in your circumstance until you actually removed the event listeners. And, once you've removed the event listeners, there's no need for the destructor for this purpose.

I suppose there's a possible weakListener() that would not prevent garbage collection, but such a thing does not exist either.


FYI, here's another relevant question Why is the object destructor paradigm in garbage collected languages pervasively absent?. This discussion covers finalizer, destructor and disposer design patterns. I found it useful to see the distinction between the three.


Edit in 2020 - proposal for object finalizer

There is a Stage 3 EMCAScript proposal to add a user-defined finalizer function after an object is garbage collected.

A canonical example of something that would benefit from a feature like this is an object that contains a handle to an open file. If the object is garbage collected (because no other code still has a reference to it), then this finalizer scheme allows one to at least put a message to the console that an external resource has just been leaked and code elsewhere should be fixed to prevent this leak.

If you read the proposal thoroughly, you will see that it's nothing like a full-blown destructor in a language like C++. This finalizer is called after the object has already been destroyed and you have to predetermine what part of the instance data needs to be passed to the finalizer for it to do its work. Further, this feature is not meant to be relied upon for normal operation, but rather as a debugging aid and as a backstop against certain types of bugs. You can read the full explanation for these limitations in the proposal.

The container 'Maven Dependencies' references non existing library - STS

Although it's too late , But here is my experience .

Whenever you get your maven project from a source controller or just copying your project from one machine to another , you need to update the dependencies .

For this Right-click on Project on project explorer -> Maven -> Update Project.

Please consider checking the "Force update of snapshot/releases" checkbox.

If you have not your dependencies in m2/repository then you need internet connection to get from the remote maven repository.

In case you have get from the source controller and you have not any unit test , It's probably your test folder does not include in the source controller in the first place , so you don't have those in the new repository.so you need to create those folders manually.

I have had both these cases .

How can I display a JavaScript object?

var output = '';
for (var property in object) {
  output += property + ': ' + object[property]+'; ';
}
alert(output);

Eclipse error: "The import XXX cannot be resolved"

This has solved my issue.

1) clean project Project -> clean...

2) Right click on project -> BuildPath -> Configure BuildPath -> Libraries tab -> Double click on JRE SYSTEM LIBRARY -> Then select alternate JRE

3) Click Save

4) Again go to your project in project explorer and right click to project -> BuildPath -> Configure BuildPath -> Libraries tab -> Double click on JRE SYSTEM LIBRARY -> This time select "Execution Environment"

5) Apply

Entity Framework Migrations renaming tables and columns

In EF Core, I use the following statements to rename tables and columns:

As for renaming tables:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameTable(name: "OldTableName", schema: "dbo", newName: "NewTableName", newSchema: "dbo");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameTable(name: "NewTableName", schema: "dbo", newName: "OldTableName", newSchema: "dbo");
    }

As for renaming columns:

    protected override void Up(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(name: "OldColumnName", table: "TableName", newName: "NewColumnName", schema: "dbo");
    }

    protected override void Down(MigrationBuilder migrationBuilder)
    {
        migrationBuilder.RenameColumn(name: "NewColumnName", table: "TableName", newName: "OldColumnName", schema: "dbo");
    }

jQuery - Get Width of Element when Not Visible (Display: None)

Thank you for posting the realWidth function above, it really helped me. Based on "realWidth" function above, I wrote, a CSS reset, (reason described below).

function getUnvisibleDimensions(obj) {
    if ($(obj).length == 0) {
        return false;
    }

    var clone = obj.clone();
    clone.css({
        visibility:'hidden',
        width : '',
        height: '',
        maxWidth : '',
        maxHeight: ''
    });
    $('body').append(clone);
    var width = clone.outerWidth(),
        height = clone.outerHeight();
    clone.remove();
    return {w:width, h:height};
}

"realWidth" gets the width of an existing tag. I tested this with some image tags. The problem was, when the image has given CSS dimension per width (or max-width), you will never get the real dimension of that image. Perhaps, the img has "max-width: 100%", the "realWidth" function clone it and append it to the body. If the original size of the image is bigger than the body, then you get the size of the body and not the real size of that image.

Finding rows that don't contain numeric data in Oracle

In contrast to SGB's answer, I prefer doing the regexp defining the actual format of my data and negating that. This allows me to define values like $DDD,DDD,DDD.DD In the OPs simple scenario, it would look like

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^[0-9]+$');

which finds all non-positive integers. If you wau accept negatiuve integers also, it's an easy change, just add an optional leading minus.

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+$');

accepting floating points...

SELECT * 
FROM table_with_column_to_search 
WHERE NOT REGEXP_LIKE(varchar_col_with_non_numerics, '^-?[0-9]+(\.[0-9]+)?$');

Same goes further with any format. Basically, you will generally already have the formats to validate input data, so when you will desire to find data that does not match that format ... it's simpler to negate that format than come up with another one; which in case of SGB's approach would be a bit tricky to do if you want more than just positive integers.

how to read System environment variable in Spring applicationContext

In your bean definition, make sure to include "searchSystemEnvironment" and set it to "true". And if you're using it to build a path to a file, specify it as a file:/// url.

So for example, if you have a config file located in

/testapp/config/my.app.config.properties

then set an environment variable like so:

MY_ENV_VAR_PATH=/testapp/config

and your app can load the file using a bean definition like this:

e.g.

<bean class="org.springframework.web.context.support.ServletContextPropertyPlaceholderConfigurer">
    <property name="systemPropertiesModeName" value="SYSTEM_PROPERTIES_MODE_OVERRIDE" />
    <property name="searchSystemEnvironment" value="true" />
    <property name="searchContextAttributes" value="true" />
    <property name="contextOverride" value="true" />
    <property name="ignoreResourceNotFound" value="true" />
    <property name="locations">
        <list>
            <value>file:///${MY_ENV_VAR_PATH}/my.app.config.properties</value>
        </list>
    </property>
</bean>

Group by & count function in sqlalchemy

You can also count on multiple groups and their intersection:

self.session.query(func.count(Table.column1),Table.column1, Table.column2).group_by(Table.column1, Table.column2).all()

The query above will return counts for all possible combinations of values from both columns.

jQuery UI DatePicker to show month year only

Is it just me or is this not working as it should in IE(8)? The date changes when clicking done, but the datepicker opens up again, until you actually click somewhere in the page to loose focus on the input field...

I'm looking in to solving this.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.1/jquery.js"></script>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/jquery-ui.min.js"></script>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.7.2/themes/base/jquery-ui.css">
<script type="text/javascript">
$(function() {
    $('.date-picker').datepicker( {
        changeMonth: true,
        changeYear: true,
        showButtonPanel: true,
        dateFormat: 'MM yy',
        onClose: function(dateText, inst) { 
            var month = $("#ui-datepicker-div .ui-datepicker-month :selected").val();
            var year = $("#ui-datepicker-div .ui-datepicker-year :selected").val();
            $(this).datepicker('setDate', new Date(year, month, 1));
        }
    });
});
</script>
<style>
.ui-datepicker-calendar {
    display: none;
    }
</style>
</head>
<body>
    <label for="startDate">Date :</label>
    <input name="startDate" id="startDate" class="date-picker" />
</body>
</html>

Shrink a YouTube video to responsive width

You can make YouTube videos responsive with CSS. Wrap the iframe in a div with the class of "videowrapper" and apply the following styles:

.videowrapper {
    float: none;
    clear: both;
    width: 100%;
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 25px;
    height: 0;
}
.videowrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

The .videowrapper div should be inside a responsive element. The padding on the .videowrapper is necessary to keep the video from collapsing. You may have to tweak the numbers depending upon your layout.

Algorithm to convert RGB to HSV and HSV to RGB in range 0-255 for both

Here's a C implementation based on Agoston's Computer Graphics and Geometric Modeling: Implementation and Algorithms p. 304, with H ? [0, 360] and S,V ? [0, 1].

#include <math.h>

typedef struct {
    double r;       // ? [0, 1]
    double g;       // ? [0, 1]
    double b;       // ? [0, 1]
} rgb;

typedef struct {
    double h;       // ? [0, 360]
    double s;       // ? [0, 1]
    double v;       // ? [0, 1]
} hsv;

rgb hsv2rgb(hsv HSV)
{
    rgb RGB;
    double H = HSV.h, S = HSV.s, V = HSV.v,
            P, Q, T,
            fract;

    (H == 360.)?(H = 0.):(H /= 60.);
    fract = H - floor(H);

    P = V*(1. - S);
    Q = V*(1. - S*fract);
    T = V*(1. - S*(1. - fract));

    if      (0. <= H && H < 1.)
        RGB = (rgb){.r = V, .g = T, .b = P};
    else if (1. <= H && H < 2.)
        RGB = (rgb){.r = Q, .g = V, .b = P};
    else if (2. <= H && H < 3.)
        RGB = (rgb){.r = P, .g = V, .b = T};
    else if (3. <= H && H < 4.)
        RGB = (rgb){.r = P, .g = Q, .b = V};
    else if (4. <= H && H < 5.)
        RGB = (rgb){.r = T, .g = P, .b = V};
    else if (5. <= H && H < 6.)
        RGB = (rgb){.r = V, .g = P, .b = Q};
    else
        RGB = (rgb){.r = 0., .g = 0., .b = 0.};

    return RGB;
}

NoSQL Use Case Scenarios or WHEN to use NoSQL

It really is an "it depends" kinda question. Some general points:

  • NoSQL is typically good for unstructured/"schemaless" data - usually, you don't need to explicitly define your schema up front and can just include new fields without any ceremony
  • NoSQL typically favours a denormalised schema due to no support for JOINs per the RDBMS world. So you would usually have a flattened, denormalized representation of your data.
  • Using NoSQL doesn't mean you could lose data. Different DBs have different strategies. e.g. MongoDB - you can essentially choose what level to trade off performance vs potential for data loss - best performance = greater scope for data loss.
  • It's often very easy to scale out NoSQL solutions. Adding more nodes to replicate data to is one way to a) offer more scalability and b) offer more protection against data loss if one node goes down. But again, depends on the NoSQL DB/configuration. NoSQL does not necessarily mean "data loss" like you infer.
  • IMHO, complex/dynamic queries/reporting are best served from an RDBMS. Often the query functionality for a NoSQL DB is limited.
  • It doesn't have to be a 1 or the other choice. My experience has been using RDBMS in conjunction with NoSQL for certain use cases.
  • NoSQL DBs often lack the ability to perform atomic operations across multiple "tables".

You really need to look at and understand what the various types of NoSQL stores are, and how they go about providing scalability/data security etc. It's difficult to give an across-the-board answer as they really are all different and tackle things differently.

For MongoDb as an example, check out their Use Cases to see what they suggest as being "well suited" and "less well suited" uses of MongoDb.

How do I resolve a TesseractNotFoundError?

I faced the same problem. I hope you have installed from here and have also done pip install pytesseract.

If everything is fine you should see that the path C:\Program Files (x86)\Tesseract-OCR where tesseract.exe is available.

Adding Path variable did not helped me, I actually added new variable with name tesseract in environment variables with a value of C:\Program Files (x86)\Tesseract-OCR\tesseract.exe.

Typing tesseract in the command line should now work as expected by giving you usage informations. You can now use pytesseract as such (don't forget to restart your python kernel before running this!):

import pytesseract
from PIL import Image

value=Image.open("text_image.png")
text = pytesseract.image_to_string(value, config='')    
print("text present in images:",text)

enjoy!

How can I get the index from a JSON object with value?

Once you have a json object

obj.valueOf(Object.keys(obj).indexOf('String_to_Find'))

Display current date and time without punctuation

Here you go:

date +%Y%m%d%H%M%S

As man date says near the top, you can use the date command like this:

date [OPTION]... [+FORMAT]

That is, you can give it a format parameter, starting with a +. You can probably guess the meaning of the formatting symbols I used:

  • %Y is for year
  • %m is for month
  • %d is for day
  • ... and so on

You can find this, and other formatting symbols in man date.

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

Run multiple python scripts concurrently

I am working in Windows 7 with Python IDLE. I have two programs,

# progA
while True:
    m = input('progA is running ')
    print (m)

and

# progB
while True:
    m = input('progB is running ')
    print (m)

I open up IDLE and then open file progA.py. I run the program, and when prompted for input I enter "b" + <Enter> and then "c" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progA.py =
progA is running b
b
progA is running c
c
progA is running 

Next, I go back to Windows Start and open up IDLE again, this time opening file progB.py. I run the program, and when prompted for input I enter "x" + <Enter> and then "y" + <Enter>

I am looking at this window:

Python 3.6.3 (v3.6.3:2c5fed8, Oct  3 2017, 17:26:49) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
= RESTART: C:\Users\Mike\AppData\Local\Programs\Python\Python36-32\progB.py =
progB is running x
x
progB is running y
y
progB is running 

Now two IDLE Python 3.6.3 Shell programs are running at the same time, one shell running progA while the other one is running progB.

What is the difference between fastcgi and fpm?

What Anthony says is absolutely correct, but I'd like to add that your experience will likely show a lot better performance and efficiency (due not to fpm-vs-fcgi but more to the implementation of your httpd).

For example, I had a quad-core machine running lighttpd + fcgi humming along nicely. I upgraded to a 16-core machine to cope with growth, and two things exploded: RAM usage, and segfaults. I found myself restarting lighttpd every 30 minutes to keep the website up.

I switched to php-fpm and nginx, and RAM usage dropped from >20GB to 2GB. Segfaults disappeared as well. After doing some research, I learned that lighttpd and fcgi don't get along well on multi-core machines under load, and also have memory leak issues in certain instances.

Is this due to php-fpm being better than fcgi? Not entirely, but how you hook into php-fpm seems to be a whole heckuva lot more efficient than how you serve via fcgi.

How to set enum to null

If this is C#, it won't work: enums are value types, and can't be null.

The normal options are to add a None member:

public enum Color
{
  None,
  Red,
  Green,
  Yellow
}

Color color = Color.None;

...or to use Nullable:

Color? color = null;

IE6/IE7 css border on select element

Using ONLY css is impossbile. In fact, all form elements are impossible to customize to look in the same way on all browsers only with css. You can try niceforms though ;)

What is a StackOverflowError?

Like you say, you need to show some code. :-)

A stack overflow error usually happens when your function calls nest too deeply. See the Stack Overflow Code Golf thread for some examples of how this happens (though in the case of that question, the answers intentionally cause stack overflow).

Powershell 2 copy-item which creates a folder if doesn't exist

  $filelist | % {
    $file = $_
    mkdir -force (Split-Path $dest) | Out-Null
    cp $file $dest
  } 

How do I concatenate two arrays in C#?

The most efficient structure in terms of RAM (and CPU) to hold the combined array would be a special class that implements IEnumerable (or if you wish even derives from Array) and links internally to the original arrays to read the values. AFAIK Concat does just that.

In your sample code you could omit the .ToArray() though, which would make it more efficient.

How to manually trigger click event in ReactJS?

Got the following to work May 2018 with ES6 React Docs as a reference: https://reactjs.org/docs/refs-and-the-dom.html

import React, { Component } from "react";
class AddImage extends Component {
  constructor(props) {
    super(props);
    this.fileUpload = React.createRef();
    this.showFileUpload = this.showFileUpload.bind(this);
  }
  showFileUpload() {
    this.fileUpload.current.click();
  }
  render() {
    return (
      <div className="AddImage">
        <input
          type="file"
          id="my_file"
          style={{ display: "none" }}
          ref={this.fileUpload}
        />
        <input
          type="image"
          src="http://www.graphicssimplified.com/wp-content/uploads/2015/04/upload-cloud.png"
          width="30px"
          onClick={this.showFileUpload}
        />
      </div>
    );
  }
}
export default AddImage;

Center Contents of Bootstrap row container

With Bootstrap 4, there is a css class specifically for this. The below will center row content:

<div class="row justify-content-center">
  ...inner divs and content...
</div>

See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.

SVG drop shadow using css3

I'm not aware of a CSS-only solution.

As you mentioned, filters are the canonical approach to creating drop shadow effects in SVG. The SVG specification includes an example of this.

How to scroll to the bottom of a UITableView on the iPhone before the view appears

For Swift:

if tableView.contentSize.height > tableView.frame.size.height {
    let offset = CGPoint(x: 0, y: tableView.contentSize.height - tableView.frame.size.height)
    tableView.setContentOffset(offset, animated: false)
}

Get protocol, domain, and port from URL

Simple answer that works for all browsers:

let origin;

if (!window.location.origin) {
  origin = window.location.protocol + "//" + window.location.hostname + 
     (window.location.port ? ':' + window.location.port: '');
}

origin = window.location.origin;

Python's most efficient way to choose longest string in list?

def longestWord(some_list): 
    count = 0    #You set the count to 0
    for i in some_list: # Go through the whole list
        if len(i) > count: #Checking for the longest word(string)
            count = len(i)
            word = i
    return ("the longest string is " + word)

or much easier:

max(some_list , key = len)

How to change a table name using an SQL query?

In Postgress SQL:

Alter table student rename to student_details;

How to add an image to the "drawable" folder in Android Studio?

For Android Studio 3.4+:

You can use the new Resource Manager tab Click on the + sign and select Import Drawables.

From here, you can select multiple folders/files and it will handle everything for you.

Resource Manager

The result will look something like this:

Resource Manager Picker

Click the import button and the images will be automatically imported to the correct folder.

Sum function in VBA

Place the function value into the cell

Application.Sum often does not work well in my experience (or at least the VBA developer environment does not like it for whatever reason).

The function that works best for me is Excel.WorksheetFunction.Sum()

Example:

Dim Report As Worksheet 'Set up your new worksheet variable.
Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

Report.Cells(11, 1).Value = Excel.WorksheetFunction.Sum(Report.Range("A1:A10")) 'Add the function result.

Place the function directly into the cell

The other method which you were looking for I think is to place the function directly into the cell. This can be done by inputting the function string into the cell value. Here is an example that provides the same result as above, except the cell value is given the function and not the result of the function:

    Dim Report As Worksheet 'Set up your new worksheet variable.
    Set Report = Excel.ActiveSheet 'Assign the active sheet to the variable.

    Report.Cells(11, 1).Value = "=Sum(A1:A10)" 'Add the function.

Python Database connection Close

You might try turning off pooling, which is enabled by default. See this discussion for more information.

import pyodbc
pyodbc.pooling = False
conn = pyodbc.connect('DRIVER=MySQL ODBC 5.1 driver;SERVER=localhost;DATABASE=spt;UID=who;PWD=testest') 

csr = conn.cursor()  
csr.close()
del csr

How to convert number of minutes to hh:mm format in TSQL?

declare function dbo.minutes2hours (
    @minutes int
)
RETURNS varchar(10)
as
begin
    return format(dateadd(minute,@minutes,'00:00:00'), N'HH\:mm','FR-fr')
end

Iterating a JavaScript object's properties using jQuery

$.each( { name: "John", lang: "JS" }, function(i, n){
    alert( "Name: " + i + ", Value: " + n );
});

each

SQL LIKE condition to check for integer?

If you want to search as string, you can cast to text like this:

SELECT * FROM books WHERE price::TEXT LIKE '123%'

The remote host closed the connection. The error code is 0x800704CD

I was getting this on an asp.net 2.0 iis7 Windows2008 site. Same code on iis6 worked fine. It was causing an issue for me because it was messing up the login process. User would login and get a 302 to default.asxp, which would get through page_load, but not as far as pre-render before iis7 would send a 302 back to login.aspx without the auth cookie. I started playing with app pool settings, and for some reason 'enable 32 bit applications' seems to have fixed it. No idea why, since this site isn't doing anything special that should require any 32 bit drivers. We have some sites that still use Access that require 32bit, but not our straight SQL sites like this one.

How to beautifully update a JPA entity in Spring Data?

If you need to work with DTOs rather than entities directly then you should retrieve the existing Customer instance and map the updated fields from the DTO to that.

Customer entity = //load from DB
//map fields from DTO to entity

Visual Studio 2010 - recommended extensions

AtomineerUtils Pro (not free, $9.99 USD) is, in my opinion, better than Ghost Doc. But, just like Ghost Doc or any automatic documentation generator, the generated documentation is meant to be edited to be of any real value.

how to fetch data from database in Hibernate

Query query = session.createQuery("from Employee");

Note: from Employee. here Employee is not your table name it's POJO name.

How to stop console from closing on exit?

You could open a command prompt, CD to the Debug or Release folder, and type the name of your exe. When I suggest this to people they think it is a lot of work, but here are the bare minimum clicks and keystrokes for this:

  • in Visual Studio, right click your project in Solution Explorer or the tab with the file name if you have a file in the solution open, and choose Open Containing Folder or Open in Windows Explorer
  • in the resulting Windows Explorer window, double-click your way to the folder with the exe
  • Shift-right-click in the background of the explorer window and choose Open Commmand Window here
  • type the first letter of your executable and press tab until the full name appears
  • press enter

I think that's 14 keystrokes and clicks (counting shift-right-click as two for example) which really isn't much. Once you have the command prompt, of course, running it again is just up-arrow, enter.

How do I execute a bash script in Terminal?

Firstly you have to make it executable using: chmod +x name_of_your_file_script.

After you made it executable, you can run it using ./same_name_of_your_file_script

Remove object from a list of objects in python

If you want to remove multiple object from a list. There are various ways to delete an object from a list

Try this code. a is list with all object, b is list object you want to remove.

example :

a = [1,2,3,4,5,6]
b = [2,3]

for i in b:
   if i in a:
      a.remove(i)

print(a)

the output is [1,4,5,6] I hope, it will work for you

git push rejected: error: failed to push some refs

Just do

git pull origin [branch]

and then you should be able to push.

If you have commits on your own and didn't push it the branch yet, try

git pull --rebase origin [branch]

and then you should be able to push.

Read more about handling branches with Git.

visual c++: #include files from other projects in the same solution

Since both projects are under the same solution, there's a simpler way for the include files and linker as described in https://docs.microsoft.com/en-us/cpp/build/adding-references-in-visual-cpp-projects?view=vs-2019 :

  1. The include can be written in a relative path (E.g. #include "../libProject/libHeader.h").
  2. For the linker, right click on "References", Click on Add Reference, and choose the other project.

change the date format in laravel view page

You can use Carbon::createFromTimestamp

BLADE

{{ \Carbon\Carbon::createFromTimestamp(strtotime($user->from_date))->format('d-m-Y')}}

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

TypeScript solution:

function pick<T extends object, U extends keyof T>(
  obj: T,
  paths: Array<U>
): Pick<T, U> {
  const ret = Object.create(null);
  for (const k of paths) {
    ret[k] = obj[k];
  }
  return ret;
}

The typing information even allows for auto-completion:

Credit to DefinitelyTyped for U extends keyof T trick!

TypeScript Playground

adding multiple entries to a HashMap at once in one statement

You could add this utility function to a utility class:

public static <K, V> Map<K, V> mapOf(Object... keyValues) {
    Map<K, V> map = new HashMap<>();

    for (int index = 0; index < keyValues.length / 2; index++) {
        map.put((K)keyValues[index * 2], (V)keyValues[index * 2 + 1]);
    }

    return map;
}

Map<Integer, String> map1 = YourClass.mapOf(1, "value1", 2, "value2");
Map<String, String> map2 = YourClass.mapOf("key1", "value1", "key2", "value2");

Note: in Java 9 you can use Map.of

how to make label visible/invisible?

Change visible="false" to style="visibility:hidden" on your tags..


or better use a class to show/hide the labels..

.hidden{
   visibility:hidden;
}

then on your labels add class="hidden"

and with your script remove the class

document.getElementById("endTimeLabel").className = 'hidden'; // to hide

and

document.getElementById("endTimeLabel").className = ''; // to show

jQuery selector to get form by name

$('form[name="frmSave"]') is correct. You mentioned you thought this would get all children with the name frmsave inside the form; this would only happen if there was a space or other combinator between the form and the selector, eg: $('form [name="frmSave"]');

$('form[name="frmSave"]') literally means find all forms with the name frmSave, because there is no combinator involved.

What's the name for hyphen-separated case?

My ECMAScript proposal for String.prototype.toKebabCase.

String.prototype.toKebabCase = function () {
  return this.valueOf().replace(/-/g, ' ').split('')
    .reduce((str, char) => char.toUpperCase() === char ?
      `${str} ${char}` :
      `${str}${char}`, ''
    ).replace(/ * /g, ' ').trim().replace(/ /g, '-').toLowerCase();
}

INSERT statement conflicted with the FOREIGN KEY constraint - SQL Server

In your table dbo.Sup_Item_Cat, it has a foreign key reference to another table. The way a FK works is it cannot have a value in that column that is not also in the primary key column of the referenced table.

If you have SQL Server Management Studio, open it up and sp_help 'dbo.Sup_Item_Cat'. See which column that FK is on, and which column of which table it references. You're inserting some bad data.

Let me know if you need anything explained better!

Unit testing with mockito for constructors

I believe, it is not possible to mock constructors using mockito. Instead, I suggest following approach

Class First {

   private Second second;

   public First(int num, String str) {
     if(second== null)
     {
       //when junit runs, you get the mocked object(not null), hence don't 
       //initialize            
       second = new Second(str);
     }
     this.num = num;
   }

   ... // some other methods
}

And, for test:

class TestFirst{
    @InjectMock
    First first;//inject mock the real testable class
    @Mock
    Second second

    testMethod(){

        //now you can play around with any method of the Second class using its 
        //mocked object(second),like:
        when(second.getSomething(String.class)).thenReturn(null);
    }
}

How can I install pip on Windows?

The following works for Python 2.7. Save this script and launch it:

https://raw.github.com/pypa/pip/master/contrib/get-pip.py

Pip is installed, then add the path to your environment :

C:\Python27\Scripts

Finally

pip install virtualenv

Also you need Microsoft Visual C++ 2008 Express to get the good compiler and avoid these kind of messages when installing packages:

error: Unable to find vcvarsall.bat

If you have a 64-bit version of Windows 7, you may read 64-bit Python installation issues on 64-bit Windows 7 to successfully install the Python executable package (issue with registry entries).

Does C# have a String Tokenizer like Java's?

For complex splitting you could use a regex creating a match collection.

How I can check whether a page is loaded completely or not in web driver?

You can set a JavaScript variable in your WepPage that gets set once it's been loaded. You could put it anywhere, but if you're using jQuery, $(document).onReady isn't a bad place to start. If not, then you can put it in a <script> tag at the bottom of the page.

The advantage of this method as opposed to checking for element visibility is that you know the exact state of the page after the wait statement executes.

MyWebPage.html

... All my page content ...
<script> window.TestReady = true; </script></body></html>

And in your test (C# example):

// The timespan determines how long to wait for any 'condition' to return a value
// If it is exceeded an exception is thrown.
WebDriverWait wait = new WebDriverWait(driver, TimeSpan.FromSeconds(5.0));

// Set the 'condition' as an anonymous function returning a boolean
wait.Until<Boolean>(delegate(IWebDriver d)
{
    // Check if our global variable is initialized by running a little JS
    return (Boolean)((IJavaScriptExecutor)d).ExecuteScript("return typeof(window.TestReady) !== 'undefined' && window.TestReady === true");
});

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

How to use '-prune' option of 'find' in sh?

Prune is a do not recurse at any directory switch.

From the man page

If -depth is not given, true; if the file is a directory, do not descend into it. If -depth is given, false; no effect.

Basically it will not desend into any sub directories.

Take this example:

You have the following directories

  • /home/test2
  • /home/test2/test2

If you run find -name test2:

It will return both directories

If you run find -name test2 -prune:

It will return only /home/test2 as it will not descend into /home/test2 to find /home/test2/test2

Pip "Could not find a that satisfies the requirement"

pygame is not distributed via pip. See this link which provides windows binaries ready for installation.

  1. Install python
  2. Make sure you have python on your PATH
  3. Download the appropriate wheel from this link
  4. Install pip using this tutorial
  5. Finally, use these commands to install pygame wheel with pip

    • Python 2 (usually called pip)

      • pip install file.whl
    • Python 3 (usually called pip3)

      • pip3 install file.whl

Another tutorial for installing pygame for windows can be found here. Although the instructions are for 64bit windows, it can still be applied to 32bit

Is there any quick way to get the last two characters in a string?

The existing answers will fail if the string is empty or only has one character. Options:

String substring = str.length() > 2 ? str.substring(str.length() - 2) : str;

or

String substring = str.substring(Math.max(str.length() - 2, 0));

That's assuming that str is non-null, and that if there are fewer than 2 characters, you just want the original string.

Refresh Page C# ASP.NET

Depending on what exactly you require, a Server.Transfer might be a resource-cheaper alternative to Response.Redirect. More information is in Server.Transfer Vs. Response.Redirect.

RandomForestClassfier.fit(): ValueError: could not convert string to float

You may not pass str to fit this kind of classifier.

For example, if you have a feature column named 'grade' which has 3 different grades:

A,B and C.

you have to transfer those str "A","B","C" to matrix by encoder like the following:

A = [1,0,0]

B = [0,1,0]

C = [0,0,1]

because the str does not have numerical meaning for the classifier.

In scikit-learn, OneHotEncoder and LabelEncoder are available in inpreprocessing module. However OneHotEncoder does not support to fit_transform() of string. "ValueError: could not convert string to float" may happen during transform.

You may use LabelEncoder to transfer from str to continuous numerical values. Then you are able to transfer by OneHotEncoder as you wish.

In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object. The following code works for me and I hope this will help you.

 from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    for column_name in train_data.columns:
        if train_data[column_name].dtype == object:
            train_data[column_name] = le.fit_transform(train_data[column_name])
        else:
            pass

How to send a stacktrace to log4j?

Just because it happened to me and can be useful. If you do this

try {
   ...
} catch (Exception e) {
    log.error( "failed! {}", e );
}

you will get the header of the exception and not the whole stacktrace. Because the logger will think that you are passing a String. Do it without {} as skaffman said

Iterate through a HashMap

Iterate through the entrySet() like so:

public static void printMap(Map mp) {
    Iterator it = mp.entrySet().iterator();
    while (it.hasNext()) {
        Map.Entry pair = (Map.Entry)it.next();
        System.out.println(pair.getKey() + " = " + pair.getValue());
        it.remove(); // avoids a ConcurrentModificationException
    }
}

Read more about Map.

Why does Java's hashCode() in String use 31 as a multiplier?

From JDK-4045622, where Joshua Bloch describes the reasons why that particular (new) String.hashCode() implementation was chosen

The table below summarizes the performance of the various hash functions described above, for three data sets:

1) All of the words and phrases with entries in Merriam-Webster's 2nd Int'l Unabridged Dictionary (311,141 strings, avg length 10 chars).

2) All of the strings in /bin/, /usr/bin/, /usr/lib/, /usr/ucb/ and /usr/openwin/bin/* (66,304 strings, avg length 21 characters).

3) A list of URLs gathered by a web-crawler that ran for several hours last night (28,372 strings, avg length 49 characters).

The performance metric shown in the table is the "average chain size" over all elements in the hash table (i.e., the expected value of the number of key compares to look up an element).

                          Webster's   Code Strings    URLs
                          ---------   ------------    ----
Current Java Fn.          1.2509      1.2738          13.2560
P(37)    [Java]           1.2508      1.2481          1.2454
P(65599) [Aho et al]      1.2490      1.2510          1.2450
P(31)    [K+R]            1.2500      1.2488          1.2425
P(33)    [Torek]          1.2500      1.2500          1.2453
Vo's Fn                   1.2487      1.2471          1.2462
WAIS Fn                   1.2497      1.2519          1.2452
Weinberger's Fn(MatPak)   6.5169      7.2142          30.6864
Weinberger's Fn(24)       1.3222      1.2791          1.9732
Weinberger's Fn(28)       1.2530      1.2506          1.2439

Looking at this table, it's clear that all of the functions except for the current Java function and the two broken versions of Weinberger's function offer excellent, nearly indistinguishable performance. I strongly conjecture that this performance is essentially the "theoretical ideal", which is what you'd get if you used a true random number generator in place of a hash function.

I'd rule out the WAIS function as its specification contains pages of random numbers, and its performance is no better than any of the far simpler functions. Any of the remaining six functions seem like excellent choices, but we have to pick one. I suppose I'd rule out Vo's variant and Weinberger's function because of their added complexity, albeit minor. Of the remaining four, I'd probably select P(31), as it's the cheapest to calculate on a RISC machine (because 31 is the difference of two powers of two). P(33) is similarly cheap to calculate, but it's performance is marginally worse, and 33 is composite, which makes me a bit nervous.

Josh

How to sort findAll Doctrine's method?

You need to use a criteria, for example:

<?php

namespace Bundle\Controller;

use Symfony\Bundle\FrameworkBundle\Controller\Controller;
use Symfony\Component\HttpFoundation\Request;
use Doctrine\Common\Collections\Criteria;

/**
* Thing controller
*/
class ThingController extends Controller
{
    public function thingsAction(Request $request, $id)
    {
        $ids=explode(',',$id);
        $criteria = new Criteria(null, <<DQL ordering expression>>, null, null );

        $rep    = $this->getDoctrine()->getManager()->getRepository('Bundle:Thing');
        $things = $rep->matching($criteria);
        return $this->render('Bundle:Thing:things.html.twig', [
            'entities' => $things,
        ]);
    }
}

How to specify table's height such that a vertical scroll bar appears?

You need to wrap the table inside another element and set the height of that element. Example with inline css:

<div style="height: 500px; overflow: auto;">
 <table>
 </table>
</div>

Convert Float to Int in Swift

Use a function style conversion (found in section labeled "Integer and Floating-Point Conversion" from "The Swift Programming Language."[iTunes link])

  1> Int(3.4)
$R1: Int = 3

PHP sessions default timeout

Yes, that's usually happens after 1440s (24 minutes)

Skip first line(field) in loop using CSV file?

csvreader.next() Return the next row of the reader’s iterable object as a list, parsed according to the current dialect.

How do I check for equality using Spark Dataframe without SQL Query?

To get the negation, do this ...

df.filter(not( ..expression.. ))

eg

df.filter(not($"state" === "TX"))

Resolve build errors due to circular dependency amongst classes

I've written a post about this once: Resolving circular dependencies in c++

The basic technique is to decouple the classes using interfaces. So in your case:

//Printer.h
class Printer {
public:
    virtual Print() = 0;
}

//A.h
#include "Printer.h"
class A: public Printer
{
    int _val;
    Printer *_b;
public:

    A(int val)
        :_val(val)
    {
    }

    void SetB(Printer *b)
    {
        _b = b;
        _b->Print();
    }

    void Print()
    {
        cout<<"Type:A val="<<_val<<endl;
    }
};

//B.h
#include "Printer.h"
class B: public Printer
{
    double _val;
    Printer* _a;
public:

    B(double val)
        :_val(val)
    {
    }

    void SetA(Printer *a)
    {
        _a = a;
        _a->Print();
    }

    void Print()
    {
        cout<<"Type:B val="<<_val<<endl;
    }
};

//main.cpp
#include <iostream>
#include "A.h"
#include "B.h"

int main(int argc, char* argv[])
{
    A a(10);
    B b(3.14);
    a.Print();
    a.SetB(&b);
    b.Print();
    b.SetA(&a);
    return 0;
}

MultipartException: Current request is not a multipart request

i was facing the same issue with misspelled enctype="multipart/form-data", i was fix this exception by doing correct spelling . Current request is not a multipart request client side error so please check your form.

What exactly is OAuth (Open Authorization)?

Oauth is definitely gaining momentum and becoming popular among enterprise APIs as well. In the app and data driven world, Enterprises are exposing APIs more and more to the outer world in line with Google, Facebook, twitter. With this development a 3 way triangle of authentication gets formed

1) API provider- Any enterprise which exposes their assets by API, say Amazon,Target etc 2) Developer - The one who build mobile/other apps over this APIs 3) The end user- The end user of the service provided by the - say registered/guest users of Amazon

Now this develops a situation related to security - (I am listing few of these complexities) 1) You as an end user wants to allow the developer to access APIs on behalf of you. 2) The API provider has to authenticate the developer and the end user 3) The end user should be able to grant and revoke the permissions for the consent they have given 4) The developer can have varying level of trust with the API provider, in which the level of permissions given to her is different

The Oauth is an authorization framework which tries to solve the above mentioned problem in a standard way. With the prominence of APIs and Apps this problem will become more and more relevant and any standard which tries to solve it - be it ouath or any other - will be something to care about as an API provider/developer and even end user!

Error:(9, 5) error: resource android:attr/dialogCornerRadius not found

If you are migrated for AndroidX and getting this error, you need to set the compile SDK to Android 9.0 (API level 28) or higher

Tomcat Servlet: Error 404 - The requested resource is not available

Writing Java servlets is easy if you use Java EE 7

@WebServlet("/hello-world")
public class HelloWorld extends HttpServlet {
  @Override
  public void doGet(HttpServletRequest request, 
                  HttpServletResponse response) {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   out.println("Hello World");
   out.flush();
  }
}

Since servlet 3.0

The good news is the deployment descriptor is no longer required!

Read the tutorial for Java Servlets.

html table span entire width?

<table border="1"; width=100%>

works for me.

Adding items in a Listbox with multiple columns

There is one more way to achieve it:-

Private Sub UserForm_Initialize()
Dim list As Object
Set list = UserForm1.Controls.Add("Forms.ListBox.1", "hello", True)
With list
    .Top = 30
    .Left = 30
    .Width = 200
    .Height = 340
    .ColumnHeads = True
    .ColumnCount = 2
    .ColumnWidths = "100;100"
    .MultiSelect = fmMultiSelectExtended
    .RowSource = "Sheet1!C4:D25"
End With End Sub

Here, I am using the range C4:D25 as source of data for the columns. It will result in both the columns populated with values.

The properties are self explanatory. You can explore other options by drawing ListBox in UserForm and using "Properties Window (F4)" to play with the option values.

Gradle build without tests

gradle build -x test --parallel

If your machine has multiple cores. However, it is not recommended to use parallel clean.

Proper use of the IDisposable interface

Apart from its primary use as a way to control the lifetime of system resources (completely covered by the awesome answer of Ian, kudos!), the IDisposable/using combo can also be used to scope the state change of (critical) global resources: the console, the threads, the process, any global object like an application instance.

I've written an article about this pattern: http://pragmateek.com/c-scope-your-global-state-changes-with-idisposable-and-the-using-statement/

It illustrates how you can protect some often used global state in a reusable and readable manner: console colors, current thread culture, Excel application object properties...

Deserialize from string instead TextReader

static T DeserializeXml<T>(string sourceXML) where T : class
{
    var serializer = new XmlSerializer(typeof(T));
    T result = null;

    using (TextReader reader = new StringReader(sourceXML))
    {
        result = (T) serializer.Deserialize(reader);
    }

    return result;
}

How to get a parent element to appear above child

Since your divs are position:absolute, they're not really nested as far as position is concerned. On your jsbin page I switched the order of the divs in the HTML to:

<div class="child"><div class="parent"></div></div>

and the red box covered the blue box, which I think is what you're looking for.

Spring RestTemplate - how to enable full debugging/logging of requests/responses?

Refer the Q/A for logging the request and response for the rest template by enabling the multiple reads on the HttpInputStream

Why my custom ClientHttpRequestInterceptor with empty response

Getting value from JQUERY datepicker

To position the datepicker next to the input field you could use following code.

$('#datepicker').datepicker({
    beforeShow: function(input, inst)
    {
        inst.dpDiv.css({marginLeft: input.offsetWidth + 'px'});
    }
});

Set attribute without value

Not sure if this is really beneficial or why I prefer this style but what I do (in vanilla js) is:

document.querySelector('#selector').toggleAttribute('data-something');

This will add the attribute in all lowercase without a value or remove it if it already exists on the element.

https://developer.mozilla.org/en-US/docs/Web/API/Element/toggleAttribute

What MIME type should I use for CSV?

You should use "text/csv" according to RFC 4180.

printf() formatting for hex

The "0x" counts towards the eight character count. You need "%#010x".

Note that # does not append the 0x to 0 - the result will be 0000000000 - so you probably actually should just use "0x%08x" anyway.

"Unable to get the VLookup property of the WorksheetFunction Class" error

I was having the same problem. It seems that passing Me.ComboBox1.Value as an argument for the Vlookup function is causing the issue. What I did was assign this value to a double and then put it into the Vlookup function.

Dim x As Double
x = Me.ComboBox1.Value
Me.TextBox1.Value = Application.WorksheetFunction.VLookup(x, Worksheets("Sheet3").Range("Names"), 2, False) 

Or, for a shorter method, you can just convert the type within the Vlookup function using Cdbl(<Value>).

So it would end up being

Me.TextBox1.Value = Application.WorksheetFunction.VLookup(Cdbl(Me.ComboBox1.Value), Worksheets("Sheet3").Range("Names"), 2, False) 

Strange as it may sound, it works for me.

Hope this helps.

How to generate a QR Code for an Android application?

Have you looked into ZXING? I've been using it successfully to create barcodes. You can see a full working example in the bitcoin application src

// this is a small sample use of the QRCodeEncoder class from zxing
try {
    // generate a 150x150 QR code
    Bitmap bm = encodeAsBitmap(barcode_content, BarcodeFormat.QR_CODE, 150, 150);

    if(bm != null) {
        image_view.setImageBitmap(bm);
    }
} catch (WriterException e) { //eek }