Programs & Examples On #Circuit breaker

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

CASCADE DELETE just once

No. To do it just once you would simply write the delete statement for the table you want to cascade.

DELETE FROM some_child_table WHERE some_fk_field IN (SELECT some_id FROM some_Table);
DELETE FROM some_table;

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

I'm using EasyPHP in making my Thesis about Content Management System. So far, this tool is very good and easy to use.

Dropdownlist width in IE

you could just try the following...

  styleClass="someStyleWidth"
  onmousedown="javascript:if(navigator.appName=='Microsoft Internet Explorer'){this.style.position='absolute';this.style.width='auto'}" 
  onblur="this.style.position='';this.style.width=''"

I tried and it works for me. Nothing else is required.

C free(): invalid pointer

From where did you get the idea that you need to free(token) and free(tk)? You don't. strsep() doesn't allocate memory, it only returns pointers inside the original string. Of course, those are not pointers allocated by malloc() (or similar), so free()ing them is undefined behavior. You only need to free(s) when you are done with the entire string.

Also note that you don't need dynamic memory allocation at all in your example. You can avoid strdup() and free() altogether by simply writing char *s = p;.

What is a NullPointerException, and how do I fix it?

A null pointer exception is thrown when an application attempts to use null in a case where an object is required. These include:

  1. Calling the instance method of a null object.
  2. Accessing or modifying the field of a null object.
  3. Taking the length of null as if it were an array.
  4. Accessing or modifying the slots of null as if it were an array.
  5. Throwing null as if it were a Throwable value.

Applications should throw instances of this class to indicate other illegal uses of the null object.

Reference: http://docs.oracle.com/javase/8/docs/api/java/lang/NullPointerException.html

Could not load type 'XXX.Global'

There are a few things you can try with this, seems to happen alot and the solution varies for everyone it seems.

  • If you are still using the IIS virtual directory make sure its pointed to the correct directory and also check the ASP.NET version it is set to, make sure it is set to ASP.NET 2.0.

  • Clear out your bin/debug/obj all of them. Do a Clean solution and then a Build Solution.

  • Check your project file in a text editor and make sure where its looking for the global file is correct, sometimes it doesnt change the directory.

  • Remove the global from the solution and add it back after saving and closing. make sure all the script tags in the ASPX file point to the correct one after.

  • You can try running the Convert to Web Application tool, that redoes all of the code and project files.

  • IIS Express is using the wrong root directory (see answer in VS 2012 launching app based on wrong path)

Make sure you close VS after you try them.

Those are some things I know to try. Hope one of them works for you.

How to install Selenium WebDriver on Mac OS

First up you need to download Selenium jar files from http://www.seleniumhq.org/download/. Then you'd need an IDE, something like IntelliJ or Eclipse. Then you'll have to map your jar files to those IDEs. Then depending on which language/framework you choose, you'll have to download the relevant library files, for example, if you're using JUnit you'll have to download Junit 4.11 jar file. Finally don't forget to download the drivers for Chrome and Safari (firefox driver comes standard with selenium). Once done, you can start coding and testing your code with the browser of your choice.

Example of a strong and weak entity types

A weak entity is the entity which can't be fully identified by its own attributes and takes the foreign key as an attribute (generally it takes the primary key of the entity it is related to) in conjunction.

Examples

The existence of rooms is entirely dependent on the existence of a hotel. So room can be seen as the weak entity of the hotel.
Another example is the
bank account of a particular bank has no existence if the bank doesn't exist anymore.

Unknown column in 'field list' error on MySQL Update query

Enclose any string to be passed to the mysql server inside single quotes; e.g.:

$name = "my name"
$query = " INSERT INTO mytable VALUES ( 1 , '$name') "

Note that although the query is enclosed between double quotes, you must enclose any string in single quotes.

How do you post to the wall on a facebook page (not profile)

You can make api calls by choosing the HTTP method and setting optional parameters:

$facebook->api('/me/feed/', 'post', array(
    'message' => 'I want to display this message on my wall'
));

Submit Post to Facebook Wall :

Include the fbConfig.php file to connect Facebook API and get the access token.

Post message, name, link, description, and the picture will be submitted to Facebook wall. Post submission status will be shown.

If FB access token ($accessToken) is not available, the Facebook Login URL will be generated and the user would be redirected to the FB login page.

Post to facebook wall php sdk

<?php
//Include FB config file
require_once 'fbConfig.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;

        // OAuth 2.0 client handler helps to manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();

        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

    //FB post content
    $message = 'Test message from CodexWorld.com website';
    $title = 'Post From Website';
    $link = 'http://www.codexworld.com/';
    $description = 'CodexWorld is a programming blog.';
    $picture = 'http://www.codexworld.com/wp-content/uploads/2015/12/www-codexworld-com-programming-blog.png';

    $attachment = array(
        'message' => $message,
        'name' => $title,
        'link' => $link,
        'description' => $description,
        'picture'=>$picture,
    );

    try{
        //Post to Facebook
        $fb->post('/me/feed', $attachment, $accessToken);

        //Display post submission status
        echo 'The post was submitted successfully to Facebook timeline.';
    }catch(FacebookResponseException $e){
        echo 'Graph returned an error: ' . $e->getMessage();
        exit;
    }catch(FacebookSDKException $e){
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }
}else{
    //Get FB login URL
    $fbLoginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);

    //Redirect to FB login
    header("Location:".$fbLoginURL);
}

Refrences:

https://github.com/facebookarchive/facebook-php-sdk

https://developers.facebook.com/docs/pages/publishing/

https://developers.facebook.com/docs/php/gettingstarted

http://www.pontikis.net/blog/auto_post_on_facebook_with_php

https://www.codexworld.com/post-to-facebook-wall-from-website-php-sdk/

Tab key == 4 spaces and auto-indent after curly braces in Vim

The best way to get filetype-specific indentation is to use filetype plugin indent on in your vimrc. Then you can specify things like set sw=4 sts=4 et in .vim/ftplugin/c.vim, for example, without having to make those global for all files being edited and other non-C type syntaxes will get indented correctly, too (even lisps).

How to change Visual Studio 2012,2013 or 2015 License Key?

For those of you using Visual Studio 2017 Professional, the registry key is:

HKCR\Licenses\5C505A59-E312-4B89-9508-E162F8150517

I also recommend you first export the registry key, before you delete it, so you'll have a backup if you accidentally delete the wrong key.

File name without extension name VBA

You could always use Replace() since you're performing this on the workbook's Name, which will almost certainly end with .xlsm by virtue of using VBA.

Using ActiveWorkbook per your example:

Replace(Application.ActiveWorkbook.Name, ".xlsm", "")

Using ThisWorkbook:

Replace(Application.ThisWorkbook.Name, ".xlsm", "")

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

Remove rows not .isin('X')

You can use numpy.logical_not to invert the boolean array returned by isin:

In [63]: s = pd.Series(np.arange(10.0))

In [64]: x = range(4, 8)

In [65]: mask = np.logical_not(s.isin(x))

In [66]: s[mask]
Out[66]: 
0    0
1    1
2    2
3    3
8    8
9    9

As given in the comment by Wes McKinney you can also use

s[~s.isin(x)]

Jquery check if element is visible in viewport

According to the documentation for that plugin, .visible() returns a boolean indicating if the element is visible. So you'd use it like this:

if ($('#element').visible(true)) {
    // The element is visible, do something
} else {
    // The element is NOT visible, do something else
}

Basic Python client socket example

Here is a pretty simple socket program. This is about as simple as sockets get.

for the client program(CPU 1)

import socket

s = socket.socket()
host = '111.111.0.11' # needs to be in quote
port = 1247
s.connect((host, port))
print s.recv(1024)
inpt = raw_input('type anything and click enter... ')
s.send(inpt)
print "the message has been sent"

You have to replace the 111.111.0.11 in line 4 with the IP number found in the second computers network settings.

For the server program(CPU 2)

import socket

s = socket.socket()
host = socket.gethostname()
port = 1247
s.bind((host,port))
s.listen(5)
while True:
    c, addr = s.accept()
    print("Connection accepted from " + repr(addr[1]))

    c.send("Server approved connection\n")
    print repr(addr[1]) + ": " + c.recv(1026)
    c.close()

Run the server program and then the client one.

Convert hours:minutes:seconds into total minutes in excel

Just use the formula

120 = (HOUR(A8)*3600+MINUTE(A8)*60+SECOND(A8))/60

How to dynamically add a style for text-align using jQuery

<!DOCTYPE html>
<html>
  <head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
    <script>
      $( document ).ready(function() {
      $this = $('h1');
         $this.css('color','#3498db');
         $this.css('text-align','center');
         $this.css('border','1px solid #ededed');
      });
    </script>

  </head>
  <body>
      <h1>Title</h1>
 </body>
</html>

How to consume a SOAP web service in Java

I will use CXF also you can think of AXIS 2 .

The best way to do it may be using JAX RS Refer this example

Example:

wsimport -p stockquote http://stockquote.xyz/quote?wsdl

This will generate the Java artifacts and compile them by importing the http://stockquote.xyz/quote?wsdl.

I

Git: cannot checkout branch - error: pathspec '...' did not match any file(s) known to git

I have the same error in my case:

git checkout master
error: pathspec 'master' did not match any file(s) known to git

Since Git's "master" name updated with "main", new project can only use "main".

git checkout main

Using PowerShell credentials without being prompted for a password

The problem with Get-Credential is that it will always prompt for a password. There is a way around this however but it involves storing the password as a secure string on the filesystem.

The following article explains how this works:

Using PSCredentials without a prompt

In summary, you create a file to store your password (as an encrypted string). The following line will prompt for a password then store it in c:\mysecurestring.txt as an encrypted string. You only need to do this once:

read-host -assecurestring | convertfrom-securestring | out-file C:\mysecurestring.txt

Wherever you see a -Credential argument on a PowerShell command then it means you can pass a PSCredential. So in your case:

$username = "domain01\admin01"
$password = Get-Content 'C:\mysecurestring.txt' | ConvertTo-SecureString
$cred = new-object -typename System.Management.Automation.PSCredential `
         -argumentlist $username, $password

$serverNameOrIp = "192.168.1.1"
Restart-Computer -ComputerName $serverNameOrIp `
                 -Authentication default `
                 -Credential $cred
                 <any other parameters relevant to you>

You may need a different -Authentication switch value because I don't know your environment.

How does java do modulus calculations with negative numbers?

Both definitions of modulus of negative numbers are in use - some languages use one definition and some the other.

If you want to get a negative number for negative inputs then you can use this:

int r = x % n;
if (r > 0 && x < 0)
{
    r -= n;
}

Likewise if you were using a language that returns a negative number on a negative input and you would prefer positive:

int r = x % n;
if (r < 0)
{
    r += n;
}

PHP Fatal error: Cannot redeclare class

This function will print a stack telling you where it was called from:

function PrintTrace() {
    $trace = debug_backtrace();
    echo '<pre>';
    $sb = array();
    foreach($trace as $item) {
        if(isset($item['file'])) {
            $sb[] = htmlspecialchars("$item[file]:$item[line]");
        } else {
            $sb[] = htmlspecialchars("$item[class]:$item[function]");
        }
    }
    echo implode("\n",$sb);
    echo '</pre>';
}

Call this function at the top of the file that includes your class.

Sometimes it will only print once, even though your class is being included two or more times. This is because PHP actually parses all the top-level classes in a file before executing any code and throws the fatal error immediately. To remedy this, wrap your class declaration in if(true) { ... }, which will move your class down a level in scope. Then you should get your two traces before PHP fatal errors.

This should help you find where you class is being included from multiple times in a complex project.

ActionController::InvalidAuthenticityToken

I had the same issue but with pages which were page cached. Pages got buffered with a stale authenticity token and all actions using the methods post/put/delete where recognized as forgery attempts. Error (422 Unprocessable Entity) was returned to the user.

The solution for Rails 3:
Add:

 skip_before_filter :verify_authenticity_token  

or as "sagivo" pointed out in Rails 4 add:

 skip_before_action :verify_authenticity_token

On pages which do caching.

As @toobulkeh commented this is not a vulnerability on :index, :show actions, but beware using this on :put, :post actions.

For example:

 caches_page :index, :show  
 skip_before_filter :verify_authenticity_token, :only => [:index, :show]

Reference: http://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection/ClassMethods.html

Note added by barlop- Rails 4.2 deprecated skip_before_filter in favour of skip_before_action https://guides.rubyonrails.org/4_2_release_notes.html "The *_filter family of methods have been removed from the documentation. Their usage is discouraged in favor of the *_action family of methods"

For Rails 6 (as "collimarco" pointed out) you can use skip_forgery_protection and that it is safe to use it for a REST API that doesn't use session data.

setting the id attribute of an input element dynamically in IE: alternative for setAttribute method

Use jquery attr method. It works in all browsers.

var hiddenInput = document.createElement("input");
$(hiddenInput).attr({
    'id':'uniqueIdentifier',
    'type': 'hidden',
    'value': ID,
    'class': 'ListItem'
});

Or you could use folowing code:

var e = $('<input id = "uniqueIdentifier" type="hidden" value="' + ID + '" class="ListItem" />');

What's the difference between MyISAM and InnoDB?

The main differences between InnoDB and MyISAM ("with respect to designing a table or database" you asked about) are support for "referential integrity" and "transactions".

If you need the database to enforce foreign key constraints, or you need the database to support transactions (i.e. changes made by two or more DML operations handled as single unit of work, with all of the changes either applied, or all the changes reverted) then you would choose the InnoDB engine, since these features are absent from the MyISAM engine.

Those are the two biggest differences. Another big difference is concurrency. With MyISAM, a DML statement will obtain an exclusive lock on the table, and while that lock is held, no other session can perform a SELECT or a DML operation on the table.

Those two specific engines you asked about (InnoDB and MyISAM) have different design goals. MySQL also has other storage engines, with their own design goals.

So, in choosing between InnoDB and MyISAM, the first step is in determining if you need the features provided by InnoDB. If not, then MyISAM is up for consideration.

A more detailed discussion of differences is rather impractical (in this forum) absent a more detailed discussion of the problem space... how the application will use the database, how many tables, size of the tables, the transaction load, volumes of select, insert, updates, concurrency requirements, replication features, etc.


The logical design of the database should be centered around data analysis and user requirements; the choice to use a relational database would come later, and even later would the choice of MySQL as a relational database management system, and then the selection of a storage engine for each table.

Change form size at runtime in C#

Something like this works fine for me:

public partial class Form1 : Form
{
    Form mainFormHandler;
...
}

private void Form1_Load(object sender, EventArgs e){
    mainFormHandler = Application.OpenForms[0];
   //or instead use this one:
   //mainFormHandler = Application.OpenForms["Form1"];
}

Then you can change the size as below:

mainFormHandler.Width = 600;
mainFormHandler.Height= 400;

or

mainFormHandler.Size = new Size(600, 400);

Another useful point is that if you want to change the size of mainForm from another Form, you can simply use Property to set the size.

Return HTTP status code 201 in flask

You can read about it here.

return render_template('page.html'), 201

How many spaces will Java String.trim() remove?

From the source code (decompiled) :

  public String trim()
  {
    int i = this.count;
    int j = 0;
    int k = this.offset;
    char[] arrayOfChar = this.value;
    while ((j < i) && (arrayOfChar[(k + j)] <= ' '))
      ++j;
    while ((j < i) && (arrayOfChar[(k + i - 1)] <= ' '))
      --i;
    return (((j > 0) || (i < this.count)) ? substring(j, i) : this);
  }

The two while that you can see mean all the characters whose unicode is below the space character's, at beginning and end, are removed.

Python re.sub replace with matched content

For the replacement portion, Python uses \1 the way sed and vi do, not $1 the way Perl, Java, and Javascript (amongst others) do. Furthermore, because \1 interpolates in regular strings as the character U+0001, you need to use a raw string or \escape it.

Python 3.2 (r32:88445, Jul 27 2011, 13:41:33) 
[GCC 4.0.1 (Apple Inc. build 5465)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> method = 'images/:id/huge'
>>> import re
>>> re.sub(':([a-z]+)', r'<span>\1</span>', method)
'images/<span>id</span>/huge'
>>> 

What is an Intent in Android?

From the paper Deep Dive into Android IPC/Binder Framework atAndroid Builders Summit 2013 link

The intent is understood in some small but effective lines

  1. Android supports a simple form of IPC(inter process communication) via intents
  2. Intent messaging is a framework for asynchronous communication among Android components (activity, service, content providers, broadcast receiver )
  3. Those components may run in the same or across different apps (i.e. processes)
  4. Enables both point-to-point as well as publish subscribe messaging domains
  5. The intent itself represents a message containing the description of the operation to be performed as well as data to be passed to the recipient(s).

From this thread a simple answer of android architect Dianne Hackborn states it as a data container which it actually is.

From android architecture point of view :

Intent is a data container that is used for inter process communication. It is built on top of the Binder from android architecture point of view.

php: Get html source code with cURL

I found a tool in Github that could possibly be a solution to this question. https://incarnate.github.io/curl-to-php/ I hope that will be useful

What are the options for storing hierarchical data in a relational database?

Adjacency Model + Nested Sets Model

I went for it because I could insert new items to the tree easily (you just need a branch's id to insert a new item to it) and also query it quite fast.

+-------------+----------------------+--------+-----+-----+
| category_id | name                 | parent | lft | rgt |
+-------------+----------------------+--------+-----+-----+
|           1 | ELECTRONICS          |   NULL |   1 |  20 |
|           2 | TELEVISIONS          |      1 |   2 |   9 |
|           3 | TUBE                 |      2 |   3 |   4 |
|           4 | LCD                  |      2 |   5 |   6 |
|           5 | PLASMA               |      2 |   7 |   8 |
|           6 | PORTABLE ELECTRONICS |      1 |  10 |  19 |
|           7 | MP3 PLAYERS          |      6 |  11 |  14 |
|           8 | FLASH                |      7 |  12 |  13 |
|           9 | CD PLAYERS           |      6 |  15 |  16 |
|          10 | 2 WAY RADIOS         |      6 |  17 |  18 |
+-------------+----------------------+--------+-----+-----+
  • Every time you need all children of any parent you just query the parent column.
  • If you needed all descendants of any parent you query for items which have their lft between lft and rgt of parent.
  • If you needed all parents of any node up to the root of the tree, you query for items having lft lower than the node's lft and rgt bigger than the node's rgt and sort the by parent.

I needed to make accessing and querying the tree faster than inserts, that's why I chose this

The only problem is to fix the left and right columns when inserting new items. well I created a stored procedure for it and called it every time I inserted a new item which was rare in my case but it is really fast. I got the idea from the Joe Celko's book, and the stored procedure and how I came up with it is explained here in DBA SE https://dba.stackexchange.com/q/89051/41481

How to change facet labels?

I think all other solutions are really helpful to do this, but there is yet another way.

I assume:

  • you have installed the dplyr package, which has the convenient mutate command, and
  • your dataset is named survey.

    survey %>% mutate(Hosp1 = Hospital1, Hosp2 = Hospital2,........)

This command helps you to rename columns, yet all other columns are kept.

Then do the same facet_wrap, you are fine now.

how to iterate through dictionary in a dictionary in django template?

If you pass a variable data (dictionary type) as context to a template, then you code should be:

{% for key, value in data.items %}
    <p>{{ key }} : {{ value }}</p> 
{% endfor %}

When should I use Memcache instead of Memcached?

This is 2013. Forget about the 2009 comments. Likewise, if you are running serious traffic loads, do not even contemplate how to make-do with a windows based memcache. When dealing with a very large scale (500+ front end web servers) and 20+ back end database servers and replicants (mysql & mssql mix), a farm of memcached servers (12 servers in group) supports multiple high volume OLTP applications answering 25K ~ 40K mc->get calls per-second. These calls are those that do NOT have to reach a database.

IMHO, this use of memcached provided SERIOUS $$$,$$$savings on CAPEX for new DB servers & licences as well as on support contracts for large commercial designs.

How do I alter the position of a column in a PostgreSQL database table?

I don't think you can at present: see this article on the Postgresql wiki.

The three workarounds from this article are:

  1. Recreate the table
  2. Add columns and move data
  3. Hide the differences with a view.

What is the { get; set; } syntax in C#?

In the Visual Studio, if you define a property X in a class and you want to use this class only as a type, after building your project you will get a warning that says "Field X is never assigned to, and will always has its default value".

By adding a { get; set; } to X property, you will not get this warning.

In addition in Visual Studio 2013 and upper versions, by adding { get; set; } you are able to see all references to that property.

enter image description here

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

Close a div by clicking outside

 //for closeing the popover when user click outside it will close all popover 
 var hidePopover = function(element) {
        var elementScope = angular.element($(element).siblings('.popover')).scope().$parent;
        elementScope.isOpen = false;
        elementScope.$apply();
        //Remove the popover element from the DOM
        $(element).siblings('.popover').remove();
    };
 $(document).ready(function(){
 $('body').on('click', function (e) {
       $("a").each(function () {
                    //Only do this for all popovers other than the current one that cause this event
           if (!($(this).is(e.target) || $(this).has(e.target).length > 0) 
                && $(this).siblings('.popover').length !== 0 && $(this).siblings('.popover').has(e.target).length === 0)                  
                    {
                         hidePopover(this);
                    }
        });
    });
 });

System.IO.IOException: file used by another process

 System.Drawing.Image FileUploadPhoto = System.Drawing.Image.FromFile(location1);
                                 FileUploadPhoto.Save(location2);
                                 FileUploadPhoto.Dispose();

Ansible: how to get output to display

Every Ansible task when run can save its results into a variable. To do this, you have to specify which variable to save the results into. Do this with the register parameter, independently of the module used.

Once you save the results to a variable you can use it later in any of the subsequent tasks. So for example if you want to get the standard output of a specific task you can write the following:

---
- hosts: localhost
  tasks:
    - shell: ls
      register: shell_result

    - debug:
        var: shell_result.stdout_lines

Here register tells ansible to save the response of the module into the shell_result variable, and then we use the debug module to print the variable out.

An example run would look like the this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
changed: [localhost]

TASK [debug] *******************************************************************
ok: [localhost] => {
    "shell_result.stdout_lines": [
        "play.yml"
    ]
}

Responses can contain multiple fields. stdout_lines is one of the default fields you can expect from a module's response.

Not all fields are available from all modules, for example for a module which doesn't return anything to the standard out you wouldn't expect anything in the stdout or stdout_lines values, however the msg field might be filled in this case. Also there are some modules where you might find something in a non-standard variable, for these you can try to consult the module's documentation for these non-standard return values.

Alternatively you can increase the verbosity level of ansible-playbook. You can choose between different verbosity levels: -v, -vvv and -vvvv. For example when running the playbook with verbosity (-vvv) you get this:

PLAY [localhost] ***************************************************************

TASK [command] *****************************************************************
(...)
changed: [localhost] => {
    "changed": true,
    "cmd": "ls",
    "delta": "0:00:00.007621",
    "end": "2017-02-17 23:04:41.912570",
    "invocation": {
        "module_args": {
            "_raw_params": "ls",
            "_uses_shell": true,
            "chdir": null,
            "creates": null,
            "executable": null,
            "removes": null,
            "warn": true
        },
        "module_name": "command"
    },
    "rc": 0,
    "start": "2017-02-17 23:04:41.904949",
    "stderr": "",
    "stdout": "play.retry\nplay.yml",
    "stdout_lines": [
        "play.retry",
        "play.yml"
    ],
    "warnings": []
}

As you can see this will print out the response of each of the modules, and all of the fields available. You can see that the stdout_lines is available, and its contents are what we expect.

To answer your main question about the jenkins_script module, if you check its documentation, you can see that it returns the output in the output field, so you might want to try the following:

tasks:
  - jenkins_script:
      script: (...)
    register: jenkins_result

  - debug:
      var: jenkins_result.output

How to sort rows of HTML table that are called from MySQL

The easiest way to do this would be to put a link on your column headers, pointing to the same page. In the query string, put a variable so that you know what they clicked on, and then use ORDER BY in your SQL query to perform the ordering.

The HTML would look like this:

<th><a href="mypage.php?sort=type">Type:</a></th>
<th><a href="mypage.php?sort=desc">Description:</a></th>
<th><a href="mypage.php?sort=recorded">Recorded Date:</a></th>
<th><a href="mypage.php?sort=added">Added Date:</a></th>

And in the php code, do something like this:

<?php

$sql = "SELECT * FROM MyTable";

if ($_GET['sort'] == 'type')
{
    $sql .= " ORDER BY type";
}
elseif ($_GET['sort'] == 'desc')
{
    $sql .= " ORDER BY Description";
}
elseif ($_GET['sort'] == 'recorded')
{
    $sql .= " ORDER BY DateRecorded";
}
elseif($_GET['sort'] == 'added')
{
    $sql .= " ORDER BY DateAdded";
}

$>

Notice that you shouldn't take the $_GET value directly and append it to your query. As some user could got to MyPage.php?sort=; DELETE FROM MyTable;

How to change maven logging level to display only warning and errors?

You can achieve this with MAVEN_OPTS, for example
MAVEN_OPTS=-Dorg.slf4j.simpleLogger.defaultLogLevel=warn mvn clean

Rather than putting the system property directly on the command line. (At least for maven 3.3.1.)

Consider using ~/.mavenrc for setting MAVEN_OPTS if you would like logging changed for your login across all maven invocations.

Input mask for numeric and decimal

You can do it using jquery inputmask plugin.

HTML:

<input id="price" type="text">

Javascript:

$('#price').inputmask({
  alias: 'numeric', 
  allowMinus: false,  
  digits: 2, 
  max: 999.99
});

https://codepen.io/vladimir-vovk/pen/BgNLgv

Get a json via Http Request in NodeJS

http sends/receives data as strings... this is just the way things are. You are looking to parse the string as json.

var jsonObject = JSON.parse(data);

How to parse JSON using Node.js?

how to disable DIV element and everything inside

Try this!

$("#test *").attr("disabled", "disabled").off('click');

I don't see you using jquery above, but you have it listed as a tag.

How to access command line arguments of the caller inside a function?

# Save the script arguments
SCRIPT_NAME=$0
ARG_1=$1
ARGS_ALL=$*

function stuff {
  # use script args via the variables you saved
  # or the function args via $
  echo $0 $*
} 


# Call the function with arguments
stuff 1 2 3 4

To find first N prime numbers in python

This is my version

import timeit
import math

__author__ = 'rain'


primes = [2]

def is_prime(n):
    for prime in primes:
        if n % prime == 0:
            return False
    return True


def find_nth_prime(n):
    current_index = 0
    while(len(primes) < n):
        if current_index == 0:
            start_value = 3
            end_value = 2 * 2
        else:
            start_value = primes[current_index - 1] * primes[current_index - 1] + 1
            end_value = primes[current_index] * primes[current_index]
        for i in range(start_value, end_value):
            if is_prime(i):
                primes.append(i)
        current_index += 1
    return primes[n-1]


def solve():
    return find_nth_prime(10001)

print solve()

print timeit.timeit(solve, number=10)

I use a sieve to scan primes, it's quite quick

It's take only 3.8e-06 seconds to get 10001th prime (10 times).

What is the difference between Eclipse for Java (EE) Developers and Eclipse Classic?

If you want to build Java EE applications, it's best to use Eclipse IDE for Java EE. It has editors from HTML to JSP/JSF, Javascript. It's rich for webapps development, and provide plugins and tools to develop Java EE applications easily (all bundled).

Eclipse Classic is basically the full featured Eclipse without the Java EE part.

Unable to connect to SQL Express "Error: 26-Error Locating Server/Instance Specified)

Go to SQL Server Configuration Manager > SQL Server Services > In Right Side window show all the servers which may stop. If you are using "SQLEXPRESS" then , Right click on SQL Server(SQLEXPRESS) and start. After try to connect server... I had same problem but I resolved by these steps.

How can I style the border and title bar of a window in WPF?

I suggest you to start from an existing solution and customize it to fit your needs, that's better than starting from scratch!

I was looking for the same thing and I fall on this open source solution, I hope it will help.

Removing header column from pandas dataframe

I think you cant remove column names, only reset them by range with shape:

print df.shape[1]
2

print range(df.shape[1])
[0, 1]

df.columns = range(df.shape[1])
print df
    0   1
0  23  12
1  21  44
2  98  21

This is same as using to_csv and read_csv:

print df.to_csv(header=None,index=False)
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(header=None,index=False)), header=None)
    0   1
0  23  12
1  21  44
2  98  21

Next solution with skiprows:

print df.to_csv(index=False)
A,B
23,12
21,44
98,21

print pd.read_csv(io.StringIO(u""+df.to_csv(index=False)), header=None, skiprows=1)
    0   1
0  23  12
1  21  44
2  98  21

HTML5 iFrame Seamless Attribute

iO8 has removed support for the iframe seamless attribute.

  • Tested in Safari, HomeScreen, new WKWebView and UIWebView.

Full Details and performance review of other iOS 8 changes:

MySQL Error: #1142 - SELECT command denied to user

In MySQL query browser go to Tools tab>MySQL Administrator > User Administration and then give the privileges to user.

Create boolean column in MySQL with false as default value?

Use ENUM in MySQL for true / false it gives and accepts the true / false values without any extra code.

ALTER TABLE `itemcategory` ADD `aaa` ENUM('false', 'true') NOT NULL DEFAULT 'false'

How to add key,value pair to dictionary?

I am not sure what you mean by "dynamic". If you mean adding items to a dictionary at runtime, it is as easy as dictionary[key] = value.

If you wish to create a dictionary with key,value to start with (at compile time) then use (surprise!)

dictionary[key] = value

Angular no provider for NameService

Shockingly, the syntax has changed yet again in the latest version of Angular :-) From the Angular 6 docs:

Beginning with Angular 6.0, the preferred way to create a singleton services is to specify on the service that it should be provided in the application root. This is done by setting providedIn to root on the service's @Injectable decorator:

src/app/user.service.0.ts

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root',
})
export class UserService {
}

Convert char array to a int number in C

So, the idea is to convert character numbers (in single quotes, e.g. '8') to integer expression. For instance char c = '8'; int i = c - '0' //would yield integer 8; And sum up all the converted numbers by the principle that 908=9*100+0*10+8, which is done in a loop.

char t[5] = {'-', '9', '0', '8', '\0'}; //Should be terminated properly.

int s = 1;
int i = -1;
int res = 0;

if (c[0] == '-') {
  s = -1;
  i = 0;
}

while (c[++i] != '\0') { //iterate until the array end
  res = res*10 + (c[i] - '0'); //generating the integer according to read parsed numbers.
}

res = res*s; //answer: -908

Default settings Raspberry Pi /etc/network/interfaces

Assuming that you have a DHCP server running at your router I would use:

# /etc/network/interfaces
auto lo eth0
iface lo inet loopback

iface eth0 inet dhcp

After changing the file issue (as root):

/etc/init.d/networking restart

comparing two strings in SQL Server

There is no direct string compare function in SQL Server

CASE
  WHEN str1 = str2 THEN 0
  WHEN str1 < str2 THEN -1
  WHEN str1 > str2 THEN 1
  ELSE NULL --one of the strings is NULL so won't compare (added on edit)
END

Notes

  • you can wraps this via a UDF using CREATE FUNCTION etc
  • you may need NULL handling (in my code above, any NULL will report 1)
  • str1 and str2 will be column names or @variables

How to capitalize the first letter of a String in Java?

You may try this

/**
 * capitilizeFirst(null)  -> ""
 * capitilizeFirst("")    -> ""
 * capitilizeFirst("   ") -> ""
 * capitilizeFirst(" df") -> "Df"
 * capitilizeFirst("AS")  -> "As"
 *
 * @param str input string
 * @return String with the first letter capitalized
 */
public String capitilizeFirst(String str)
{
    // assumptions that input parameter is not null is legal, as we use this function in map chain
    Function<String, String> capFirst = (String s) -> {
        String result = ""; // <-- accumulator

        try { result += s.substring(0, 1).toUpperCase(); }
        catch (Throwable e) {}
        try { result += s.substring(1).toLowerCase(); }
        catch (Throwable e) {}

        return result;
    };

    return Optional.ofNullable(str)
            .map(String::trim)
            .map(capFirst)
            .orElse("");
}

How do I ignore a directory with SVN?

"Thank-you" svn for such a hideous, bogus and difficult way to ignore files.

So I wrote a script svn-ignore-all:

#!/bin/sh

# svn-ignore-all

# usage: 
#   1. run svn status to see what is going on at each step 
#   2. add or commit all files that you DO want to have in svn
#   3. remove any random files that you don't want to svn:ignore
#   4. run this script to svn:ignore everything marked '?' in output of `svn status`

svn status |
grep '^?' |
sed 's/^? *//' |
while read f; do
    d=`dirname "$f"`
    b=`basename "$f"`
    ignore=`svn propget svn:ignore "$d"`
    if [ -n "$ignore" ]; then
        ignore="$ignore
"
    fi
    ignore="$ignore$b"
    svn propset svn:ignore "$ignore" "$d"
done

Also, to ignore specific list of files / pathnames, we can use this variant svn-ignore. I guess svn-ignore-all should really be like xargs svn-ignore.

#!/bin/sh

# svn-ignore

# usage:
#   svn-ignore file/to/ignore ...

for f; do
    d=`dirname "$f"`
    b=`basename "$f"`
    ignore=`svn propget svn:ignore "$d"`
    if [ -n "$ignore" ]; then
        ignore="$ignore
"
    fi
    ignore="$ignore$b"
    svn propset svn:ignore "$ignore" "$d"
done

One more thing: I tend to pollute my svn checkouts with many random files. When it's time to commit, I move those files into an 'old' subdirectory, and tell svn to ignore 'old'.

How do I check out a remote Git branch?

You can try

git fetch remote
git checkout --track -b local_branch_name origin/branch_name

or

git fetch
git checkout -b local_branch_name origin/branch_name

How to run Unix shell script from Java code?

As for me all things must be simple. For running script just need to execute

new ProcessBuilder("pathToYourShellScript").start();

Upload File With Ajax XmlHttpRequest

  1. There is no such thing as xhr.file = file;; the file object is not supposed to be attached this way.
  2. xhr.send(file) doesn't send the file. You have to use the FormData object to wrap the file into a multipart/form-data post data object:

    var formData = new FormData();
    formData.append("thefile", file);
    xhr.send(formData);
    

After that, the file can be access in $_FILES['thefile'] (if you are using PHP).

Remember, MDC and Mozilla Hack demos are your best friends.

EDIT: The (2) above was incorrect. It does send the file, but it would send it as raw post data. That means you would have to parse it yourself on the server (and it's often not possible, depend on server configuration). Read how to get raw post data in PHP here.

configure Git to accept a particular self-signed server certificate for a particular https remote

OSX User adjustments.

Following the steps of the Accepted answer worked for me with a small addition when configuring on OSX.

I put the cert.pem file in a directory under my OSX logged in user and thus caused me to adjust the location for the trusted certificate.

Configure git to trust this certificate:

$ git config --global http.sslCAInfo $HOME/git-certs/cert.pem

What's the difference between subprocess Popen and call (how can I use them)?

There are two ways to do the redirect. Both apply to either subprocess.Popen or subprocess.call.

  1. Set the keyword argument shell = True or executable = /path/to/the/shell and specify the command just as you have it there.

  2. Since you're just redirecting the output to a file, set the keyword argument

    stdout = an_open_writeable_file_object
    

    where the object points to the output file.

subprocess.Popen is more general than subprocess.call.

Popen doesn't block, allowing you to interact with the process while it's running, or continue with other things in your Python program. The call to Popen returns a Popen object.

call does block. While it supports all the same arguments as the Popen constructor, so you can still set the process' output, environmental variables, etc., your script waits for the program to complete, and call returns a code representing the process' exit status.

returncode = call(*args, **kwargs) 

is basically the same as calling

returncode = Popen(*args, **kwargs).wait()

call is just a convenience function. It's implementation in CPython is in subprocess.py:

def call(*popenargs, timeout=None, **kwargs):
    """Run command with arguments.  Wait for command to complete or
    timeout, then return the returncode attribute.

    The arguments are the same as for the Popen constructor.  Example:

    retcode = call(["ls", "-l"])
    """
    with Popen(*popenargs, **kwargs) as p:
        try:
            return p.wait(timeout=timeout)
        except:
            p.kill()
            p.wait()
            raise

As you can see, it's a thin wrapper around Popen.

Using HTML5/JavaScript to generate and save a file

Simple solution for HTML5 ready browsers...

function download(filename, text) {
    var pom = document.createElement('a');
    pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
    pom.setAttribute('download', filename);

    if (document.createEvent) {
        var event = document.createEvent('MouseEvents');
        event.initEvent('click', true, true);
        pom.dispatchEvent(event);
    }
    else {
        pom.click();
    }
}

Usage

download('test.txt', 'Hello world!');

How to read embedded resource text file

You can also use this simplified version of @dtb's answer:

public string GetEmbeddedResource(string ns, string res)
{
    using (var reader = new StreamReader(Assembly.GetExecutingAssembly().GetManifestResourceStream(string.Format("{0}.{1}", ns, res))))
    {
        return reader.ReadToEnd();
    }
}

RSA: Get exponent and modulus given a public key

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

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

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

Position buttons next to each other in the center of page

This can be solved using the following CSS:

#container {
  text-align: center;
}

button {
  display: inline-block;
}

display: inline-block will put the buttons side by side and text-align: center places the buttons in the center of the page.

JsFiddle: https://jsfiddle.net/026tbk13/

Easy way to password-protect php page

Not the solution, but for your interest: HTTP authentication only works, when PHP runs as Apache module. Most hosters provide PHP as CGI version only.

Apply jQuery datepicker to multiple instances

A little note to the SeanJA answer.

Interestingly, if you use KnockoutJS and jQuery together the following inputs with different IDs, but with the same data-bind observable:

<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: first_dt" id="date_2" class="datepick" />

will bind one (the same) datepicker to both of the inputs (even though they have different ids or names).

Use separate observables in your ViewModel to bind a separate datepicker to each input:

<data-bind="value: first_dt" id="date_1" class="datepick" />
<data-bind="value: second_dt" id="date_2" class="datepick" />

Initialization:

$('.datepick').each(function(){
    $(this).datepicker();
});

Xampp MySQL not starting - "Attempting to start MySQL service..."

Everytime my MySQL starts, it will stop, then I noticed that some files are getting generated in C:\xampp\mysql\data. I tried deleting some files (like the Error logs, err file, etc.) on that directory. Back up first what you're going to delete to avoid losing data.

I don't know how it works. I'm just trying to enable HTTPS in my local machine but then suddenly MySQL can't be started. But now it's working.

I'm using Windows 10 and XAMPP 3.2.4.

IIS: Idle Timeout vs Recycle

From here:

One way to conserve system resources is to configure idle time-out settings for the worker processes in an application pool. When these settings are configured, a worker process will shut down after a specified period of inactivity. The default value for idle time-out is 20 minutes.

Also check Why is the IIS default app pool recycle set to 1740 minutes?

If you have a just a few sites on your server and you want them to always load fast then set this to zero. Otherwise, when you have 20 minutes without any traffic then the app pool will terminate so that it can start up again on the next visit. The problem is that the first visit to an app pool needs to create a new w3wp.exe worker process which is slow because the app pool needs to be created, ASP.NET or another framework needs to be loaded, and then your application needs to be loaded. That can take a few seconds. Therefore I set that to 0 every chance I have, unless it’s for a server that hosts a lot of sites that don’t always need to be running.

Comparing a variable with a string python not working when redirecting from bash script

When you read() the file, you may get a newline character '\n' in your string. Try either

if UserInput.strip() == 'List contents': 

or

if 'List contents' in UserInput: 

Also note that your second file open could also use with:

with open('/Users/.../USER_INPUT.txt', 'w+') as UserInputFile:     if UserInput.strip() == 'List contents': # or if s in f:         UserInputFile.write("ls")     else:         print "Didn't work" 

How to target only IE (any version) within a stylesheet?

For targeting IE only in my stylesheets, I use this Sass Mixin :

@mixin ie-only {
  @media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
    @content;
  }
}

li:before{ content: "¦"; } How to Encode this Special Character as a Bullit in an Email Stationery?

Never faced this problem before (not worked much on email, I avoid it like the plague) but you could try declaring the bullet with the unicode code point (different notation for CSS than for HTML): content: '\2022'. (you need to use the hex number, not the 8226 decimal one)

Then, in case you use something that picks up those characters and HTML-encodes them into entities (which won't work for CSS strings), I guess it will ignore that.

How to convert image to byte array

Another way to get Byte array from image path is

byte[] imgdata = System.IO.File.ReadAllBytes(HttpContext.Current.Server.MapPath(path));

Reason for Column is invalid in the select list because it is not contained in either an aggregate function or the GROUP BY clause

Basically, what this error is saying is that if you are going to use the GROUP BY clause, then your result is going to be a relation/table with a row for each group, so in your SELECT statement you can only "select" the column that you are grouping by and use aggregate functions on that column because the other columns will not appear in the resulting table.

ImportError: No module named google.protobuf

if protobuf is installed then import it like this

pip install protobuf

import google.protobuf

Loop through JSON in EJS

in my case, datas is an objects of Array for more information please Click Here

<% for(let [index,data] of datas.entries() || []){  %>
 Index : <%=index%>
 Data : <%=data%>
<%} %>

How to set focus to a button widget programmatically?

Yeah it's possible.

Button myBtn = (Button)findViewById(R.id.myButtonId);
myBtn.requestFocus();

or in XML

<Button ...><requestFocus /></Button>

Important Note: The button widget needs to be focusable and focusableInTouchMode. Most widgets are focusable but not focusableInTouchMode by default. So make sure to either set it in code

myBtn.setFocusableInTouchMode(true);

or in XML

android:focusableInTouchMode="true"

How to import existing Git repository into another?

I think you can do this using 'git mv' and 'git pull'.

I'm a fair git noob - so be careful with your main repository - but I just tried this in a temp dir and it seems to work.

First - rename the structure of XXX to match how you want it to look when it's within YYY:

cd XXX
mkdir tmp
git mv ZZZ tmp/ZZZ
git mv tmp ZZZ

Now XXX looks like this:

XXX
 |- ZZZ
     |- ZZZ

Now use 'git pull' to fetch the changes across:

cd ../YYY
git pull ../XXX

Now YYY looks like this:

YYY
 |- ZZZ
     |- ZZZ
 |- (other folders that already were in YYY)

Removing duplicates in the lists

below code is simple for removing duplicate in list

def remove_duplicates(x):
    a = []
    for i in x:
        if i not in a:
            a.append(i)
    return a

print remove_duplicates([1,2,2,3,3,4])

it returns [1,2,3,4]

How do I get the file name from a String containing the Absolute file path?

Alternative using Path (Java 7+):

Path p = Paths.get("C:\\Hello\\AnotherFolder\\The File Name.PDF");
String file = p.getFileName().toString();

Note that splitting the string on \\ is platform dependent as the file separator might vary. Path#getName takes care of that issue for you.

Figure out size of UILabel based on String in Swift

Use an extension on String

Swift 3

extension String {
    func height(withConstrainedWidth width: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)
    
        return ceil(boundingBox.height)
    }

    func width(withConstrainedHeight height: CGFloat, font: UIFont) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = self.boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, attributes: [NSFontAttributeName: font], context: nil)

        return ceil(boundingBox.width)
    }
}

and also on NSAttributedString (which is very useful at times)

extension NSAttributedString {
    func height(withConstrainedWidth width: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: width, height: .greatestFiniteMagnitude)
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
    
        return ceil(boundingBox.height)
    }

    func width(withConstrainedHeight height: CGFloat) -> CGFloat {
        let constraintRect = CGSize(width: .greatestFiniteMagnitude, height: height)
        let boundingBox = boundingRect(with: constraintRect, options: .usesLineFragmentOrigin, context: nil)
    
        return ceil(boundingBox.width)
    }
}

Swift 4 & 5

Just change the value for attributes in the extension String methods

from

[NSFontAttributeName: font]

to

[.font : font]

update one table with data from another

UPDATE table1
SET 
`ID` = (SELECT table2.id FROM table2 WHERE table1.`name`=table2.`name`)

AttributeError: Can only use .dt accessor with datetimelike values

First you need to define the format of date column.

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d %H:%M:%S')

For your case base format can be set to;

df['Date'] = pd.to_datetime(df.Date, format='%Y-%m-%d')

After that you can set/change your desired output as follows;

df['Date'] = df['Date'].dt.strftime('%Y-%m-%d')

T-SQL: Selecting rows to delete via joins

Yes you can. Example :

DELETE TableA 
FROM TableA AS a
INNER JOIN TableB AS b
ON a.BId = b.BId
WHERE [filter condition]

How to embed images in email

Correct way of embedding images into Outlook and avoiding security problems is the next:

  1. Use interop for Outlook 2003;
  2. Create new email and set it save folder;
  3. Do not use base64 embedding, outlook 2007 does not support it; do not reference files on your disk, they won't be send; do not use word editor inspector because you will get security warnings on some machines;
  4. Attachment must have png/jpg extension. If it will have for instance tmp extension - Outlook will warn user;
  5. Pay attention how CID is generated without mapi;
  6. Do not access properties via getters or you will get security warnings on some machines.

    public static void PrepareEmail()
    {
        var attachFile = Path.Combine(
            Application.StartupPath, "mySuperImage.png"); // pay attention that image must not contain spaces, because Outlook cannot inline such images
    
        Microsoft.Office.Interop.Outlook.Application outlook = null;
        NameSpace space = null;
        MAPIFolder folder = null;
        MailItem mail = null;
        Attachment attachment = null;
        try
        {
            outlook = new Microsoft.Office.Interop.Outlook.Application();
            space = outlook.GetNamespace("MAPI");
            space.Logon(null, null, true, true);
    
            folder = space.GetDefaultFolder(OlDefaultFolders.olFolderSentMail);
            mail = (MailItem) outlook.CreateItem(OlItemType.olMailItem);
    
            mail.SaveSentMessageFolder = folder;
            mail.Subject = "Hi Everyone";
            mail.Attachments.Add(attachFile, OlAttachmentType.olByValue, 0, Type.Missing); 
            // Last Type.Missing - is for not to show attachment in attachments list.
    
            string attachmentId = Path.GetFileName(attachFile);
            mail.BodyFormat = OlBodyFormat.olFormatHTML;
    
             mail.HTMLBody = string.Format("<br/><img src=\'cid:{0}\' />", attachmentId);
    
            mail.Display(false);
        }
        finally
        {
            ReleaseComObject(outlook, space, folder, mail, attachment);
        }
    }
    

jQuery click anywhere in the page except on 1 div

try this

 $('html').click(function() {
 //your stuf
 });

 $('#menucontainer').click(function(event){
     event.stopPropagation();
 });

you can also use the outside events

How to open a link in new tab (chrome) using Selenium WebDriver?

this below code works for me in Selenium 3 and chrome version 58.

    WebDriver driver = new ChromeDriver();
    driver.get("http://yahoo.com");  
    ((JavascriptExecutor)driver).executeScript("window.open()");
    ArrayList<String> tabs = new ArrayList<String>(driver.getWindowHandles());
    driver.switchTo().window(tabs.get(1));
    driver.get("http://google.com");

Java generics - ArrayList initialization

A lot of this has to do with polymorphism. When you assign

X = new Y();

X can be much less 'specific' than Y, but not the other way around. X is just the handle you are accessing Y with, Y is the real instantiated thing,

You get an error here because Integer is a Number, but Number is not an Integer.

ArrayList<Integer> a = new ArrayList<Number>(); // compile-time error

As such, any method of X that you call must be valid for Y. Since X is more generally it probably shares some, but not all of Y's methods. Still, any arguments given must be valid for Y.

In your examples with add, an int (small i) is not a valid Object or Integer.

ArrayList<?> a = new ArrayList<?>();

This is no good because you can't actually instantiate an array list containing ?'s. You can declare one as such, and then damn near anything can follow in new ArrayList<Whatever>();

Return current date plus 7 days

$date = strtotime("+7 day", strtotime("M d, Y"));
$date =  date('j M, Y', $date);

This will work as well

What is the effect of extern "C" in C++?

I used 'extern "C"' before for dll(dynamic link library) files to make etc. main() function "exportable" so it can be used later in another executable from dll. Maybe an example of where I used to use it can be useful.

DLL

#include <string.h>
#include <windows.h>

using namespace std;

#define DLL extern "C" __declspec(dllexport)
//I defined DLL for dllexport function
DLL main ()
{
    MessageBox(NULL,"Hi from DLL","DLL",MB_OK);
}

EXE

#include <string.h>
#include <windows.h>

using namespace std;

typedef LPVOID (WINAPI*Function)();//make a placeholder for function from dll
Function mainDLLFunc;//make a variable for function placeholder

int main()
{
    char winDir[MAX_PATH];//will hold path of above dll
    GetCurrentDirectory(sizeof(winDir),winDir);//dll is in same dir as exe
    strcat(winDir,"\\exmple.dll");//concentrate dll name with path
    HINSTANCE DLL = LoadLibrary(winDir);//load example dll
    if(DLL==NULL)
    {
        FreeLibrary((HMODULE)DLL);//if load fails exit
        return 0;
    }
    mainDLLFunc=(Function)GetProcAddress((HMODULE)DLL, "main");
    //defined variable is used to assign a function from dll
    //GetProcAddress is used to locate function with pre defined extern name "DLL"
    //and matcing function name
    if(mainDLLFunc==NULL)
    {
        FreeLibrary((HMODULE)DLL);//if it fails exit
        return 0;
    }
    mainDLLFunc();//run exported function 
    FreeLibrary((HMODULE)DLL);
}

Error: "dictionary update sequence element #0 has length 1; 2 is required" on Django 1.4

I encountered this issue when trying to invoke the update method with a parameter of a wrong type. The expected dict was:

{'foo': True}

The one that was passed was:

{'foo': "True"}

make sure you check all the parameters you pass are of the expected type.

Access index of the parent ng-repeat from child ng-repeat

$parent doesn't work if there are multiple parents. instead of that we can define a parent index variable in init and use it

<div data-ng-init="parentIndex = $index" ng-repeat="f in foos">
  <div>
    <div data-ng-init="childIndex = $index" ng-repeat="b in foos.bars">
      <a ng-click="addSomething(parentIndex)">Add Something</a>
    </div>
  </div>
</div>

How to make background of table cell transparent

I use the "transparent" keyword and it works perfect!

<style type="text/css">
#img table,tr, td {
    border: 1px solid transparent;
    align="center";
    border-spacing: 25px;
    border-collapse: collapse;
    border-width: 5px;
    padding: 5px;
    padding-left: 50px;
}

What's the purpose of META-INF?

META-INF in Maven

In Maven the META-INF folder is understood because of the Standard Directory Layout, which by name convention package your project resources within JARs: any directories or files placed within the ${basedir}/src/main/resources directory are packaged into your JAR with the exact same structure starting at the base of the JAR. The Folder ${basedir}/src/main/resources/META-INF usually contains .properties files while in the jar contains a generated MANIFEST.MF, pom.properties, the pom.xml, among other files. Also frameworks like Spring use classpath:/META-INF/resources/ to serve web resources. For more information see How do I add resources to my Maven Project.

Lightweight Javascript DB for use in Node.js

Maybe you should try LocallyDB it's easy-to-use and lightweight in addition to the with advanced selecting system similar to javascript conditional expression...

https://github.com/btwael/locallydb

How do I calculate power-of in C#?

For powers of 2:

var twoToThePowerOf = 1 << yourExponent;
// eg: 1 << 12 == 4096

using javascript to detect whether the url exists before display in iframe

You can try and do a simple GET on the page, if you get a 200 back it means the page exists. Try this (using jQuery), the function is the success callback function on a successful page load. Note this will only work on sites within your domain to prevent XSS. Other domains will have to be handled server side

$.get(
   yourURL,
   function(data, textStatus, jqXHR) {
      //load the iframe here...
   }
);

Using "margin: 0 auto;" in Internet Explorer 8

  1. Assuming margin: 0 auto then the element should be centered, but the width is left as-is--whatever it is calculated to be, disregarding any margin settings.
  2. If you set the <INPUT> tag to display:block, then it should be centered with margin: 0 auto.

See Visual formatting model details - calculating widths and margins from the CSS 2.1 specs for more details. Relavent bits include:

In a block formatting context, each box's left outer edge touches the left edge of the containing block.

and

When the total width of the inline boxes on a line is less than the width of the line box containing them, their horizontal distribution within the line box is determined by the 'text-align' property.

finally

If 'width' is set to 'auto', any other 'auto' values become '0' and 'width' follows from the resulting equality.

If both 'margin-left' and 'margin-right' are 'auto', their used values are equal. This horizontally centers the element with respect to the edges of the containing block.

Get the position of a div/span tag

I realize this is an old thread, but @alex 's answer needs to be marked as the correct answer

element.getBoundingClientRect() is an exact match to jQuery's $(element).offset()

And it's compatible with IE4+ ... https://developer.mozilla.org/en-US/docs/Web/API/Element.getBoundingClientRect

How do I install Python 3 on an AWS EC2 instance?

EC2 (on the Amazon Linux AMI) currently supports python3.4 and python3.5.

sudo yum install python35
sudo yum install python35-pip

Checking for empty result (php, pdo, mysql)

You're throwing away a result row when you do $sth->fetchColumn(). That's not how you check if there's any results. you do

if ($sth->rowCount() > 0) {
  ... got results ...
} else {
   echo 'nothing';
}

relevant docs here: http://php.net/manual/en/pdostatement.rowcount.php

How to replace NaN values by Zeroes in a column of a Pandas Dataframe?

To replace nan in different columns with different ways:

   replacement= {'column_A': 0, 'column_B': -999, 'column_C': -99999}
   df.fillna(value=replacement)

Close all infowindows in Google Maps API v3

I had a dynamic loop that was creating the infowindows and markers based on how many were input into the CMS, so I didn't want to create a new InfoWindow() on every event click and bog it down with requests, if that ever arose. Instead, I tried to know what the specific infowindow variable for each instance was going to be out of the set amount of locations I had, and then prompt Maps to close all of them before it opened the correct one.

My array of locations was called locations, so the PHP I set up before the actual maps initilization to get my infowindow variable names was:

for($k = 0; $k < count($locations); $k++) {
        $infowindows[] = 'infowindow' . $k; 
} 

Then after initialzing the map and so forth, in the script I had a PHP foreach loop creating the dynamic info windows using a counter:

//...javascript map initilization
<?php 
$i=0;
foreach($locations as $location) {

    ..//get latitudes, longitude, image, etc...

echo 'var mapMarker' . $i . ' = new google.maps.Marker({
          position: myLatLng' . $i . ',
          map: map,
          icon: image
      });';

echo 'var contentString' . $i . ' = "<h1>' . $title[$i] . '</h1><h2>' . $address[$i] . '</h2>' . $content[$i] .         '";'; 
echo 'infowindow' . $i . ' = new google.maps.InfoWindow({ ';
echo '    content: contentString' . $i . '
          });';

echo 'google.maps.event.addListener(mapMarker' . $i . ', "click", function() { ';   
    foreach($infowindows as $window) {  
        echo $window . '.close();'; 
    }
        echo 'infowindow' . $i . '.open(map,mapMarker'. $i . ');
      });';

$i++; 
}
?>
...//continue with Maps script... 

So, the point is, before I called the entire map script, I had an array with the names I knew were going to be outputted when an InfoWindow() was created, like infowindow0, infowindow1, infowindow2, etc...

Then, on the click event for each marker, the foreach loop goes through and says close all of them before you follow through with the next step of opening them. It turns out looking like this:

google.maps.event.addListener(mapMarker0, "click", function() {
    infowindow0.close();
    infowindow1.close();
    infowindow2.close();
    infowindow0.open(map,mapMarker0);
}

Just a different way of doing things I suppose... but I hope it helps someone.

add onclick function to a submit button

I have this code:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
<SCRIPT type=text/javascript>_x000D_
function deshabilitarBoton() {     _x000D_
    document.getElementById("boton").style.display = 'none';_x000D_
    document.getElementById("envio").innerHTML ="<br><img src='img/loading.gif' width='16' height='16' border='0'>Generando...";     _x000D_
    return true;_x000D_
} _x000D_
</SCRIPT>_x000D_
<title>untitled</title>_x000D_
</head>_x000D_
<body>_x000D_
<form name="form" action="ok.do" method="post" >_x000D_
<table>_x000D_
<tr>_x000D_
<td>Fecha inicio:</td>_x000D_
<td><input type="TEXT" name="fecha_inicio" id="fecha_inicio"  /></td>_x000D_
</tr>_x000D_
</table>_x000D_
<div id="boton">_x000D_
   <input type="submit" name="event" value="Enviar" class="button" onclick="return deshabilitarBoton()" />_x000D_
</div>_x000D_
<div id="envio">_x000D_
</div>_x000D_
</form>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

Another corner case that this could happen: if you read/write a JAR file through a URL and later try to delete the same file within the same JVM session.

File f = new File("/tmp/foo.jar");
URL j = f.toURI().toURL();

URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
URLConnection c = u.openConnection();

// open a Jar entry in auto-closing manner
try (InputStream i = c.getInputStream()) {

    // just read some stuff; for demonstration purposes only
    byte[] first16 = new byte[16];
    i.read(first16);
    System.out.println(new String(first16));
}

// ...

// i is now closed, so we should be good to delete the jar; but...
System.out.println(f.delete());     // says false!

Reason is that the internal JAR file handling logic of Java, tends to cache JarFile entries:

// inner class of `JarURLConnection` that wraps the actual stream returned by `getInputStream()`

class JarURLInputStream extends FilterInputStream {
    JarURLInputStream(InputStream var2) {
        super(var2);
    }

    public void close() throws IOException {
        try {
            super.close();
        } finally {

            // if `getUseCaches()` is set, `jarFile` won't get closed!

            if (!JarURLConnection.this.getUseCaches()) {
                JarURLConnection.this.jarFile.close();
            }
        }
    }
}

And each JarFile (rather, the underlying ZipFile structure) would hold a handle to the file, right from the time of construction up until close() is invoked:

public ZipFile(File file, int mode, Charset charset) throws IOException {
    // ...

    jzfile = open(name, mode, file.lastModified(), usemmap);

    // ...
}

// ...

private static native long open(String name, int mode, long lastModified,
                                boolean usemmap) throws IOException;

There's a good explanation on this NetBeans issue.


Apparently there are two ways to "fix" this:

  • You can disable the JAR file caching - for the current URLConnection, or for all future URLConnections (globally) in the current JVM session:

    URL u = new URL("jar:" + j + "!/META-INF/MANIFEST.MF");
    URLConnection c = u.openConnection();
    
    // for only c
    c.setUseCaches(false);
    
    // globally; for some reason this method is not static,
    // so we still need to access it through a URLConnection instance :(
    c.setDefaultUseCaches(false);
    
  • [HACK WARNING!] You can manually purge the JarFile from the cache when you are done with it. The cache manager sun.net.www.protocol.jar.JarFileFactory is package-private, but some reflection magic can get the job done for you:

    class JarBridge {
    
        static void closeJar(URL url) throws Exception {
    
            // JarFileFactory jarFactory = JarFileFactory.getInstance();
            Class<?> jarFactoryClazz = Class.forName("sun.net.www.protocol.jar.JarFileFactory");
            Method getInstance = jarFactoryClazz.getMethod("getInstance");
            getInstance.setAccessible(true);
            Object jarFactory = getInstance.invoke(jarFactoryClazz);
    
            // JarFile jarFile = jarFactory.get(url);
            Method get = jarFactoryClazz.getMethod("get", URL.class);
            get.setAccessible(true);
            Object jarFile = get.invoke(jarFactory, url);
    
            // jarFactory.close(jarFile);
            Method close = jarFactoryClazz.getMethod("close", JarFile.class);
            close.setAccessible(true);
            //noinspection JavaReflectionInvocation
            close.invoke(jarFactory, jarFile);
    
            // jarFile.close();
            ((JarFile) jarFile).close();
        }
    }
    
    // and in your code:
    
    // i is now closed, so we should be good to delete the jar
    JarBridge.closeJar(j);
    System.out.println(f.delete());     // says true, phew.
    

Please note: All this is based on Java 8 codebase (1.8.0_144); they may not work with other / later versions.

What is the difference between a candidate key and a primary key?

John Woo's answer is correct, as far as it goes. Here are a few additional points.

A primary key is always one of the candidate keys. Fairly often, it's the only candidate.

A table with no candidate keys does not represent a relation. If you're using the relational model to help you build a good database, then every table you design will have at least one candidate key.

The relational model would be complete without the concept of primary key. It wasn't in the original presentation of the relational model. As a practical matter, the use of foreign key references without a declared primary key leads to a mess. It could be a logically correct mess, but it's a mess nonetheless. Declaring a primary key lets the DBMS help you enforce the data rules. Most of the time, having the DBMS help you enforce the data rules is a good thing, and well worth the cost.

Some database designers and some users have some mental confusion about whether the primary key identifies a row (record) in a table or an instance of an entity in the subject matter that the table represents. In an ideal world, it's supposed to do both, and there should be a one-for-one correspondence between rows in an entity table and instances of the corresponding entity.

In the real world, things get screwed up. Somebody enters the same new employee twice, and the employee ends up with two ids. Somebody gets hired, but the data entry slips through the cracks in some manual process, and the employee doesn't get an id, until the omission is corrected. A database that does not collapse the first time things get screwed up is more robust than one that does.

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

Alternatively, you can use Inner Queries to do so.

SQL> INSERT INTO <NEW_TABLE> SELECT * FROM CUSTOMERS WHERE ID IN (SELECT ID FROM <OLD_TABLE>);

Hope this helps!

What is the most efficient way to store tags in a database?

One item is going to have many tags. And one tag will belong to many items. This implies to me that you'll quite possibly need an intermediary table to overcome the many-to-many obstacle.

Something like:

Table: Items
Columns: Item_ID, Item_Title, Content

Table: Tags
Columns: Tag_ID, Tag_Title

Table: Items_Tags
Columns: Item_ID, Tag_ID

It might be that your web app is very very popular and need de-normalizing down the road, but it's pointless muddying the waters too early.

Best way to iterate through a Perl array

1 is substantially different from 2 and 3, since it leaves the array in tact, whereas the other two leave it empty.

I'd say #3 is pretty wacky and probably less efficient, so forget that.

Which leaves you with #1 and #2, and they do not do the same thing, so one cannot be "better" than the other. If the array is large and you don't need to keep it, generally scope will deal with it (but see NOTE), so generally, #1 is still the clearest and simplest method. Shifting each element off will not speed anything up. Even if there is a need to free the array from the reference, I'd just go:

undef @Array;

when done.

  • NOTE: The subroutine containing the scope of the array actually keeps the array and re-uses the space next time. Generally, that should be fine (see comments).

Can't push to GitHub because of large file which I already deleted

I am adding to the first answer.

git filter-branch --index-filter 'git rm -r --cached --ignore-unmatch ' HEAD

There will be some merge conflict from origin/master.

Your branch and 'origin/master' have diverged, and have 114 and 109 different commits each, respectively. (use "git pull" to merge the remote branch into yours)

Please run this

git reset --hard origin/master

It will throw away all my staged and unstaged changes, forget everything on my current local branch and make it exactly the same as origin/master.

Instantiating a generic class in Java

From https://stackoverflow.com/a/2434094/848072. You need a default constructor for T class.


import java.lang.reflect.ParameterizedType;

class Foo {

  public bar() {
    ParameterizedType superClass = (ParameterizedType) getClass().getGenericSuperclass();
    Class type = (Class) superClass.getActualTypeArguments()[0];
    try {
      T t = type.newInstance();
      //Do whatever with t
    } catch (Exception e) {
      // Oops, no default constructor
      throw new RuntimeException(e);
    } 
  }
}

Java - get index of key in HashMap?

Not sure if this is any "cleaner", but:

List keys = new ArrayList(map.keySet());
for (int i = 0; i < keys.size(); i++) {
    Object obj = keys.get(i);
    // do stuff here
}

What's the proper way to "go get" a private repository?

For me, the solutions offered by others still gave the following error during go get

[email protected]: Permission denied (publickey). fatal: Could not read from remote repository. Please make sure you have the correct access rights and the repository exists.

What this solution required

  1. As stated by others:

    git config --global url."[email protected]:".insteadOf "https://github.com/"

  2. Removing the passphrase from my ./ssh/id_rsa key which was used for authenticating the connection to the repository. This can be done by entering an empty password when prompted as a response to:

    ssh-keygen -p

Why this works

This is not a pretty workaround as it is always better to have a passphrase on your private key, but it was causing issues somewhere inside OpenSSH.

go get uses internally git, which uses openssh to open the connection. OpenSSH takes the certs necessary for authentication from .ssh/id_rsa. When executing git commands from the command line an agent can take care of opening the id_rsa file for you so that you do not have to specify the passphrase every time, but when executed in the belly of go get, this did not work somewhy in my case. OpenSSH wants to prompt you then for a password but since it is not possible due to how it was called, it prints to its debug log:

read_passphrase: can't open /dev/tty: No such device or address

And just fails. If you remove the passphrase from the key file, OpenSSH will get to your key without that prompt and it works

This might be caused by Go fetching modules concurrently and opening multiple SSH connections to Github at the same time (as described in this article). This is somewhat supported by the fact that OpenSSH debug log showed the initial connection to the repository succeed, but later tried it again for some reason and this time opted to ask for a passphrase.

However the solution of using SSH connection multiplexing as put forward in the mentioned article did not work for me. For the record, the author suggested adding the collowing conf to the ssh config file for the affected host:

  ControlMaster auto
  ControlPersist 3600
  ControlPath ~/.ssh/%r@%h:%p

But as stated, for me it did not work, maybe I did it wrong

Return value from exec(@sql)

On the one hand you could use sp_executesql:

exec sp_executesql N'select @rowcount=count(*) from anytable', 
                    N'@rowcount int output', @rowcount output;

On the other hand you could use a temporary table:

declare @result table ([rowcount] int);
insert into @result ([rowcount])
exec (N'select count(*) from anytable');
declare @rowcount int = (select top (1) [rowcount] from @result);

Hide Show content-list with only CSS, no javascript used

This is what I've used recently.

CSS

div#tabs p{display:none;}

div#tabs p.tab1:target {display:block;}
div#tabs p.tab2:target {display:block;}
div#tabs p.tab3:target {display:block;}

HTML

<div id='tabs'>
  <h2 class="nav-tab-wrapper">
    <a href="#tab1" class="nav-tab tab1">Pages</a>
    <a href="#tab2" class="nav-tab nav-tab-active tab2">Email</a>
    <a href="#tab3" class="nav-tab tab3">Support</a>
  </h2>

  <p id='tab1' class='tab1'>Awesome tab1 stuff</p>
  <p id='tab2' class='tab2'>Tab2 stuff</p>
  <p id='tab3' class='tab3'>Tab3 stuff</p>

</div>

https://jsfiddle.net/hoq0djwc/1/

Hope it helps somewhere.

SQL Server error on update command - "A severe error occurred on the current command"

in my case, the method: context.Database.CreateIfNotExists(); called up multiple times before create database and crashed an error A severe error occurred on the current command. The results, if any, should be discarded.

how to print an exception using logger?

Try to log the stack trace like below:

logger.error("Exception :: " , e);

How to calculate probability in a normal distribution given mean & standard deviation?

Starting Python 3.8, the standard library provides the NormalDist object as part of the statistics module.

It can be used to get the probability density function (pdf - likelihood that a random sample X will be near the given value x) for a given mean (mu) and standard deviation (sigma):

from statistics import NormalDist

NormalDist(mu=100, sigma=12).pdf(98)
# 0.032786643008494994

Also note that the NormalDist object also provides the cumulative distribution function (cdf - probability that a random sample X will be less than or equal to x):

NormalDist(mu=100, sigma=12).cdf(98)
# 0.43381616738909634

Laravel Eloquent limit and offset

Try this sample code:

$art = Article::where('id',$article)->firstOrFail();

$products = $art->products->take($limit);

Set Google Chrome as the debugging browser in Visual Studio

For win7 chrome can be found at:

C:\Users\[UserName]\AppData\Local\Google\Chrome\Application\chrome.exe

For VS2017 click the little down arrow next to the run in debug/release mode button to find the "browse with..." option.

How to set the background image of a html 5 canvas to .png image

You can give the background image in css :

#canvas { background:url(example.jpg) }

it will show you canvas back ground image

Regular expression containing one word or another

You just missed an extra pair of brackets for the "OR" symbol. The following should do the trick:

([0-9]+)\s+((\bseconds\b)|(\bminutes\b))

Without those you were either matching a number followed by seconds OR just the word minutes

Check if element is in the list (contains)

Use std::find, something like:

if (std::find(std::begin(my_list), std::end(my_list), my_var) != std::end(my_list))
    // my_list has my_var

How to take keyboard input in JavaScript?

Since event.keyCode is deprecated, I found the event.key useful in javascript. Below is an example for getting the names of the keyboard keys pressed (using an input element). They are given as a KeyboardEvent key text property:

_x000D_
_x000D_
function setMyKeyDownListener() {_x000D_
    window.addEventListener(_x000D_
      "keydown",_x000D_
      function(event) {MyFunction(event.key)}_x000D_
    )_x000D_
}_x000D_
_x000D_
function MyFunction (the_Key) {_x000D_
    alert("Key pressed is: "+the_Key);_x000D_
}
_x000D_
html { font-size: 4vw; background-color: green; color: white; padding: 1em; }
_x000D_
<body onload="setMyKeyDownListener()">_x000D_
    <div>_x000D_
        <input id="MyInputId">_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Determine when a ViewPager changes pages

For ViewPager2,

viewPager.registerOnPageChangeCallback(object : ViewPager2.OnPageChangeCallback() {
  override fun onPageSelected(position: Int) {
    super.onPageSelected(position)
  }
})

where OnPageChangeCallback is a static class with three methods:

onPageScrolled(int position, float positionOffset, @Px int positionOffsetPixels),
onPageSelected(int position), 
onPageScrollStateChanged(@ScrollState int state)

How do I add a simple jQuery script to WordPress?

function xyz_scripts() {
    wp_enqueue_script('jquery');
}
add_action('wp_enqueue_scripts', 'xyz_scripts');

CSS scale down image to fit in containing div, without specifing original size

Hope this will answer the age old problem (Without using CSS background property)

Html

<div class="card-cont">
 <img src="demo.png" />
</div>

Css

.card-cont{
  width:100%;
  height:150px;
}

.card-cont img{
  max-width: 100%;
  min-width: 100%;
  min-height: 150px;
}

Using local makefile for CLion instead of CMake

Currently, only CMake is supported by CLion. Others build systems will be added in the future, but currently, you can only use CMake.

An importer tool has been implemented to help you to use CMake.

Edit:

Source : http://blog.jetbrains.com/clion/2014/09/clion-answers-frequently-asked-questions/

How can I output leading zeros in Ruby?

If the maximum number of digits in the counter is known (e.g., n = 3 for counters 1..876), you can do

str = "file_" + i.to_s.rjust(n, "0")

What is a singleton in C#?

A Singleton (and this isn't tied to C#, it's an OO design pattern) is when you want to allow only ONE instance of a class to be created throughout your application. Useages would typically include global resources, although I will say from personal experience, they're very often the source of great pain.

regex error - nothing to repeat

Beyond the bug that was discovered and fixed, I'll just note that the error message sre_constants.error: nothing to repeat is a bit confusing. I was trying to use r'?.*' as a pattern, and thought it was complaining for some strange reason about the *, but the problem is actually that ? is a way of saying "repeat zero or one times". So I needed to say r'\?.*'to match a literal ?

How to find if a given key exists in a C++ std::map

m.find == m.end() // not found 

If you want to use other API, then find go for m.count(c)>0

 if (m.count("f")>0)
      cout << " is an element of m.\n";
    else 
      cout << " is not an element of m.\n";

How to put more than 1000 values into an Oracle IN clause

select column_X, ... from my_table
where ('magic', column_X ) in (
        ('magic', 1),
        ('magic', 2),
        ('magic', 3),
        ('magic', 4),
             ...
        ('magic', 99999)
    ) ...

Resource from src/main/resources not found after building with maven

I think assembly plugin puts the file on class path. The location will be different in in the JAR than you see on disk. Unpack the resulting JAR and look where the file is located there.

ASP.net vs PHP (What to choose)

There are a couple of topics that might provide you with an answer. You could also run some tests yourself. Doesn't see too hard to get some loops started and adding a timer to calculate the execution time ;-)

Escaping special characters in Java Regular Expressions

The only way the regex matcher knows you are looking for a digit and not the letter d is to escape the letter (\d). To type the regex escape character in java, you need to escape it (so \ becomes \\). So, there's no way around typing double backslashes for special regex chars.

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

Step 1. Install "Apache_OpenOffice_4.1.2" in your system Step 2. Download "unoconv" library from github or any where else.

-> C:\Program Files (x86)\OpenOffice 4\program\python.exe = Path of open office install directory

-> D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv = Path of library folder

-> D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' = path and file name of pdf

-> D:/wamp/www/doc_to_pdf/files/'.$doc_file_name = Path of your document file.

If pdf not created than last step is Go to ->Control Panel\All Control Panel Items\Administrative Tools-> services-> find "wampapache" -> right click and click on property -> click on logon tab Than check checkbox of allow service to interact with desktop

Create sample .php file and put below code and run on wamp or xampp server

$result = exec('"C:\Program Files (x86)\OpenOffice 4\program\python.exe" D:\wamp\www\doc_to_pdf\libobasis4.4-pyuno\unoconv -f pdf -o D:/wamp/www/doc_to_pdf/files/'.$pdf_File_name.' D:/wamp/www/doc_to_pdf/files/'.$doc_file_name);

This code working for me in windows-8 operating system

AngularJS - Does $destroy remove event listeners?

Event listeners

First off it's important to understand that there are two kinds of "event listeners":

  1. Scope event listeners registered via $on:

    $scope.$on('anEvent', function (event, data) {
      ...
    });
    
  2. Event handlers attached to elements via for example on or bind:

    element.on('click', function (event) {
      ...
    });
    

$scope.$destroy()

When $scope.$destroy() is executed it will remove all listeners registered via $on on that $scope.

It will not remove DOM elements or any attached event handlers of the second kind.

This means that calling $scope.$destroy() manually from example within a directive's link function will not remove a handler attached via for example element.on, nor the DOM element itself.


element.remove()

Note that remove is a jqLite method (or a jQuery method if jQuery is loaded before AngularjS) and is not available on a standard DOM Element Object.

When element.remove() is executed that element and all of its children will be removed from the DOM together will all event handlers attached via for example element.on.

It will not destroy the $scope associated with the element.

To make it more confusing there is also a jQuery event called $destroy. Sometimes when working with third-party jQuery libraries that remove elements, or if you remove them manually, you might need to perform clean up when that happens:

element.on('$destroy', function () {
  scope.$destroy();
});

What to do when a directive is "destroyed"

This depends on how the directive is "destroyed".

A normal case is that a directive is destroyed because ng-view changes the current view. When this happens the ng-view directive will destroy the associated $scope, sever all the references to its parent scope and call remove() on the element.

This means that if that view contains a directive with this in its link function when it's destroyed by ng-view:

scope.$on('anEvent', function () {
 ...
});

element.on('click', function () {
 ...
});

Both event listeners will be removed automatically.

However, it's important to note that the code inside these listeners can still cause memory leaks, for example if you have achieved the common JS memory leak pattern circular references.

Even in this normal case of a directive getting destroyed due to a view changing there are things you might need to manually clean up.

For example if you have registered a listener on $rootScope:

var unregisterFn = $rootScope.$on('anEvent', function () {});

scope.$on('$destroy', unregisterFn);

This is needed since $rootScope is never destroyed during the lifetime of the application.

The same goes if you are using another pub/sub implementation that doesn't automatically perform the necessary cleanup when the $scope is destroyed, or if your directive passes callbacks to services.

Another situation would be to cancel $interval/$timeout:

var promise = $interval(function () {}, 1000);

scope.$on('$destroy', function () {
  $interval.cancel(promise);
});

If your directive attaches event handlers to elements for example outside the current view, you need to manually clean those up as well:

var windowClick = function () {
   ...
};

angular.element(window).on('click', windowClick);

scope.$on('$destroy', function () {
  angular.element(window).off('click', windowClick);
});

These were some examples of what to do when directives are "destroyed" by Angular, for example by ng-view or ng-if.

If you have custom directives that manage the lifecycle of DOM elements etc. it will of course get more complex.

JavaScript and getElementById for multiple elements with the same ID

You shouldn't do that and even if it's possible it's not reliable and prone to cause issues.

Reason being that an ID is unique on the page. i.e. you cannot have more than 1 element on the page with the same ID.

Spin or rotate an image on hover

if you want to rotate inline elements, you should set the inline element to inline-block first.

i {
  display: inline-block;
}

i:hover {
  animation: rotate-btn .5s linear 3;
  -webkit-animation: rotate-btn .5s linear 3;
}

@keyframes rotate-btn {
  0% {
    transform: rotate(0);
  }
  100% {
    transform: rotate(-360deg);
  }
}

Python, Pandas : write content of DataFrame into text File

I used a slightly modified version:

with open(file_name, 'w', encoding = 'utf-8') as f:
    for rec_index, rec in df.iterrows():
        f.write(rec['<field>'] + '\n')

I had to write the contents of a dataframe field (that was delimited) as a text file.

Prevent the keyboard from displaying on activity start

Try this -

this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Alternatively,

  1. you could also declare in your manifest file's activity -
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".Main"
          android:label="@string/app_name"
          android:windowSoftInputMode="stateHidden"
          >
  1. If you have already been using android:windowSoftInputMode for a value like adjustResize or adjustPan, you can combine two values like:
<activity
        ...
        android:windowSoftInputMode="stateHidden|adjustPan"
        ...
        >

This will hide the keyboard whenever appropriate but pan the activity view in case the keyboard has to be shown.

Rails Model find where not equal

In Rails 4.x (See http://edgeguides.rubyonrails.org/active_record_querying.html#not-conditions)

GroupUser.where.not(user_id: me)

In Rails 3.x

GroupUser.where(GroupUser.arel_table[:user_id].not_eq(me))

To shorten the length, you could store GroupUser.arel_table in a variable or if using inside the model GroupUser itself e.g., in a scope, you can use arel_table[:user_id] instead of GroupUser.arel_table[:user_id]

Rails 4.0 syntax credit to @jbearden's answer

non static method cannot be referenced from a static context

In Java, static methods belong to the class rather than the instance. This means that you cannot call other instance methods from static methods unless they are called in an instance that you have initialized in that method.

Here's something you might want to do:

public class Foo
{
  public void fee()
  {
     //do stuff  
  }

  public static void main (String[]arg) 
  { 
     Foo foo = new Foo();
     foo.fee();
  } 
}

Notice that you are running an instance method from an instance that you've instantiated. You can't just call call a class instance method directly from a static method because there is no instance related to that static method.

Why do I need to explicitly push a new branch?

Output of git push when pushing a new branch

> git checkout -b new_branch
Switched to a new branch 'new_branch'
> git push
fatal: The current branch new_branch has no upstream branch.
To push the current branch and set the remote as upstream, use

    git push --set-upstream origin new_branch

A simple git push assumes that there already exists a remote branch that the current local branch is tracking. If no such remote branch exists, and you want to create it, you must specify that using the -u (short form of --set-upstream) flag.

Why this is so? I guess the implementers felt that creating a branch on the remote is such a major action that it should be hard to do it by mistake. git push is something you do all the time.

"Isn't a branch a new change to be pushed by default?" I would say that "a change" in Git is a commit. A branch is a pointer to a commit. To me it makes more sense to think of a push as something that pushes commits over to the other repositories. Which commits are pushed is determined by what branch you are on and the tracking relationship of that branch to branches on the remote.

You can read more about tracking branches in the Remote Branches chapter of the Pro Git book.

Hidden property of a button in HTML

<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4/jquery.min.js"></script>
<script>

function showButtons () { $('#b1, #b2, #b3').show(); }

</script>
<style type="text/css">
#b1, #b2, #b3 {
display: none;
}

</style>
</head>
<body>

<a href="#" onclick="showButtons();">Show me the money!</a>

<input type="submit" id="b1" value="B1" />
<input type="submit" id="b2" value="B2"/>
<input type="submit" id="b3" value="B3" />

</body>
</html>

jQuery changing font family and font size

In my opinion, it would be a cleaner and easier solution to just set a class on the body and set the font-family in css according to that class.
don't know if that's an option in your case though.

What browsers support HTML5 WebSocket API?

Client side

  • Hixie-75:
    • Chrome 4.0 + 5.0
    • Safari 5.0.0
  • HyBi-00/Hixie-76:
  • HyBi-07+:
  • HyBi-10:
    • Chrome 14.0 + 15.0
    • Firefox 7.0 + 8.0 + 9.0 + 10.0 - prefixed: MozWebSocket
    • IE 10 (from Windows 8 developer preview)
  • HyBi-17/RFC 6455
    • Chrome 16
    • Firefox 11
    • Opera 12.10 / Opera Mobile 12.1

Any browser with Flash can support WebSocket using the web-socket-js shim/polyfill.

See caniuse for the current status of WebSockets support in desktop and mobile browsers.

See the test reports from the WS testsuite included in Autobahn WebSockets for feature/protocol conformance tests.


Server side

It depends on which language you use.

In Java/Java EE:

Some other Java implementations:

In C#:

In PHP:

In Python:

In C:

In Node.js:

  • Socket.io : Socket.io also has serverside ports for Python, Java, Google GO, Rack
  • sockjs : sockjs also has serverside ports for Python, Java, Erlang and Lua
  • WebSocket-Node - Pure JavaScript Client & Server implementation of HyBi-10.

Vert.x (also known as Node.x) : A node like polyglot implementation running on a Java 7 JVM and based on Netty with :

  • Support for Ruby(JRuby), Java, Groovy, Javascript(Rhino/Nashorn), Scala, ...
  • True threading. (unlike Node.js)
  • Understands multiple network protocols out of the box including: TCP, SSL, UDP, HTTP, HTTPS, Websockets, SockJS as fallback for WebSockets

Pusher.com is a Websocket cloud service accessible through a REST API.

DotCloud cloud platform supports Websockets, and Java (Jetty Servlet Container), NodeJS, Python, Ruby, PHP and Perl programming languages.

Openshift cloud platform supports websockets, and Java (Jboss, Spring, Tomcat & Vertx), PHP (ZendServer & CodeIgniter), Ruby (ROR), Node.js, Python (Django & Flask) plateforms.

For other language implementations, see the Wikipedia article for more information.

The RFC for Websockets : RFC6455

gitignore all files of extension in directory

Never tried it, but git help ignore suggests that if you put a .gitignore with *.js in /public/static, it will do what you want.

Note: make sure to also check out Joeys' answer below: if you want to ignore files in a specific subdirectory, then a local .gitignore is the right solution (locality is good). However if you need the same pattern to apply to your whole repo, then the ** solution is better.

How to have conditional elements and keep DRY with Facebook React's JSX?

Just to extend @Jack Allan answer with references to docs.

React basic (Quick Start) documentation suggests null in such case. However, Booleans, Null, and Undefined Are Ignored as well, mentioned in Advanced guide.

What's the difference between VARCHAR and CHAR?

CHAR :

  • Supports both Character & Numbers.
  • Supports 2000 characters.
  • Fixed Length.

VARCHAR :

  • Supports both Character & Numbers.
  • Supports 4000 characters.
  • Variable Length.

any comments......!!!!

git pull aborted with error filename too long

Open your.gitconfig file to add the longpaths property. So it will look like the following:

[core]
symlinks = false
autocrlf = true
longpaths = true

ImageMagick security policy 'PDF' blocking conversion

Works in Ubuntu 20.04

Add this line inside <policymap>

<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />

Comment these lines:

  <!--
  <policy domain="coder" rights="none" pattern="PS" />
  <policy domain="coder" rights="none" pattern="PS2" />
  <policy domain="coder" rights="none" pattern="PS3" />
  <policy domain="coder" rights="none" pattern="EPS" />
  <policy domain="coder" rights="none" pattern="PDF" />
  <policy domain="coder" rights="none" pattern="XPS" />
   -->

Correct way of using log4net (logger naming)

Instead of naming my invoking class, I started using the following:

private static readonly ILog log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);

In this way, I can use the same line of code in every class that uses log4net without having to remember to change code when I copy and paste. Alternatively, i could create a logging class, and have every other class inherit from my logging class.

Sleep/Wait command in Batch

You want to use timeout. timeout 10 will sleep 10 seconds

What can be the reasons of connection refused errors?

In Ubuntu, Try sudo ufw allow <port_number> to allow firewall access to both of your server and db.

How to avoid Number Format Exception in java?

As always, the Jakarta Commons have at least part of the answer :

NumberUtils.isNumber()

This can be used to check most whether a given String is a number. You still have to choose what to do in case your String isnt a number ...

How to set a timeout on a http.request() in Node?

Just to clarify the answer above:

Now it is possible to use timeout option and the corresponding request event:

// set the desired timeout in options
const options = {
    //...
    timeout: 3000,
};

// create a request
const request = http.request(options, response => {
    // your callback here
});

// use its "timeout" event to abort the request
request.on('timeout', () => {
    request.abort();
});

PIL image to array (numpy array to array) - Python

I highly recommend you use the tobytes function of the Image object. After some timing checks this is much more efficient.

def jpg_image_to_array(image_path):
  """
  Loads JPEG image into 3D Numpy array of shape 
  (width, height, channels)
  """
  with Image.open(image_path) as image:         
    im_arr = np.fromstring(image.tobytes(), dtype=np.uint8)
    im_arr = im_arr.reshape((image.size[1], image.size[0], 3))                                   
  return im_arr

The timings I ran on my laptop show

In [76]: %timeit np.fromstring(im.tobytes(), dtype=np.uint8)
1000 loops, best of 3: 230 µs per loop

In [77]: %timeit np.array(im.getdata(), dtype=np.uint8)
10 loops, best of 3: 114 ms per loop

```

How to fix Python indentation

Try Emacs. It has good support for indentation needed in Python. Please check this link http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm

Redirect form to different URL based on select option element

Just use a onchnage Event for select box.

<select id="selectbox" name="" onchange="javascript:location.href = this.value;">
    <option value="https://www.yahoo.com/" selected>Option1</option>
    <option value="https://www.google.co.in/">Option2</option>
    <option value="https://www.gmail.com/">Option3</option>

</select>

And if selected option to be loaded at the page load then add some javascript code

<script type="text/javascript">
    window.onload = function(){
        location.href=document.getElementById("selectbox").value;
    }       
</script>

for jQuery: Remove the onchange event from <select> tag

jQuery(function () {
    // remove the below comment in case you need chnage on document ready
    // location.href=jQuery("#selectbox").val(); 
    jQuery("#selectbox").change(function () {
        location.href = jQuery(this).val();
    })
})

JavaScript: How do I print a message to the error console?

To answer your question you can use ES6 features,

var var=10;
console.log(`var=${var}`);

Check if a class `active` exist on element with jquery

Pure JavaScript answer:

document.querySelector('.menu').classList.contains('active');

Might help someone someday.

Making a Bootstrap table column fit to content

Add w-auto native bootstrap 4 class to the table element and your table will fit its content.

enter image description here

An ASP.NET setting has been detected that does not apply in Integrated managed pipeline mode

Below step solved my issue:

Open CMD Prompt with Admin Privileges.

Run : iisreset.

Hope this helps.

Add new field to every document in a MongoDB collection

Same as the updating existing collection field, $set will add a new fields if the specified field does not exist.

Check out this example:

> db.foo.find()
> db.foo.insert({"test":"a"})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> item = db.foo.findOne()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "test" : "a" }
> db.foo.update({"_id" :ObjectId("4e93037bbf6f1dd3a0a9541a") },{$set : {"new_field":1}})
> db.foo.find()
{ "_id" : ObjectId("4e93037bbf6f1dd3a0a9541a"), "new_field" : 1, "test" : "a" }

EDIT:

In case you want to add a new_field to all your collection, you have to use empty selector, and set multi flag to true (last param) to update all the documents

db.your_collection.update(
  {},
  { $set: {"new_field": 1} },
  false,
  true
)

EDIT:

In the above example last 2 fields false, true specifies the upsert and multi flags.

Upsert: If set to true, creates a new document when no document matches the query criteria.

Multi: If set to true, updates multiple documents that meet the query criteria. If set to false, updates one document.

This is for Mongo versions prior to 2.2. For latest versions the query is changed a bit

db.your_collection.update({},
                          {$set : {"new_field":1}},
                          {upsert:false,
                          multi:true}) 

JavaScript: Create and destroy class instance through class method

You can only manually delete properties of objects. Thus:

var container = {};

container.instance = new class();

delete container.instance;

However, this won't work on any other pointers. Therefore:

var container = {};

container.instance = new class();

var pointer = container.instance;

delete pointer; // false ( ie attempt to delete failed )

Furthermore:

delete container.instance; // true ( ie attempt to delete succeeded, but... )

pointer; // class { destroy: function(){} }

So in practice, deletion is only useful for removing object properties themselves, and is not a reliable method for removing the code they point to from memory.

A manually specified destroy method could unbind any event listeners. Something like:

function class(){
  this.properties = { /**/ }

  function handler(){ /**/ }

  something.addEventListener( 'event', handler, false );

  this.destroy = function(){
    something.removeEventListener( 'event', handler );
  }
}

PHP Get name of current directory

To get the names of current directory we can use getcwd() or dirname(__FILE__) but getcwd() and dirname(__FILE__) are not synonymous. They do exactly what their names are. If your code is running by referring a class in another file which exists in some other directory then these both methods will return different results.

For example if I am calling a class, from where these two functions are invoked and the class exists in some /controller/goodclass.php from /index.php then getcwd() will return '/ and dirname(__FILE__) will return /controller.

How to get max value of a column using Entity Framework?

Maybe help, if you want to add some filter:

context.Persons
.Where(c => c.state == myState)
.Select(c => c.age)
.DefaultIfEmpty(0)
.Max();

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

Using imagemagick, you can try:

convert page.png page.pdf

Or for multiple images:

convert page*.png mydoc.pdf

How can I add a background thread to flask?

Your additional threads must be initiated from the same app that is called by the WSGI server.

The example below creates a background thread that executes every 5 seconds and manipulates data structures that are also available to Flask routed functions.

import threading
import atexit
from flask import Flask

POOL_TIME = 5 #Seconds

# variables that are accessible from anywhere
commonDataStruct = {}
# lock to control access to variable
dataLock = threading.Lock()
# thread handler
yourThread = threading.Thread()

def create_app():
    app = Flask(__name__)

    def interrupt():
        global yourThread
        yourThread.cancel()

    def doStuff():
        global commonDataStruct
        global yourThread
        with dataLock:
        # Do your stuff with commonDataStruct Here

        # Set the next thread to happen
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()   

    def doStuffStart():
        # Do initialisation stuff here
        global yourThread
        # Create your thread
        yourThread = threading.Timer(POOL_TIME, doStuff, ())
        yourThread.start()

    # Initiate
    doStuffStart()
    # When you kill Flask (SIGTERM), clear the trigger for the next thread
    atexit.register(interrupt)
    return app

app = create_app()          

Call it from Gunicorn with something like this:

gunicorn -b 0.0.0.0:5000 --log-config log.conf --pid=app.pid myfile:app

Unsupported operation :not writeable python

file = open('ValidEmails.txt','wb')
file.write(email.encode('utf-8', 'ignore'))

This is solve your encode error also.

How to install multiple python packages at once using pip

You can use the following steps:

Step 1: Create a requirements.txt with list of packages to be installed. If you want to copy packages in a particular environment, do this

pip freeze >> requirements.txt

else store package names in a file named requirements.txt

Step 2: Execute pip command with this file

pip install -r requirements.txt

How to convert timestamp to datetime in MySQL?

Use the FROM_UNIXTIME() function in MySQL

Remember that if you are using a framework that stores it in milliseconds (for example Java's timestamp) you have to divide by 1000 to obtain the right Unix time in seconds.

How to move/rename a file using an Ansible task on a remote system

- name: Move the src file to dest
  command: mv /path/to/src /path/to/dest
  args:
    removes: /path/to/src
    creates: /path/to/dest

This runs the mv command only when /path/to/src exists and /path/to/dest does not, so it runs once per host, moves the file, then doesn't run again.

I use this method when I need to move a file or directory on several hundred hosts, many of which may be powered off at any given time. It's idempotent and safe to leave in a playbook.

Plot two histograms on single chart with matplotlib

Here is a simple method to plot two histograms, with their bars side-by-side, on the same plot when the data has different sizes:

def plotHistogram(p, o):
    """
    p and o are iterables with the values you want to 
    plot the histogram of
    """
    plt.hist([p, o], color=['g','r'], alpha=0.8, bins=50)
    plt.show()

UIView background color in Swift

I see that this question is solved, but, I want to add some information than can help someone.

if you want use hex to set background color, I found this function and work:

func UIColorFromHex(rgbValue:UInt32, alpha:Double=1.0)->UIColor {
    let red = CGFloat((rgbValue & 0xFF0000) >> 16)/256.0
    let green = CGFloat((rgbValue & 0xFF00) >> 8)/256.0
    let blue = CGFloat(rgbValue & 0xFF)/256.0

    return UIColor(red:red, green:green, blue:blue, alpha:CGFloat(alpha))
}

I use this function as follows:

view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)

some times you must use self:

self.view.backgroundColor = UIColorFromHex(0x323232,alpha: 1)

Well that was it, I hope it helps someone .

sorry for my bad english.

this work on iOS 7.1+

CryptographicException 'Keyset does not exist', but only through WCF

This is the only solution worked for me.

    // creates the CspParameters object and sets the key container name used to store the RSA key pair
    CspParameters cp = new CspParameters();
    cp.KeyContainerName = "MyKeyContainerName"; //Eg: Friendly name

    // instantiates the rsa instance accessing the key container MyKeyContainerName
    RSACryptoServiceProvider rsa = new RSACryptoServiceProvider(cp);
    // add the below line to delete the key entry in MyKeyContainerName
    // rsa.PersistKeyInCsp = false;

    //writes out the current key pair used in the rsa instance
    Console.WriteLine("Key is : \n" + rsa.ToXmlString(true));

Reference 1

Reference 2

How to convert an int to string in C?

EDIT: As pointed out in the comment, itoa() is not a standard, so better use sprintf() approach suggested in the rivaling answer!


You can use itoa() function to convert your integer value to a string.

Here is an example:

int num = 321;
char snum[5];

// convert 123 to string [buf]
itoa(num, snum, 10);

// print our string
printf("%s\n", snum);

If you want to output your structure into a file there is no need to convert any value beforehand. You can just use the printf format specification to indicate how to output your values and use any of the operators from printf family to output your data.

SQL Bulk Insert with FIRSTROW parameter skips the following line

Given how mangled some data can look after BCP importing into SQL Server from non-SQL data sources, I'd suggest doing all the BCP import into some scratch tables first.

For example

truncate table Address_Import_tbl

BULK INSERT dbo.Address_Import_tbl FROM 'E:\external\SomeDataSource\Address.csv' WITH ( FIELDTERMINATOR = '|', ROWTERMINATOR = '\n', MAXERRORS = 10 )

Make sure all the columns in Address_Import_tbl are nvarchar(), to make it as agnostic as possible, and avoid type conversion errors.

Then apply whatever fixes you need to Address_Import_tbl. Like deleting the unwanted header.

Then run a INSERT SELECT query, to copy from Address_Import_tbl to Address_tbl, along with any datatype conversions you need. For example, to cast imported dates to SQL DATETIME.

jQuery or JavaScript auto click

$(document).ready(function(){
   $('.lbOn').click();
});

Suppose this would work too.

Adb install failure: INSTALL_CANCELED_BY_USER

For Mi or Xiaomi Device

1) Setting

2) Additional Setting

3) Developer option

4) Install via USB: Toggle On

It is working fine for me.

Note: Not working then try following options also

1) Sign to MI account (Not applicable to all devices)

2) Also Disable Turn on MIUI optimization: Setting -> Additional Setting -> Developer Option, near bottom we will get this option.

3) Developer option must be enabled and Link for enabling developer option: Description here

Still not working?

-> signed out from Mi Account and then created new account and enable USB Debugging.

Thanks

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

jQuery Scroll to bottom of page/iframe

If you want a nice slow animation scroll, for any anchor with href="#bottom" this will scroll you to the bottom:

$("a[href='#bottom']").click(function() {
  $("html, body").animate({ scrollTop: $(document).height() }, "slow");
  return false;
});

Feel free to change the selector.

Converting double to integer in Java

Double perValue = 96.57;
int roundVal= (int) Math.round(perValue);

Solved my purpose.

Easy way of running the same junit test over and over?

In JUnit 5 it is much simpler by using @RepeatedTest

@RepeatedTest is used to signal that the annotated method is a test template method that should be repeated a specified number of times.

    @RepeatedTest(3) // Runs N Times
    public void test_Prime() {
    }

More info on www.baeldung.com

C#: Printing all properties of an object

You can use the TypeDescriptor class to do this:

foreach(PropertyDescriptor descriptor in TypeDescriptor.GetProperties(obj))
{
    string name=descriptor.Name;
    object value=descriptor.GetValue(obj);
    Console.WriteLine("{0}={1}",name,value);
}

TypeDescriptor lives in the System.ComponentModel namespace and is the API that Visual Studio uses to display your object in its property browser. It's ultimately based on reflection (as any solution would be), but it provides a pretty good level of abstraction from the reflection API.

How to check empty DataTable

First make sure that DataTable is not null and than check for the row count

if(dt!=null)
{
  if(dt.Rows.Count>0)
  {
    //do your code 
  }
}

What's a simple way to get a text input popup dialog box on an iPhone

Building on John Riselvato's answer, to retrieve the string back from the UIAlertView...

alert.addAction(UIAlertAction(title: "Submit", style: UIAlertAction.Style.default) { (action : UIAlertAction) in
            guard let message = alert.textFields?.first?.text else {
                return
            }
            // Text Field Response Handling Here
        })

How to get Time from DateTime format in SQL?

I often use this script to get Time from DateTime:

SELECT CONVERT(VARCHAR(9),RIGHT(YOURCOLUMN_DATETIME,9),108) FROM YOURTABLE