Programs & Examples On #Custom sections

Link to the issue number on GitHub within a commit message

If you want to link to a GitHub issue and close the issue, you can provide the following lines in your Git commit message:

Closes #1.
Closes GH-1.
Closes gh-1.

(Any of the three will work.) Note that this will link to the issue and also close it. You can find out more in this blog post (start watching the embedded video at about 1:40).

I'm not sure if a similar syntax will simply link to an issue without closing it.

Check if a string is html or not

Using jQuery in this case, the simplest form would be:

if ($(testString).length > 0)

If $(testString).length = 1, this means that there is one HTML tag inside textStging.

How to check db2 version

You can query for the built-in session variables with SQL. To identify the version of DB2 on z/OS, you need the SYSIBM.VERSION variable. This will return the PRDID - the product identifier. You can look up the human-readable version in the Knowledge Center.

SELECT GETVARIABLE('SYSIBM.VERSION')
FROM SYSIBM.SYSDUMMY1;

-- for example, the above returns DSN10015
-- DSN10015 identifies DB2 10 in new-function mode (see second link above)

Python conditional assignment operator

(can't comment or I would just do that) I believe the suggestion to check locals above is not quite right. It should be:

foo = foo if 'foo' in locals() or 'foo' in globals() else 'default'

to be correct in all contexts.

However, despite its upvotes, I don't think even that is a good analog to the Ruby operator. Since the Ruby operator allows more than just a simple name on the left:

foo[12] ||= something
foo.bar ||= something

The exception method is probably closest analog.

Show and hide a View with a slide up/down animation

Here is my solution. Just get a reference to your view and call this method:

public static void animateViewFromBottomToTop(final View view){

    view.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

        @Override
        public void onGlobalLayout() {

            view.getViewTreeObserver().removeOnGlobalLayoutListener(this);

            final int TRANSLATION_Y = view.getHeight();
            view.setTranslationY(TRANSLATION_Y);
            view.setVisibility(View.GONE);
            view.animate()
                .translationYBy(-TRANSLATION_Y)
                .setDuration(500)
                .setStartDelay(200)
                .setListener(new AnimatorListenerAdapter() {

                    @Override
                    public void onAnimationStart(final Animator animation) {

                        view.setVisibility(View.VISIBLE);
                    }
                })
                .start();
        }
    });
}

No need to do anything else =)

How to set a Timer in Java?

Ok, I think I understand your problem now. You can use a Future to try to do something and then timeout after a bit if nothing has happened.

E.g.:

FutureTask<Void> task = new FutureTask<Void>(new Callable<Void>() {
  @Override
  public Void call() throws Exception {
    // Do DB stuff
    return null;
  }
});

Executor executor = Executors.newSingleThreadScheduledExecutor();
executor.execute(task);

try {
  task.get(5, TimeUnit.SECONDS);
}
catch(Exception ex) {
  // Handle your exception
}

How to get index in Handlebars each helper?

In the newer versions of Handlebars index (or key in the case of object iteration) is provided by default with the standard each helper.


snippet from : https://github.com/wycats/handlebars.js/issues/250#issuecomment-9514811

The index of the current array item has been available for some time now via @index:

{{#each array}}
    {{@index}}: {{this}}
{{/each}}

For object iteration, use @key instead:

{{#each object}}
    {{@key}}: {{this}}
{{/each}} 

Adding class to element using Angular JS

Use the MV* Pattern

Based on the example you attached, It's better in angular to use the following tools:

  • ng-click - evaluates the expression when the element is clicked (Read More)
  • ng-class - place a class based on the a given boolean expression (Read More)

for example:

<button ng-click="enabled=true">Click Me!</button>

<div ng-class="{'alpha':enabled}"> 
    ...
</div>

This gives you an easy way to decouple your implementation. e.g. you don't have any dependency between the div and the button.

Read this to learn about the MV* Pattern

Is it safe to store a JWT in localStorage with ReactJS?

Basically it's OK to store your JWT in your localStorage.

And I think this is a good way. If we are talking about XSS, XSS using CDN, it's also a potential risk of getting your client's login/pass as well. Storing data in local storage will prevent CSRF attacks at least.

You need to be aware of both and choose what you want. Both attacks it's not all you are need to be aware of, just remember: YOUR ENTIRE APP IS ONLY AS SECURE AS THE LEAST SECURE POINT OF YOUR APP.

Once again storing is OK, be vulnerable to XSS, CSRF,... isn't

Using floats with sprintf() in embedded C

use the %f modifier:

sprintf (str, "adc_read = %f\n", adc_read);

For instance:

#include <stdio.h>

int main (void) 
{
    float x = 2.5;
    char y[200];

    sprintf(y, "x = %f\n", x);
    printf(y);
    return 0;
}

Yields this:

x = 2.500000

How to list all installed packages and their versions in Python?

If you have pip install and you want to see what packages have been installed with your installer tools you can simply call this:

pip freeze

It will also include version numbers for the installed packages.

Update

pip has been updated to also produce the same output as pip freeze by calling:

pip list

Note

The output from pip list is formatted differently, so if you have some shell script that parses the output (maybe to grab the version number) of freeze and want to change your script to call list, you'll need to change your parsing code.

How do I find the current machine's full hostname in C (hostname and domain information)?

To get a fully qualified name for a machine, we must first get the local hostname, and then lookup the canonical name.

The easiest way to do this is by first getting the local hostname using uname() or gethostname() and then performing a lookup with gethostbyname() and looking at the h_name member of the struct it returns. If you are using ANSI c, you must use uname() instead of gethostname().

Example:

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);
printf("Hostname: %s\n", hostname);
struct hostent* h;
h = gethostbyname(hostname);
printf("h_name: %s\n", h->h_name);

Unfortunately, gethostbyname() is deprecated in the current POSIX specification, as it doesn't play well with IPv6. A more modern version of this code would use getaddrinfo().

Example:

struct addrinfo hints, *info, *p;
int gai_result;

char hostname[1024];
hostname[1023] = '\0';
gethostname(hostname, 1023);

memset(&hints, 0, sizeof hints);
hints.ai_family = AF_UNSPEC; /*either IPV4 or IPV6*/
hints.ai_socktype = SOCK_STREAM;
hints.ai_flags = AI_CANONNAME;

if ((gai_result = getaddrinfo(hostname, "http", &hints, &info)) != 0) {
    fprintf(stderr, "getaddrinfo: %s\n", gai_strerror(gai_result));
    exit(1);
}

for(p = info; p != NULL; p = p->ai_next) {
    printf("hostname: %s\n", p->ai_canonname);
}

freeaddrinfo(info);

Of course, this will only work if the machine has a FQDN to give - if not, the result of the getaddrinfo() ends up being the same as the unqualified hostname.

Why do table names in SQL Server start with "dbo"?

It's new to SQL 2005 and offers a simplified way to group objects, especially for the purpose of securing the objects in that "group".

The following link offers a more in depth explanation as to what it is, why we would use it:

Understanding the Difference between Owners and Schemas in SQL Server

Form Submit jQuery does not work

According to http://api.jquery.com/submit/

The submit event is sent to an element when the user is attempting to submit a form. It can only be attached to elements. Forms can be submitted either by clicking an explicit <input type="submit">, <input type="image">, or <button type="submit">, or by pressing Enter when certain form elements have focus.

So basically, .submit is a binding function, to submit the form you can use simple Javascript:

document.formName.submit().

Google Play Services Library update and missing symbol @integer/google_play_services_version

after the update to the last versión i had this problem with all my projects, but it was solved just adding again the library reference:

if you don´t have the library into your workspace in Eclipse you can add it with: File -> Import -> Existing Android Code Into Workspace -> browse and navigate to google-play-services_lib project lib, (android-sdk/extras/google/google_play_services/libproject).

enter image description here

then deleting /bin and /gen folders of my project (something similar to the clean option) and building my project again.

How would you count occurrences of a string (actually a char) within a string?

string s = "HOWLYH THIS ACTUALLY WORKSH WOWH";
int count = 0;
for (int i = 0; i < s.Length; i++)
   if (s[i] == 'H') count++;

It just checks every character in the string, if the character is the character you are searching for, add one to count.

What does void do in java?

When the return type is void, your method doesn't return anything.

Look again at your code: There's no return in that method. You print to the console and exit.

MongoDB: exception in initAndListen: 20 Attempted to create a lock file on a read-only directory: /data/db, terminating

If your system is using SELinux, make sure that you use the right context for the directory you created:

ls -dZ /data/db/
ls -dZ /var/lib/mongo/

and clone the context with:

chcon -R --reference=/var/lib/mongo /data/db

laravel Unable to prepare route ... for serialization. Uses Closure

The Actual solution of this problem is changing first line in web.php

Just replace Welcome route with following route

Route::view('/', 'welcome');

If still getting same error than you probab

Best way to remove items from a collection

To do this while looping through the collection and not to get the modifying a collection exception, this is the approach I've taken in the past (note the .ToList() at the end of the original collection, this creates another collection in memory, then you can modify the existing collection)

foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments.ToList())
{
    if (spAssignment.Member.Name == shortName)
    {
        workspace.RoleAssignments.Remove(spAssignment);
    }
}

How to get the first five character of a String

Just a heads up there is a new way to do this in C# 8.0: Range operators

Microsoft Docs

Or as I like to call em, Pandas slices.

Old way:

string newString = oldstring.Substring(0, 5);

New way:

string newString = oldstring[..5];

Which at first glance appears like a pretty bad tradeoff of some readability for shorter code but the new feature gives you

  1. a standard syntax for slicing arrays (and therefore strings)
  2. cool stuff like this:

    var slice1 = list[2..^3]; // list[Range.Create(2, Index.CreateFromEnd(3))]

    var slice2 = list[..^3]; // list[Range.ToEnd(Index.CreateFromEnd(3))]

    var slice3 = list[2..]; // list[Range.FromStart(2)]

    var slice4 = list[..]; // list[Range.All]

Rails 4 image-path, image-url and asset-url no longer work in SCSS files

I had a similar problem, trying to add a background image with inline css. No need to specify the images folder due to the way asset sync works.

This worked for me:

background-image: url('/assets/image.jpg');

DataGridView changing cell background color

You can use the VisibleChanged event handler.

private void DataGridView1_VisibleChanged(object sender, System.EventArgs e)
{
    var grid = sender as DataGridView;
    grid.Rows[0].Cells[0].Style.BackColor = Color.Yellow;
}

Is it possible to set UIView border properties from interface builder?

For Swift 3 and 4, if you're willing to use IBInspectables, there's this:

@IBDesignable extension UIView {
    @IBInspectable var borderColor:UIColor? {
        set {
            layer.borderColor = newValue!.cgColor
        }
        get {
            if let color = layer.borderColor {
                return UIColor(cgColor: color)
            }
            else {
                return nil
            }
        }
    }
    @IBInspectable var borderWidth:CGFloat {
        set {
            layer.borderWidth = newValue
        }
        get {
            return layer.borderWidth
        }
    }
    @IBInspectable var cornerRadius:CGFloat {
        set {
            layer.cornerRadius = newValue
            clipsToBounds = newValue > 0
        }
        get {
            return layer.cornerRadius
        }
    }
}

Android device is not connected to USB for debugging (Android studio)

I had tried restart the device, and it's work, popup and ask want to trust the mac for debug mode.

Get class name using jQuery

Direct way

myid.className

_x000D_
_x000D_
console.log( myid.className )
_x000D_
<div id="myid" class="myclass"></div>
_x000D_
_x000D_
_x000D_

How to check if the key pressed was an arrow key in Java KeyListener?

If you mean that you wanna attach this to your panel (Window that you are working with).

then you have to create an inner class that extend from IKeyListener interface and then add that method in to the class.

Then, attach that class to you panel by: this.addKeyListener(new subclass());

Could not resolve placeholder in string value

I got the same error in my microservice project.The property itself missed in my yml file.So I added property name and value that resolves my problem

What is null in Java?

There are two major categories of types in Java: primitive and reference. Variables declared of a primitive type store values; variables declared of a reference type store references.

String x = null;

In this case, the initialization statement declares a variables “x”. “x” stores String reference. It is null here. First of all, null is not a valid object instance, so there is no memory allocated for it. It is simply a value that indicates that the object reference is not currently referring to an object.

How to read a file from jar in Java?

Check first your class loader.

ClassLoader classLoader = Thread.currentThread().getContextClassLoader();

if (classLoader == null) {
    classLoader = Class.class.getClassLoader();
}

classLoader.getResourceAsStream("xmlFileNameInJarFile.xml");

// xml file location at xxx.jar
// + folder
// + folder
// xmlFileNameInJarFile.xml

UML diagram shapes missing on Visio 2013

CTRL+N-- to open a new document.

Right Edge find "MORE SHAPES" then "SOFTWARES AND DATABASES" and finaly "SOFTWARES". All UML DIAGRAMS are available here.

InputStream from a URL

Here is a full example which reads the contents of the given web page. The web page is read from an HTML form. We use standard InputStream classes, but it could be done more easily with JSoup library.

<dependency>
    <groupId>javax.servlet</groupId>
    <artifactId>javax.servlet-api</artifactId>
    <version>3.1.0</version>
    <scope>provided</scope>

</dependency>

<dependency>
    <groupId>commons-validator</groupId>
    <artifactId>commons-validator</artifactId>
    <version>1.6</version>
</dependency>  

These are the Maven dependencies. We use Apache Commons library to validate URL strings.

package com.zetcode.web;

import com.zetcode.service.WebPageReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet(name = "ReadWebPage", urlPatterns = {"/ReadWebPage"})
public class ReadWebpage extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        response.setContentType("text/plain;charset=UTF-8");

        String page = request.getParameter("webpage");

        String content = new WebPageReader().setWebPageName(page).getWebPageContent();

        ServletOutputStream os = response.getOutputStream();
        os.write(content.getBytes(StandardCharsets.UTF_8));
    }
}

The ReadWebPage servlet reads the contents of the given web page and sends it back to the client in plain text format. The task of reading the page is delegated to WebPageReader.

package com.zetcode.service;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.stream.Collectors;
import org.apache.commons.validator.routines.UrlValidator;

public class WebPageReader {

    private String webpage;
    private String content;

    public WebPageReader setWebPageName(String name) {

        webpage = name;
        return this;
    }

    public String getWebPageContent() {

        try {

            boolean valid = validateUrl(webpage);

            if (!valid) {

                content = "Invalid URL; use http(s)://www.example.com format";
                return content;
            }

            URL url = new URL(webpage);

            try (InputStream is = url.openStream();
                    BufferedReader br = new BufferedReader(
                            new InputStreamReader(is, StandardCharsets.UTF_8))) {

                content = br.lines().collect(
                      Collectors.joining(System.lineSeparator()));
            }

        } catch (IOException ex) {

            content = String.format("Cannot read webpage %s", ex);
            Logger.getLogger(WebPageReader.class.getName()).log(Level.SEVERE, null, ex);
        }

        return content;
    }

    private boolean validateUrl(String webpage) {

        UrlValidator urlValidator = new UrlValidator();

        return urlValidator.isValid(webpage);
    }
}

WebPageReader validates the URL and reads the contents of the web page. It returns a string containing the HTML code of the page.

<!DOCTYPE html>
<html>
    <head>
        <title>Home page</title>
        <meta charset="UTF-8">
    </head>
    <body>
        <form action="ReadWebPage">

            <label for="page">Enter a web page name:</label>
            <input  type="text" id="page" name="webpage">

            <button type="submit">Submit</button>

        </form>
    </body>
</html>

Finally, this is the home page containing the HTML form. This is taken from my tutorial about this topic.

VMWare Player vs VMWare Workstation

Workstation has some features that Player lacks, such as teams (groups of VMs connected by private LAN segments) and multi-level snapshot trees. It's aimed at power users and developers; they even have some hooks for using a debugger on the host to debug code in the VM (including kernel-level stuff). The core technology is the same, though.

How to use google maps without api key

You can still use free with iframe in google maps share button for example enter image description here

The SELECT permission was denied on the object 'Users', database 'XXX', schema 'dbo'

I resolve my problem doing this. [IMPORTANT NOTE: It allows escalated (expanded) privileges to the particular account, possibly more than are needed for individual scenario].

  1. Go to 'Object Explorer' of SQL Management Studio.
  2. Expand Security, then Login.
  3. Select the user you are working with, then right click and select Properties Windows.
  4. In Select a Page, Go to Server Roles
  5. Click on sysadmin and save.

CMD what does /im (taskkill)?

it allows you to kill a task based on the image name like taskkill /im iexplore.exe or taskkill /im notepad.exe

How do I make a list of data frames?

You can also access specific columns and values in each list element with [ and [[. Here are a couple of examples. First, we can access only the first column of each data frame in the list with lapply(ldf, "[", 1), where 1 signifies the column number.

ldf <- list(d1 = d1, d2 = d2)  ## create a named list of your data frames
lapply(ldf, "[", 1)
# $d1
#   y1
# 1  1
# 2  2
# 3  3
#
# $d2
#   y1
# 1  3
# 2  2
# 3  1

Similarly, we can access the first value in the second column with

lapply(ldf, "[", 1, 2)
# $d1
# [1] 4
# 
# $d2
# [1] 6

Then we can also access the column values directly, as a vector, with [[

lapply(ldf, "[[", 1)
# $d1
# [1] 1 2 3
#
# $d2
# [1] 3 2 1

Difference between frontend, backend, and middleware in web development

Here is one breakdown:

Front-end tier -> User Interface layer usually consisting of a mix of HTML, Javascript, CSS, Flash, and various server-side code like ASP.Net, classic ASP, PHP, etc. Think of this as being closest to the user in terms of code.

Middleware, middle-tier -> One tier back, generally referred to as the "plumbing" part of a system. Java and C# are common languages for writing this part that could be viewed as the glue between the UI and the data and can be webservices or WCF components or other SOA components possibly.

Back-end tier -> Databases and other data stores are generally at this level. Oracle, MS-SQL, MySQL, SAP, and various off-the-shelf pieces of software come to mind for this piece of software that is the final processing of the data.

Overlap can exist between any of these as you could have everything poured into one layer like an ASP.Net website that uses the built-in AJAX functionality that generates Javascript while the code behind may contain database commands making the code behind contain both middle and back-end tiers. Alternatively, one could use VBScript to act as all the layers using ADO objects and merging all three tiers into one.

Similarly, taking middleware and either front or back-end can be combined in some cases.

Bottlenecks generally have a few different levels to them:

1) Database or back-end processing -> This can vary from payroll or sales or other tasks where the throughput to the database is bogging things down.

2) Middleware bottlenecks -> This would be where some web service may be hitting capacity but the front and back ends have bandwidth to handle more traffic. Alternatively, there may be some server that is part of a system that isn't quite the UI part or the raw data that can be a bottleneck using something like Biztalk or MSMQ.

3) Front-end bottlenecks -> This could client or server-side issues. For example, if you took a low-end PC and had it load a web page that consisted of a lot of data being downloaded, the client could be where the bottleneck is. Similarly, the server could be queuing up requests if it is getting hammered with requests like what Amazon.com or other high-traffic websites may get at times.

Some of this is subject to interpretation, so it isn't perfect by any means and YMMV.


EDIT: Something to consider is that some systems can have multiple front-ends or back-ends. For example, a content management system will likely have a way for site visitors to view the content that is a front-end but what about how content editors are able to change the data on the site? The ability to pull up this data could be seen as front-end since it is a UI component or it could be seen as a back-end since it is used by internal users rather than the general public viewing the site. Thus, there is something to be said for context here.

Finding moving average from data points in Python

ravgs = [sum(data[i:i+5])/5. for i in range(len(data)-4)]

This isn't the most efficient approach but it will give your answer and I'm unclear if your window is 5 points or 10. If its 10, replace each 5 with 10 and the 4 with 9.

How to concatenate properties from multiple JavaScript objects

Simplest: spread operators

var obj1 = {a: 1}
var obj2 = {b: 2}
var concat = { ...obj1, ...obj2 } // { a: 1, b: 2 }

Updating a local repository with changes from a GitHub repository

With an already-set origin master, you just have to use the below command -

git pull "https://github.com/yourUserName/yourRepo.git"

Finding rows that don't contain numeric data in Oracle

enter image description hereI tray order by with problematic column and i find rows with column.

SELECT 
 D.UNIT_CODE,
         D.CUATM,
         D.CAPITOL,
          D.RIND,
          D.COL1  AS COL1


FROM
  VW_DATA_ALL_GC  D
  
  WHERE
  
   (D.PERIOADA IN (:pPERIOADA))  AND   
   (D.FORM = 62) 
   AND D.COL1 IS NOT NULL
 --  AND REGEXP_LIKE (D.COL1, '\[\[:alpha:\]\]')
 
-- AND REGEXP_LIKE(D.COL1, '\[\[:digit:\]\]')
 
 --AND REGEXP_LIKE(TO_CHAR(D.COL1), '\[^0-9\]+')
 
 
   GROUP BY 
    D.UNIT_CODE,
         D.CUATM,
         D.CAPITOL,
          D.RIND ,
          D.COL1  
         
         
        ORDER BY 
        D.COL1

Rewrite URL after redirecting 404 error htaccess

In your .htaccess file , if you are using apache you can try with

Rule for Error Page - 404

ErrorDocument 404 http://www.domain.com/notFound.html

PHP Multiple Checkbox Array

<form method='post' id='userform' action='thisform.php'> <tr>
    <td>Trouble Type</td>
    <td>
    <input type='checkbox' name='checkboxvar[]' value='Option One'>1<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Two'>2<br>
    <input type='checkbox' name='checkboxvar[]' value='Option Three'>3
    </td> </tr> </table> <input type='submit' class='buttons'> </form>

<?php 
if (isset($_POST['checkboxvar'])) 
{
    print_r($_POST['checkboxvar']); 
}
?>

You pass the form name as an array and then you can access all checked boxes using the var itself which would then be an array.

To echo checked options into your email you would then do this:

echo implode(',', $_POST['checkboxvar']); // change the comma to whatever separator you want

Please keep in mind you should always sanitize your input as needed.

For the record, official docs on this exist: http://php.net/manual/en/faq.html.php#faq.html.arrays

Getting index value on razor foreach

All of the above answers require logic in the view. Views should be dumb and contain as little logic as possible. Why not create properties in your view model that correspond to position in the list eg:

public int Position {get; set}

In your view model builder you set the position 1 through 4.

BUT .. there is even a cleaner way. Why not make the CSS class a property of your view model? So instead of the switch statement in your partial, you would just do this:

<div class="@Model.GridCSS">

Move the switch statement to your view model builder and populate the CSS class there.

Android: TextView: Remove spacing and padding on top and bottom

This annoyed me too, and the answer I found was that there is actually additional space in the font itself, not the TextView. It is rather irritating, coming from a document publishing background, the limited amount of control you have with Android over typographic elements. I'd recommend using a custom typeface (such as Bitstream Vera Sans, which is licensed for redistribution) that may not have this issue. I'm not sure specifically whether or not it does, though.

how can I enable PHP Extension intl?

For enable PHP Extension intl , follow the Steps..

  1. Open the xampp/php/php.ini file in any editor.
  2. Search ";extension=php_intl.dll"
  3. kindly remove the starting semicolon ( ; )

    Like :

    ;extension=php_intl.dll

    to

    extension=php_intl.dll

  4. Save the xampp/php/php.ini file.

  5. Restart your xampp/wamp

Hope its work..Cheers..

Converting rows into columns and columns into rows using R

Simply use the base transpose function t, wrapped with as.data.frame:

final_df <- as.data.frame(t(starting_df))
final_df
     A    B    C    D
a    1    2    3    4
b 0.02 0.04 0.06 0.08
c Aaaa Bbbb Cccc Dddd

Above updated. As docendo discimus pointed out, t returns a matrix. As Mark suggested wrapping it with as.data.frame gets back a data frame instead of a matrix. Thanks!

how can select from drop down menu and call javascript function

<script type="text/javascript">
function report(func)
{
    func();
}

function daily()
{
    alert('daily');
}

function monthly()
{
    alert('monthly');
}
</script>

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

Path.Combine absolute with relative path strings


Path.GetFullPath(@"c:\windows\temp\..\system32")?

Mercurial stuck "waiting for lock"

I do not expect this to be a winning answer, but it is a fairly unusual situation. Mentioning in case someone other than me runs into it.

Today I got the "waiting for lock on repository" on an hg push command.

When I killed the hung hg command I could see no .hg/store/lock

When I looked for .hg/store/lock while the command was hung, it existed. But the lockfile was deleted when the hg command was killed.

When I went to the target of the push, and executed hg pull, no problem.

Eventually I realized that the process ID on the hg push was lock waiting message was changing each time. It turns out that the "hg push" was hanging waiting for a lock held by itself (or possibly a subprocess, I did not investigate further).

It turns out that the two workspaces, let's call them A and B, had .hg trees shared by symlink:

A/.hg --symlinked-to--> B/.hg

This is NOT a good thing to do with Mercurial. Mercurial does not understand the concept of two workspaces sharing the same repository. I do understand, however, how somebody coming to Mercurial from another VCS might want this (Perforce does, although not a DVCS; the Bazaar DVCS reportedly can do so). I am surprised that a symlinked REP-ROOT/.hg works at all, although it seems to except for this push.

Mailx send html message

It's easy, if your mailx command supports the -a (append header) option:

$ mailx -a 'Content-Type: text/html' -s "my subject" [email protected] < email.html

If it doesn't, try using sendmail:

# create a header file
$ cat mailheader
To: [email protected]
Subject: my subject
Content-Type: text/html

# send
$ cat mailheader email.html | sendmail -t

How to Create an excel dropdown list that displays text with a numeric hidden value

There are two types of drop down lists available (I am not sure since which version).

ActiveX Drop Down
You can set the column widths, so your hidden column can be set to 0.

Form Drop Down
You could set the drop down range to a hidden sheet and reference the cell adjacent to the selected item. This would also work with the ActiveX type control.

Where to change default pdf page width and font size in jspdf.debug.js?

For anyone trying to this in react. There is a slight difference.

// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);

or

// Document of 8.5 inch width and 11 inch high
new jsPDF({
        orientation: 'p', 
        unit: 'in', 
        format: [612, 792]
});

When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].

Convert base64 string to ArrayBuffer

Goran.it's answer does not work because of unicode problem in javascript - https://developer.mozilla.org/en-US/docs/Web/API/WindowBase64/Base64_encoding_and_decoding.

I ended up using the function given on Daniel Guerrero's blog: http://blog.danguer.com/2011/10/24/base64-binary-decoding-in-javascript/

Function is listed on github link: https://github.com/danguer/blog-examples/blob/master/js/base64-binary.js

Use these lines

var uintArray = Base64Binary.decode(base64_string);  
var byteArray = Base64Binary.decodeArrayBuffer(base64_string); 

How to get a dependency tree for an artifact?

If you bother creating a sample project and adding your 3rd party dependency to that, then you can run the following in order to see the full hierarchy of the dependencies.

You can search for a specific artifact using this maven command:

mvn dependency:tree -Dverbose -Dincludes=[groupId]:[artifactId]:[type]:[version]

According to the documentation:

where each pattern segment is optional and supports full and partial * wildcards. An empty pattern segment is treated as an implicit wildcard.

Imagine you are trying to find 'log4j-1.2-api' jar file among different modules of your project:

mvn dependency:tree -Dverbose -Dincludes=org.apache.logging.log4j:log4j-1.2-api

more information can be found here.

Edit: Please note that despite the advantages of using verbose parameter, it might not be so accurate in some conditions. Because it uses Maven 2 algorithm and may give wrong results when used with Maven 3.

How to insert data using wpdb

You have to check your quotes properly,

$sql = $wpdb->prepare(
    "INSERT INTO `wp_submitted_form`      
       (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
 values ($name, $email, $phone, $country, $course, $message, $datesent)");
$wpdb->query($sql);

OR you can use like,

$sql = "INSERT INTO `wp_submitted_form`
          (`name`,`email`,`phone`,`country`,`course`,`message`,`datesent`) 
   values ($name, $email, $phone, $country, $course, $message, $datesent)";

$wpdb->query($sql);

Read http://codex.wordpress.org/Class_Reference/wpdb

ListView with OnItemClickListener

lv.setOnItemClickListener( new OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView < ? > parent, View view,
                            int position, long id) {
        // TODO Auto-generated method stub

    }
} );

passing object by reference in C++

One thing that I have to add is that there is no reference in C.

Secondly, this is the language syntax convention. & - is an address operator but it also mean a reference - all depends on usa case

If there was some "reference" keyword instead of & you could write

int CDummy::isitme (reference CDummy param)

but this is C++ and we should accept it advantages and disadvantages...

How does a ArrayList's contains() method evaluate objects?

It uses the equals method on the objects. So unless Thing overrides equals and uses the variables stored in the objects for comparison, it will not return true on the contains() method.

Javascript Array of Functions

Or just:

var myFuncs = {
  firstFun: function(string) {
    // do something
  },

  secondFunc: function(string) {
    // do something
  },

  thirdFunc: function(string) {
    // do something
  }
}

Prevent the keyboard from displaying on activity start

Function to hide the keyboard.

public static void hideKeyboard(Activity activity) {
    View view = activity.getCurrentFocus();

    if (view != null) {
        InputMethodManager inputManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);

        inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
    }
}

Hide keyboard in AndroidManifext.xml file.

<activity
    android:name=".MainActivity"
    android:label="@string/app_name"
    android:theme="@style/AppTheme"
    android:windowSoftInputMode="stateHidden">

document.createElement("script") synchronously

This works for modern 'evergreen' browsers that support async/await and fetch.

This example is simplified, without error handling, to show the basic principals at work.

// This is a modern JS dependency fetcher - a "webpack" for the browser
const addDependentScripts = async function( scriptsToAdd ) {

  // Create an empty script element
  const s=document.createElement('script')

  // Fetch each script in turn, waiting until the source has arrived
  // before continuing to fetch the next.
  for ( var i = 0; i < scriptsToAdd.length; i++ ) {
    let r = await fetch( scriptsToAdd[i] )

    // Here we append the incoming javascript text to our script element.
    s.text += await r.text()
  }

  // Finally, add our new script element to the page. It's
  // during this operation that the new bundle of JS code 'goes live'.
  document.querySelector('body').appendChild(s)
}

// call our browser "webpack" bundler
addDependentScripts( [
  'https://code.jquery.com/jquery-3.5.1.slim.min.js',
  'https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js'
] )

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

A lot of answer to this questions but a few were helping. I want to give accurate and updated answer.

Gradle's dependency cache may be corrupt (this sometimes occurs after a network connection timeout.)

This error happens when you bad internet connection or you put your computer to sleep while Android Studio is downloading the required dependencies.

How to resolve this issue.

  1. Find out the project's Gradle version. You will find that in gradle-wrapper.properties in distributionUrl my gradle distribution was https\://services.gradle.org/distributions/gradle-6.5-all.zip that means gradle-6.5-all.zip is required to download and right now it is corrupted because of connection timeout. Lets find out this folder and delete this.
  2. Go to .gradle folder then to wrapper then to dists then find a folder that matches the gradle version name that required to download. In my case it was gradle-6.5-all.zip select this folder and delete it.
  3. Now sync the project and make sure you have good internet connection and setting that will prevent your system going to sleep while downloading something.

android fragment- How to save states of views in a fragment when another fragment is pushed on top of it

In fragment guide FragmentList example you can find:

@Override
public void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("curChoice", mCurCheckPosition);
}

Which you can use later like this:

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    if (savedInstanceState != null) {
        // Restore last state for checked position.
        mCurCheckPosition = savedInstanceState.getInt("curChoice", 0);
    }
}

I'm a beginner in Fragments but it seems like solution of your problem ;) OnActivityCreated is invoked after fragment returns from back stack.

Onclick on bootstrap button

Seem no solutions fix the problem:

$(".anima-area").on('click', function (e) {
            return false; //return true;
});
$(".anima-area").on('click', function (e) {
            e.preventDefault();
});
 $(".anima-area").click(function (r) {
           e.preventDefault();
});
$(".anima-area").click(function () {
           return false; //return true;
});

Bootstrap button always maintain th pressed status and block all .click code. If i remove .click function button comeback to work good.

What are the recommendations for html <base> tag?

Base href example

Say a typical page with links:

<a href=home>home</a> <a href=faq>faq</a> <a href=etc>etc</a>

.and links to a diff folder:

..<a href=../p2/home>Portal2home</a> <a href=../p2/faq>p2faq</a> <a href=../p2/etc>p2etc</a>..

With base href, we can avoid repeating the base folder:

<base href=../p2/>
<a href=home>Portal2-Home</a> <a href=faq>P2FAQ</a> <a href=contact>P2Contact</a>

So that's a win.. yet pages too-often contain urls to diff bases And the current web supports only one base href per page, so the win is quickly lost as bases that aint base∙hrefed repeats, eg:

<a href=../p1/home>home</a> <a href=../p1/faq>faq</a> <a href=../p1/etc>etc</a>
<!--.. <../p1/> basepath is repeated -->

<base href=../p2>
<a href=home>Portal2-Home</a> <a href=faq>P2FAQ</a> <a href=contact>P2Contact</a>


Conclusion

(Base target might be useful.) Base href is useless as:

  • page is equally WET since:
    • default base [–parent folder] ⇌ perfect (unless unnecessary/rare exceptions 𝒞1 & 𝒞2).
    • current web ⇌ multiple base hrefs unsupported.

Related

splitting a string into an array in C++ without using vector

#define MAXSPACE 25

string line =  "test one two three.";
string arr[MAXSPACE];
string search = " ";
int spacePos;
int currPos = 0;
int k = 0;
int prevPos = 0;

do
{

    spacePos = line.find(search,currPos);

    if(spacePos >= 0)
    {

        currPos = spacePos;
        arr[k] = line.substr(prevPos, currPos - prevPos);
        currPos++;
        prevPos = currPos;
        k++;
    }


}while( spacePos >= 0);

arr[k] = line.substr(prevPos,line.length());

for(int i = 0; i < k; i++)
{
   cout << arr[i] << endl;
}

Code coverage for Jest built on top of Jasmine

Jan 2019: Jest version 23.6

For anyone looking into this question recently especially if testing using npm or yarn directly

Currently, you don't have to change the configuration options

As per Jest official website, you can do the following to generate coverage reports:

1- For npm:

You must put -- before passing the --coverage argument of Jest

npm test -- --coverage

if you try invoking the --coverage directly without the -- it won't work

2- For yarn:

You can pass the --coverage argument of jest directly

yarn test --coverage

Randomize a List<T>

A very simple approach to this kind of problem is to use a number of random element swap in the list.

In pseudo-code this would look like this:

do 
    r1 = randomPositionInList()
    r2 = randomPositionInList()
    swap elements at index r1 and index r2 
for a certain number of times

Copy rows from one table to another, ignoring duplicates

I realize this is old, but I got here from google and after reviewing the accepted answer I did my own statement and it worked for me hope someone will find it useful:

    INSERT IGNORE INTO destTable SELECT id, field2,field3... FROM origTable

Edit: This works on MySQL I did not test on MSSQL

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

Junit test case for database insert method with DAO and web service

@Test
public void testSearchManagementStaff() throws SQLException
{
    boolean res=true;
    ManagementDaoImp mdi=new ManagementDaoImp();
    boolean b=mdi.searchManagementStaff("[email protected]"," 123456");
    assertEquals(res,b);
}

Jupyter Notebook not saving: '_xsrf' argument missing from post

In My Case, I have a close tab of Home Page. After Re-opening the Jupyter.The Error was automatically gone and We can save the file.

How to declare std::unique_ptr and what is the use of it?

The constructor of unique_ptr<T> accepts a raw pointer to an object of type T (so, it accepts a T*).

In the first example:

unique_ptr<int> uptr (new int(3));

The pointer is the result of a new expression, while in the second example:

unique_ptr<double> uptr2 (pd);

The pointer is stored in the pd variable.

Conceptually, nothing changes (you are constructing a unique_ptr from a raw pointer), but the second approach is potentially more dangerous, since it would allow you, for instance, to do:

unique_ptr<double> uptr2 (pd);
// ...
unique_ptr<double> uptr3 (pd);

Thus having two unique pointers that effectively encapsulate the same object (thus violating the semantics of a unique pointer).

This is why the first form for creating a unique pointer is better, when possible. Notice, that in C++14 we will be able to do:

unique_ptr<int> p = make_unique<int>(42);

Which is both clearer and safer. Now concerning this doubt of yours:

What is also not clear to me, is how pointers, declared in this way will be different from the pointers declared in a "normal" way.

Smart pointers are supposed to model object ownership, and automatically take care of destroying the pointed object when the last (smart, owning) pointer to that object falls out of scope.

This way you do not have to remember doing delete on objects allocated dynamically - the destructor of the smart pointer will do that for you - nor to worry about whether you won't dereference a (dangling) pointer to an object that has been destroyed already:

{
    unique_ptr<int> p = make_unique<int>(42);
    // Going out of scope...
}
// I did not leak my integer here! The destructor of unique_ptr called delete

Now unique_ptr is a smart pointer that models unique ownership, meaning that at any time in your program there shall be only one (owning) pointer to the pointed object - that's why unique_ptr is non-copyable.

As long as you use smart pointers in a way that does not break the implicit contract they require you to comply with, you will have the guarantee that no memory will be leaked, and the proper ownership policy for your object will be enforced. Raw pointers do not give you this guarantee.

How to stop docker under Linux

In my case, it was neither systemd nor a cron job, but it was snap. So I had to run:

sudo snap stop docker
sudo snap remove docker

... and the last command actually never ended, I don't know why: this snap thing is really a pain. So I also ran:

sudo apt purge snap

:-)

Get all object attributes in Python?

You can use dir(your_object) to get the attributes and getattr(your_object, your_object_attr) to get the values

usage :

for att in dir(your_object):
    print (att, getattr(your_object,att))

ImportError: No module named pythoncom

You should be using pip to install packages, since it gives you uninstall capabilities.

Also, look into virtualenv. It works well with pip and gives you a sandbox so you can explore new stuff without accidentally hosing your system-wide install.

Jquery split function

Try this. It uses the split function which is a core part of javascript, nothing to do with jQuery.

var parts = html.split(":-"),
    i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
    $("#" + parts[i]).text(parts[i + 1]);
}

Error: Expression must have integral or unscoped enum type

Your variable size is declared as: float size;

You can't use a floating point variable as the size of an array - it needs to be an integer value.

You could cast it to convert to an integer:

float *temp = new float[(int)size];

Your other problem is likely because you're writing outside of the bounds of the array:

   float *temp = new float[size];

    //Getting input from the user
    for (int x = 1; x <= size; x++){
        cout << "Enter temperature " << x << ": ";

        // cin >> temp[x];
        // This should be:
        cin >> temp[x - 1];
    }

Arrays are zero based in C++, so this is going to write beyond the end and never write the first element in your original code.

Reading Excel files from C#

If you have multiple tables in the same worksheet you can give each table an object name and read the table using the OleDb method as shown here: http://vbktech.wordpress.com/2011/05/10/c-net-reading-and-writing-to-multiple-tables-in-the-same-microsoft-excel-worksheet/

How do I add a newline using printf?

Try this:

printf '\n%s\n' 'I want this on a new line!'

That allows you to separate the formatting from the actual text. You can use multiple placeholders and multiple arguments.

quantity=38; price=142.15; description='advanced widget'
$ printf '%8d%10.2f  %s\n' "$quantity" "$price" "$description"
      38    142.15  advanced widget

Specifying a custom DateTime format when serializing with Json.Net

You are on the right track. Since you said you can't modify the global settings, then the next best thing is to apply the JsonConverter attribute on an as-needed basis, as you suggested. It turns out Json.Net already has a built-in IsoDateTimeConverter that lets you specify the date format. Unfortunately, you can't set the format via the JsonConverter attribute, since the attribute's sole argument is a type. However, there is a simple solution: subclass the IsoDateTimeConverter, then specify the date format in the constructor of the subclass. Apply the JsonConverter attribute where needed, specifying your custom converter, and you're ready to go. Here is the entirety of the code needed:

class CustomDateTimeConverter : IsoDateTimeConverter
{
    public CustomDateTimeConverter()
    {
        base.DateTimeFormat = "yyyy-MM-dd";
    }
}

If you don't mind having the time in there also, you don't even need to subclass the IsoDateTimeConverter. Its default date format is yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK (as seen in the source code).

Everytime I run gulp anything, I get a assertion error. - Task function must be specified

I get the same error when using Gulp. The solution is to switch to Gulp version 3.9.1, both for the local version and the CLI version.

sudo npm install -g [email protected]

Run in the project's folder

npm install [email protected]

Open Source Alternatives to Reflector?

The Reflector tool uses Reflection.  - apparently this is not correct.

You asked for two things - code that shows what reflector does, and also an alternative to reflector.

Here's an example, much simplified from what Reflector does, but it shows the technique of reflection: TypeView.cs

I don't have a suggestion for an open-source Reflector replacement.

How do I force a favicon refresh?

Just change this filename='favicon1.ico'

In JavaScript can I make a "click" event fire programmatically for a file input element?

You can use

<button id="file">select file</button>
<input type="file" name="file" id="file_input" style="display:none;">
<script>
$('#file').click(function() {
        $('#file_input').focus().trigger('click');
    });
</script>

Default value of function parameter

In C++ the requirements imposed on default arguments with regard to their location in parameter list are as follows:

  1. Default argument for a given parameter has to be specified no more than once. Specifying it more than once (even with the same default value) is illegal.

  2. Parameters with default arguments have to form a contiguous group at the end of the parameter list.

Now, keeping that in mind, in C++ you are allowed to "grow" the set of parameters that have default arguments from one declaration of the function to the next, as long as the above requirements are continuously satisfied.

For example, you can declare a function with no default arguments

void foo(int a, int b);

In order to call that function after such declaration you'll have to specify both arguments explicitly.

Later (further down) in the same translation unit, you can re-declare it again, but this time with one default argument

void foo(int a, int b = 5);

and from this point on you can call it with just one explicit argument.

Further down you can re-declare it yet again adding one more default argument

void foo(int a = 1, int b);

and from this point on you can call it with no explicit arguments.

The full example might look as follows

void foo(int a, int b);

int main()
{
  foo(2, 3);

  void foo(int a, int b = 5); // redeclare
  foo(8); // OK, calls `foo(8, 5)`

  void foo(int a = 1, int b); // redeclare again
  foo(); // OK, calls `foo(1, 5)`
}

void foo(int a, int b)
{
  // ...
}

As for the code in your question, both variants are perfectly valid, but they mean different things. The first variant declares a default argument for the second parameter right away. The second variant initially declares your function with no default arguments and then adds one for the second parameter.

The net effect of both of your declarations (i.e. the way it is seen by the code that follows the second declaration) is exactly the same: the function has default argument for its second parameter. However, if you manage to squeeze some code between the first and the second declarations, these two variants will behave differently. In the second variant the function has no default arguments between the declarations, so you'll have to specify both arguments explicitly.

How to use paths in tsconfig.json?

You can use combination of baseUrl and paths docs.

Assuming root is on the topmost src dir(and I read your image properly) use

// tsconfig.json
{
  "compilerOptions": {
    ...
    "baseUrl": ".",
    "paths": {
      "lib/*": [
        "src/org/global/lib/*"
      ]
    }
  }
}

For webpack you might also need to add module resolution. For webpack2 this could look like

// webpack.config.js
module.exports = {
    resolve: {
        ...
        modules: [
            ...
            './src/org/global'
        ]
    }
}

Parsing a JSON array using Json.Net

Use Manatee.Json https://github.com/gregsdennis/Manatee.Json/wiki/Usage

And you can convert the entire object to a string, filename.json is expected to be located in documents folder.

        var text = File.ReadAllText("filename.json");
        var json = JsonValue.Parse(text);

        while (JsonValue.Null != null)
        {
            Console.WriteLine(json.ToString());

        }
        Console.ReadLine();

font awesome icon in select option

I used this solution and it worked with Font Awesome 5: https://stackoverflow.com/a/50973559/3813846

What made the difference in my case was to add font-weight: 900;to the class. Keep in mind to 'fa' to the value.

Example of my code:

<select class="text-primary fa-select" name="class_logo" required>
  <option value="fa address-book">&#xf2b9; address-book</option>
  <option value="fa adjust">&#xf042; adjust</option>
  <option value="fa air-freshener">&#xf5d0; air-freshener</option>
</select>

CSS:

.fa-select {
    font-family: 'Lato', 'Font Awesome 5 Free';
    font-weight: 900;
}

Edit: If you are mixing Solid Icons with Brand Icons in the select, change the CSS as follows:

.fa-select {
    font-family: 'Lato', 'Font Awesome 5 Free', 'Font Awesome 5 Brands';
    font-weight: 900;
}

Have a variable in images path in Sass?

Was searching around for an answer to the same question, but think I found a better solution: http://blog.grayghostvisuals.com/compass/image-url/

Basically, you can set your image path in config.rb and you use the image-url() helper

How do I get the localhost name in PowerShell?

In PowerShell Core v6 (works on macOS, Linux and Windows):

[Environment]::MachineName

Get the last non-empty cell in a column in Google Sheets

Here's another one:

=indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),""))))

With the final equation being this:

=DAYS360(A2,indirect("A"&max(arrayformula(if(A:A<>"",row(A:A),"")))))

The other equations on here work, but I like this one because it makes getting the row number easy, which I find I need to do more often. Just the row number would be like this:

=max(arrayformula(if(A:A<>"",row(A:A),"")))

I originally tried to find just this to solve a spreadsheet issue, but couldn't find anything useful that just gave the row number of the last entry, so hopefully this is helpful for someone.

Also, this has the added advantage that it works for any type of data in any order, and you can have blank rows in between rows with content, and it doesn't count cells with formulas that evaluate to "". It can also handle repeated values. All in all it's very similar to the equation that uses max((G:G<>"")*row(G:G)) on here, but makes pulling out the row number a little easier if that's what you're after.

Alternatively, if you want to put a script on your sheet you can make it easy on yourself if you plan on doing this a lot. Here's that scirpt:

function lastRow(sheet,column) {
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  if (column == null) {
    if (sheet != null) {
       var sheet = ss.getSheetByName(sheet);
    } else {
      var sheet = ss.getActiveSheet();
    }
    return sheet.getLastRow();
  } else {
    var sheet = ss.getSheetByName(sheet);
    var lastRow = sheet.getLastRow();
    var array = sheet.getRange(column + 1 + ':' + column + lastRow).getValues();
    for (i=0;i<array.length;i++) {
      if (array[i] != '') {       
        var final = i + 1;
      }
    }
    if (final != null) {
      return final;
    } else {
      return 0;
    }
  }
}

Here you can just type in the following if you want the last row on the same of the sheet that you're currently editing:

=LASTROW()

or if you want the last row of a particular column from that sheet, or of a particular column from another sheet you can do the following:

=LASTROW("Sheet1","A")

And for the last row of a particular sheet in general:

=LASTROW("Sheet1")

Then to get the actual data you can either use indirect:

=INDIRECT("A"&LASTROW())

or you can modify the above script at the last two return lines (the last two since you would have to put both the sheet and the column to get the actual value from an actual column), and replace the variable with the following:

return sheet.getRange(column + final).getValue();

and

return sheet.getRange(column + lastRow).getValue();

One benefit of this script is that you can choose if you want to include equations that evaluate to "". If no arguments are added equations evaluating to "" will be counted, but if you specify a sheet and column they will now be counted. Also, there's a lot of flexibility if you're willing to use variations of the script.

Probably overkill, but all possible.

WHILE LOOP with IF STATEMENT MYSQL

I have discovered that you cannot have conditionals outside of the stored procedure in mysql. This is why the syntax error. As soon as I put the code that I needed between

   BEGIN
   SELECT MONTH(CURDATE()) INTO @curmonth;
   SELECT MONTHNAME(CURDATE()) INTO @curmonthname;
   SELECT DAY(LAST_DAY(CURDATE())) INTO @totaldays;
   SELECT FIRST_DAY(CURDATE()) INTO @checkweekday;
   SELECT DAY(@checkweekday) INTO @checkday;
   SET @daycount = 0;
   SET @workdays = 0;

     WHILE(@daycount < @totaldays) DO
       IF (WEEKDAY(@checkweekday) < 5) THEN
         SET @workdays = @workdays+1;
       END IF;
       SET @daycount = @daycount+1;
       SELECT ADDDATE(@checkweekday, INTERVAL 1 DAY) INTO @checkweekday;
     END WHILE;
   END

Just for others:

If you are not sure how to create a routine in phpmyadmin you can put this in the SQL query

    delimiter ;;
    drop procedure if exists test2;;
    create procedure test2()
    begin
    select ‘Hello World’;
    end
    ;;

Run the query. This will create a stored procedure or stored routine named test2. Now go to the routines tab and edit the stored procedure to be what you want. I also suggest reading http://net.tutsplus.com/tutorials/an-introduction-to-stored-procedures/ if you are beginning with stored procedures.

The first_day function you need is: How to get first day of every corresponding month in mysql?

Showing the Procedure is working Simply add the following line below END WHILE and above END

    SELECT @curmonth,@curmonthname,@totaldays,@daycount,@workdays,@checkweekday,@checkday;

Then use the following code in the SQL Query Window.

    call test2 /* or whatever you changed the name of the stored procedure to */

NOTE: If you use this please keep in mind that this code does not take in to account nationally observed holidays (or any holidays for that matter).

How do you select the entire excel sheet with Range using VBA?

you have a few options here:

  1. Using the UsedRange property
  2. find the last row and column used
  3. use a mimic of shift down and shift right

I personally use the Used Range and find last row and column method most of the time.

Here's how you would do it using the UsedRange property:

Sheets("Sheet_Name").UsedRange.Select

This statement will select all used ranges in the worksheet, note that sometimes this doesn't work very well when you delete columns and rows.

The alternative is to find the very last cell used in the worksheet

Dim rngTemp As Range
Set rngTemp = Cells.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious)
If Not rngTemp Is Nothing Then
    Range(Cells(1, 1), rngTemp).Select
End If

What this code is doing:

  1. Find the last cell containing any value
  2. select cell(1,1) all the way to the last cell

Using the rJava package on Win7 64 bit with R

This is a follow-up to Update (July 2018). I am on 64 bit Windows 10 but am set up to build r packages from source for both 32 and 64 bit with Rtools. My 64 bit jdk is jdk-11.0.2. When I can, I do everything in RStudio. As of March 2019, rjava is tested with <=jdk11, see github issue #157.

  • Install jdks to their default location per Update (July 2018) by @Jeroen.
  • In R studio, set JAVA_HOME to the 64 bit jdk

Sys.setenv(JAVA_HOME="C:/Program Files/Java/jdk-11.0.2")

  • Optionally check your environmental variable

Sys.getenv("JAVA_HOME")

  • Install the package per the github page recommendation

install.packages("rJava",,"http://rforge.net")

FYI, the rstudio scripting console doesn't like the double commas... but it works!

Link entire table row?

Also it depends if you need to use a table element or not. You can imitate a table using CSS and make an A element the row

<div class="table" style="width:100%;">
  <a href="#" class="tr">
    <span class="td">
      cell 1
    </span>
    <span class="td">
      cell 2
    </span>
  </a>
</div>

css:

.table{display:table;}
.tr{display:table-row;}
.td{display:table-cell;}
.tr:hover{background-color:#ccc;}

Access Form - Syntax error (missing operator) in query expression

Guys am facing similar issue here is my full code

Do let me know where am i going wrong. Error message: syntax error (Missing operator) in query expression 'AutoID='

This only hapens when i click on login without entering any txt in either combobox and password field.

    Option Compare Database
Option Explicit

Private Sub Login_Click()

If IsNull(Me.ComboUserSelect.Value) Then
    MsgBox "Please select username", vbInformation, "Login ID Required"
    Me.ComboUserSelect.SetFocus
ElseIf IsNull(Me.txtpassword.Value) Then
    MsgBox "please enter password", vbInformation, "Password is Required"
    Me.txtpassword.SetFocus
End If

'============= Declaring the variables ==========='
Dim passwordindatabase As String
Dim typedpassword As String
Dim useraccesstype As String


passwordindatabase = DLookup("Password", "LoginDB", "AutoID=" & ComboUserSelect.Value)
typedpassword = txtpassword.Value
useraccesstype = DLookup("AccessType", "LoginDB", "AutoID=" & ComboUserSelect.Value)


If typedpassword = passwordindatabase Then
    If useraccesstype = "Admin" Then
    DoCmd.OpenForm ("Cam Infra")
    DoCmd.Close acForm, "Login_Form", acSaveNo
    Else
    If useraccesstype = "user" Then
    DoCmd.OpenForm ("Custom_Search_Form")
    DoCmd.Close acForm, "Login_Form", acSaveNo
    End If
    End If
    End If
    

End Sub

how to specify new environment location for conda create

If you want to use the --prefix or -p arguments, but want to avoid having to use the environment's full path to activate it, you need to edit the .condarc config file before you create the environment.

The .condarc file is in the home directory; C:\Users\<user> on Windows. Edit the values under the envs_dirs key to include the custom path for your environment. Assuming the custom path is D:\envs, the file should end up looking something like this:

ssl_verify: true
channels:
  - defaults
envs_dirs:
  - C:\Users\<user>\Anaconda3\envs
  - D:\envs

Then, when you create a new environment on that path, its name will appear along with the path when you run conda env list, and you should be able to activate it using only the name, and not the full path.

Command line screenshot

In summary, if you edit .condarc to include D:\envs, and then run conda env create -p D:\envs\myenv python=x.x, then activate myenv (or source activate myenv on Linux) should work.

Hope that helps!

P.S. I stumbled upon this through trial and error. I think what happens is when you edit the envs_dirs key, conda updates ~\.conda\environments.txt to include the environments found in all the directories specified under the envs_dirs, so they can be accessed without using absolute paths.

error C2039: 'string' : is not a member of 'std', header file problem

Take care not to include

#include <string.h> 

but only

#include <string>

It took me 1 hour to find this in my code.

Hope this can help

Remove an item from a dictionary when its key is unknown

There is nothing wrong with deleting items from the dictionary while iterating, as you've proposed. Be careful about multiple threads using the same dictionary at the same time, which may result in a KeyError or other problems.

Of course, see the docs at http://docs.python.org/library/stdtypes.html#typesmapping

Search All Fields In All Tables For A Specific Value (Oracle)

if we know the table and colum names but want to find out the number of times string is appearing for each schema:

Declare

owner VARCHAR2(1000);
tbl VARCHAR2(1000);
cnt number;
ct number;
str_sql varchar2(1000);
reason varchar2(1000);
x varchar2(1000):='%string_to_be_searched%';

cursor csr is select owner,table_name 
from all_tables where table_name ='table_name';

type rec1 is record (
ct VARCHAR2(1000));

type rec is record (
owner VARCHAR2(1000):='',
table_name VARCHAR2(1000):='');

rec2 rec;
rec3 rec1;
begin

for rec2 in csr loop

--str_sql:= 'select count(*) from '||rec.owner||'.'||rec.table_name||' where CTV_REMARKS like '||chr(39)||x||chr(39);
--dbms_output.put_line(str_sql);
--execute immediate str_sql

execute immediate 'select count(*) from '||rec2.owner||'.'||rec2.table_name||' where column_name like '||chr(39)||x||chr(39)
into rec3;
if rec3.ct <> 0 then
dbms_output.put_line(rec2.owner||','||rec3.ct);
else null;
end if;
end loop;
end;

HTML / CSS How to add image icon to input type="button"?

you can try insert image inside button http://jsfiddle.net/s5GVh/1415/

<button type="submit"><img src='https://aca5.accela.com/bcc/app_themesDefault/assets/gsearch_disabled.png'/></button>

Is there a way I can retrieve sa password in sql server 2005

Granted you have administrative Windows privileges on the server, another option would be to start SQL Server in Single User Mode, using the Startup parameter "-m". Doing this, you can login using SQLCMD, create a new user and give it sysadmin privileges. Finally, you have to disable Single User Mode, login to SSMS using your new user, and go to Segurity/Logins and change "sa" user password.

You can check this post: http://v-consult.be/2011/05/26/recover-sa-password-microsoft-sql-server-2008-r2/

Setting a property with an EventTrigger

I modified Neutrino's solution to make the xaml look less verbose when specifying the value:

Sorry for no pictures of the rendered xaml, just imagine a [=] hamburger button that you click and it turns into [<-] a back button and also toggles the visibility of a Grid.

xmlns:i="clr-namespace:System.Windows.Interactivity;assembly=System.Windows.Interactivity"

...

<Grid>
    <Button x:Name="optionsButton">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <local:SetterAction PropertyName="Visibility" Value="Collapsed" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsBackButton}" Value="Visible" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="Visible" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <glyphs:Hamburger Width="10" Height="10" />
    </Button>

    <Button x:Name="optionsBackButton" Visibility="Collapsed">
        <i:Interaction.Triggers>
            <i:EventTrigger EventName="Click">
                <local:SetterAction PropertyName="Visibility" Value="Collapsed" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsButton}" Value="Visible" />
                <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="Collapsed" />
            </i:EventTrigger>
        </i:Interaction.Triggers>

        <glyphs:Back Width="12" Height="11" />
    </Button>
</Grid>

...

<Grid Grid.RowSpan="2" x:Name="optionsPanel" Visibility="Collapsed">

</Grid>

You can also specify values this way like in Neutrino's solution:

<Button x:Name="optionsButton">
    <i:Interaction.Triggers>
        <i:EventTrigger EventName="Click">
            <local:SetterAction PropertyName="Visibility" Value="{x:Static Visibility.Collapsed}" />
            <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsBackButton}" Value="{x:Static Visibility.Visible}" />
            <local:SetterAction PropertyName="Visibility" TargetObject="{Binding ElementName=optionsPanel}" Value="{x:Static Visibility.Visible}" />
        </i:EventTrigger>
    </i:Interaction.Triggers>

    <glyphs:Hamburger Width="10" Height="10" />
</Button>

And here's the code.

using System;
using System.ComponentModel;
using System.Reflection;
using System.Windows;
using System.Windows.Interactivity;

namespace Mvvm.Actions
{
    /// <summary>
    /// Sets a specified property to a value when invoked.
    /// </summary>
    public class SetterAction : TargetedTriggerAction<FrameworkElement>
    {
        #region Properties

        #region PropertyName

        /// <summary>
        /// Property that is being set by this setter.
        /// </summary>
        public string PropertyName
        {
            get { return (string)GetValue(PropertyNameProperty); }
            set { SetValue(PropertyNameProperty, value); }
        }

        public static readonly DependencyProperty PropertyNameProperty =
            DependencyProperty.Register("PropertyName", typeof(string), typeof(SetterAction),
            new PropertyMetadata(String.Empty));

        #endregion

        #region Value

        /// <summary>
        /// Property value that is being set by this setter.
        /// </summary>
        public object Value
        {
            get { return (object)GetValue(ValueProperty); }
            set { SetValue(ValueProperty, value); }
        }

        public static readonly DependencyProperty ValueProperty =
            DependencyProperty.Register("Value", typeof(object), typeof(SetterAction),
            new PropertyMetadata(null));

        #endregion

        #endregion

        #region Overrides

        protected override void Invoke(object parameter)
        {
            var target = TargetObject ?? AssociatedObject;

            var targetType = target.GetType();

            var property = targetType.GetProperty(PropertyName, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static | BindingFlags.Instance);
            if (property == null)
                throw new ArgumentException(String.Format("Property not found: {0}", PropertyName));

            if (property.CanWrite == false)
                throw new ArgumentException(String.Format("Property is not settable: {0}", PropertyName));

            object convertedValue;

            if (Value == null)
                convertedValue = null;

            else
            {
                var valueType = Value.GetType();
                var propertyType = property.PropertyType;

                if (valueType == propertyType)
                    convertedValue = Value;

                else
                {
                    var propertyConverter = TypeDescriptor.GetConverter(propertyType);

                    if (propertyConverter.CanConvertFrom(valueType))
                        convertedValue = propertyConverter.ConvertFrom(Value);

                    else if (valueType.IsSubclassOf(propertyType))
                        convertedValue = Value;

                    else
                        throw new ArgumentException(String.Format("Cannot convert type '{0}' to '{1}'.", valueType, propertyType));
                }
            }

            property.SetValue(target, convertedValue);
        }

        #endregion
    }
}

Error:attempt to apply non-function

I got the error because of a clumsy typo:

This errors:

knitr::opts_chunk$seet(echo = FALSE)

Error: attempt to apply non-function

After correcting the typo, it works:

knitr::opts_chunk$set(echo = FALSE)

How to print binary number via printf

printf() doesn't directly support that. Instead you have to make your own function.

Something like:

while (n) {
    if (n & 1)
        printf("1");
    else
        printf("0");

    n >>= 1;
}
printf("\n");

How to provide user name and password when connecting to a network share

If you can't create an locally valid security token, it seems like you've ruled all out every option bar Win32 API and WNetAddConnection*.

Tons of information on MSDN about WNet - PInvoke information and sample code that connects to a UNC path here:

http://www.pinvoke.net/default.aspx/mpr/WNetAddConnection2.html#

MSDN Reference here:

http://msdn.microsoft.com/en-us/library/aa385391(VS.85).aspx

A process crashed in windows .. Crash dump location

On Windows 2008 R2, I have seen application crash dumps under either

C:\Users\[Some User]\Microsoft\Windows\WER\ReportArchive

or

C:\ProgramData\Microsoft\Windows\WER\ReportArchive

I don't know how Windows decides which directory to use.

How do you round a floating point number in Perl?

You can either use a module like Math::Round:

use Math::Round;
my $rounded = round( $float );

Or you can do it the crude way:

my $rounded = sprintf "%.0f", $float;

How do I get the full path of the current file's directory?

IPython has a magic command %pwd to get the present working directory. It can be used in following way:

from IPython.terminal.embed import InteractiveShellEmbed

ip_shell = InteractiveShellEmbed()

present_working_directory = ip_shell.magic("%pwd")

On IPython Jupyter Notebook %pwd can be used directly as following:

present_working_directory = %pwd

How to define multiple CSS attributes in jQuery?

Better to just use .addClass() and .removeClass() even if you have 1 or more styles to change. It's more maintainable and readable.

If you really have the urge to do multiple CSS properties, then use the following:

.css({
   'font-size' : '10px',
   'width' : '30px',
   'height' : '10px'
});

NB!
Any CSS properties with a hyphen need to be quoted.
I've placed the quotes so no one will need to clarify that, and the code will be 100% functional.

Get css top value as number not as string?

A slightly more practical/efficient plugin based on Ivan Castellanos' answer (which was based on M4N's answer). Using || 0 will convert Nan to 0 without the testing step.

I've also provided float and int variations to suit the intended use:

jQuery.fn.cssInt = function (prop) {
    return parseInt(this.css(prop), 10) || 0;
};

jQuery.fn.cssFloat = function (prop) {
    return parseFloat(this.css(prop)) || 0;
};

Usage:

$('#elem').cssInt('top');    // e.g. returns 123 as an int
$('#elem').cssFloat('top');  // e.g. Returns 123.45 as a float

Test fiddle on http://jsfiddle.net/TrueBlueAussie/E5LTu/

How do I duplicate a line or selection within Visual Studio Code?

In VSCode Ctrl+CCtrl+V duplicates the whole line below.

I prefer this to the accepted answer, because it only requires one hand to do this and feels way more natural.

The accepted answer will probably do it for most people, however Down sits the other side of the keyboard. So you have two options, use both hands on (Left Hand:L Shift+L Alt+ Right Hand:Up/Down), or with a single hand use the right R Shift+R Alt+Up/Down. The second option feels weird in my opinion. I'd rather use the option where my hand naturally sits on the keyboard, and if its one hand, even better.

Postgres where clause compare timestamp

Assuming you actually mean timestamp because there is no datetime in Postgres

Cast the timestamp column to a date, that will remove the time part:

select *
from the_table
where the_timestamp_column::date = date '2015-07-15';

This will return all rows from July, 15th.

Note that the above will not use an index on the_timestamp_column. If performance is critical, you need to either create an index on that expression or use a range condition:

select *
from the_table
where the_timestamp_column >= timestamp '2015-07-15 00:00:00'
  and the_timestamp_column < timestamp '2015-07-16 00:00:00';

How to open a page in a new window or tab from code-behind

Use:

Target= "_blank" property of anchor tag

How do I connect C# with Postgres?

If you want an recent copy of npgsql, then go here

http://www.npgsql.org/

This can be installed via package manager console as

PM> Install-Package Npgsql

How to tell Maven to disregard SSL errors (and trusting all certs)?

Create a folder ${USER_HOME}/.mvn and put a file called maven.config in it.

The content should be:

-Dmaven.wagon.http.ssl.insecure=true
-Dmaven.wagon.http.ssl.allowall=true
-Dmaven.wagon.http.ssl.ignore.validity.dates=true

Hope this helps.

How to change link color (Bootstrap)

For a direct change, you can use Bootstrap classes in the <a> tag (it won't work in the <div>):

<h4 class="text-center"><a class="text-warning" href="#">Your text</a></h4>

Triggering change detection manually in Angular

Try one of these:

  • ApplicationRef.tick() - similar to AngularJS's $rootScope.$digest() -- i.e., check the full component tree
  • NgZone.run(callback) - similar to $rootScope.$apply(callback) -- i.e., evaluate the callback function inside the Angular zone. I think, but I'm not sure, that this ends up checking the full component tree after executing the callback function.
  • ChangeDetectorRef.detectChanges() - similar to $scope.$digest() -- i.e., check only this component and its children

You can inject ApplicationRef, NgZone, or ChangeDetectorRef into your component.

change text of button and disable button in iOS

If somebody, who is looking for a solution in Swift, landed here, it would be:

myButton.isEnabled = false // disables
myButton.setTitle("myTitle", for: .normal) // sets text

Documentation: isEnabled, setTitle.

Older code:

myButton.enabled = false // disables
myButton.setTitle("myTitle", forState: UIControlState.Normal) // sets text

Python handling socket.error: [Errno 104] Connection reset by peer

"Connection reset by peer" is the TCP/IP equivalent of slamming the phone back on the hook. It's more polite than merely not replying, leaving one hanging. But it's not the FIN-ACK expected of the truly polite TCP/IP converseur. (From other SO answer)

So you can't do anything about it, it is the issue of the server.

But you could use try .. except block to handle that exception:

from socket import error as SocketError
import errno

try:
    response = urllib2.urlopen(request).read()
except SocketError as e:
    if e.errno != errno.ECONNRESET:
        raise # Not error we are looking for
    pass # Handle error here.

Base table or view not found: 1146 Table Laravel 5

Just run the command:

php artisan migrate:refresh --seed

jQuery - Getting the text value of a table cell in the same row as a clicked element

Nick has the right answer, but I wanted to add you could also get the cell data without needing the class name

var Something = $(this).closest('tr').find('td:eq(1)').text();

:eq(#) has a zero based index (link).

How do you use "git --bare init" repository?

The --bare flag creates a repository that doesn’t have a working directory. The bare repository is the central repository and you can't edit(store) codes here for avoiding the merging error.

For example, when you add a file in your local repository (machine 1) and push it to the bare repository, you can't see the file in the bare repository for it is always 'empty'. However, you really push something to the repository and you can see it inexplicitly by cloning another repository in your server(machine 2).

Both the local repository in machine 1 and the 'copy' repository in machine 2 are non-bare. relationship between bare and non-bare repositories

The blog will help you understand it. https://www.atlassian.com/git/tutorials/setting-up-a-repository

How to read and write into file using JavaScript?

Here is write solution for chrome v52+ (user still need to select a destination doe...)
source: StreamSaver.js

<!-- load StreamSaver.js before streams polyfill to detect support -->
<script src="StreamSaver.js"></script>
<script src="https://wzrd.in/standalone/web-streams-polyfill@latest"></script>
const writeStream = streamSaver.createWriteStream('filename.txt')
const encoder = new TextEncoder
let data = 'a'.repeat(1024)
let uint8array = encoder.encode(data + "\n\n")

writeStream.write(uint8array) // must be uInt8array
writeStream.close()

Best suited for writing large data generated on client side.
Otherwise I suggest using FileSaver.js to save Blob/Files

How to use PHP string in mySQL LIKE query?

You have the syntax wrong; there is no need to place a period inside a double-quoted string. Instead, it should be more like

$query = mysql_query("SELECT * FROM table WHERE the_number LIKE '$prefix%'");

You can confirm this by printing out the string to see that it turns out identical to the first case.

Of course it's not a good idea to simply inject variables into the query string like this because of the danger of SQL injection. At the very least you should manually escape the contents of the variable with mysql_real_escape_string, which would make it look perhaps like this:

$sql = sprintf("SELECT * FROM table WHERE the_number LIKE '%s%%'",
               mysql_real_escape_string($prefix));
$query = mysql_query($sql);

Note that inside the first argument of sprintf the percent sign needs to be doubled to end up appearing once in the result.

Access-Control-Allow-Origin error sending a jQuery Post to Google API's

In my case the sub domain name causes the problem. Here are details

I used app_development.something.com, here underscore(_) sub domain is creating CORS error. After changing app_development to app-development it works fine.

How to detect when a UIScrollView has finished scrolling

I had a case of tapping and dragging actions and I found out that the dragging was calling scrollViewDidEndDecelerating

And the change offset manually with code ([_scrollView setContentOffset:contentOffset animated:YES];) was calling scrollViewDidEndScrollingAnimation.

//This delegate method is called when the dragging scrolling happens, but no when the     tapping
- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView
{
    //do whatever you want to happen when the scroll is done
}

//This delegate method is called when the tapping scrolling happens, but no when the  dragging
-(void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView
{
     //do whatever you want to happen when the scroll is done
}

How do you enable mod_rewrite on any OS?

network solutions offers the advice to put a php.ini in the cgi-bin to enable mod_rewrite

move div with CSS transition

transition-property:width;

This should work. you have to have browser dependent code

How to install PIP on Python 3.6?

This what worked for me on Amazon Linux

sudo yum list | grep python3

sudo yum install python36.x86_64 python36-tools.x86_64

$ python3 --version Python 3.6.8

$ pip -V pip 9.0.3 from /usr/lib/python2.7/dist-packages (python 2.7)

]$ sudo python3.6 -m pip install --upgrade pip Collecting pip Downloading https://files.pythonhosted.org/packages/d8/f3/413bab4ff08e1fc4828dfc59996d721917df8e8583ea85385d51125dceff/pip-19.0.3-py2.py3-none-any.whl (1.4MB) 100% |¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦¦| 1.4MB 969kB/s Installing collected packages: pip Found existing installation: pip 9.0.3 Uninstalling pip-9.0.3: Successfully uninstalled pip-9.0.3 Successfully installed pip-19.0.3

$ pip -V pip 19.0.3 from /usr/local/lib/python3.6/site-packages/pip (python 3.6)

Access cell value of datatable

If you need a weak reference to the cell value:

object field = d.Rows[0][3]

or

object field = d.Rows[0].ItemArray[3]

Should do it

If you need a strongly typed reference (string in your case) you can use the DataRowExtensions.Field extension method:

string field = d.Rows[0].Field<string>(3);

(make sure System.Data is in listed in the namespaces in this case)

Indexes are 0 based so we first access the first row (0) and then the 4th column in this row (3)

Laravel 4 Eloquent Query Using WHERE with OR AND OR?

If you want to use parameters for a,b,c,d in Laravel 4

Model::where(function ($query) use ($a,$b) {
    $query->where('a', '=', $a)
          ->orWhere('b', '=', $b);
})
->where(function ($query) use ($c,$d) {
    $query->where('c', '=', $c)
          ->orWhere('d', '=', $d);
});

setContentView(R.layout.main); error

Just take 2 steps and problem would be more likely to get solved:

Step 1: Clean your project by clicking Project -> Clean.

Step 2: Rebuild your project by clicking Project -> Build All.

Also make sure that your layout xml files are syntax error free and you don't have any image which has non-acceptable names (such as a "-" between image name).

Also I request you to have a look at problems window and let me know what errors are being shown there.

Load HTML page dynamically into div with jQuery

You can through option

Try this with some modifications

<div trbidi="on">
<script type="text/javascript">
function MostrarVideo(idYouTube)
{
var contenedor = document.getElementById('divInnerVideo');
if(idYouTube == '')
{contenedor.innerHTML = '';
} else{
var url = idYouTube;
contenedor.innerHTML = '<iframe width="560" height="315" src="https://www.youtube.com/embed/'+ url +'" frameborder="0" allowfullscreen></iframe>';
}
}
</script>


<select onchange="MostrarVideo(this.value);">
<option selected disabled>please selected </option>
<option value="qycqF1CWcXg">test1</option>
<option value="hniPHaBgvWk">test2</option>
<option value="bOQA33VNo7w">test3</option>
</select>
<div id="divInnerVideo">
</div>

If you want to put a default page placed inside id="divInnerVideo"

example:

<div id="divInnerVideo">
<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/pES8SezkV8w?rel=0&amp;showinfo=0" frameborder="0" allowfullscreen></iframe>
</div>

Why Choose Struct Over Class?

Since struct instances are allocated on stack, and class instances are allocated on heap, structs can sometimes be drastically faster.

However, you should always measure it yourself and decide based on your unique use case.

Consider the following example, which demonstrates 2 strategies of wrapping Int data type using struct and class. I am using 10 repeated values are to better reflect real world, where you have multiple fields.

class Int10Class {
    let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int
    init(_ val: Int) {
        self.value1 = val
        self.value2 = val
        self.value3 = val
        self.value4 = val
        self.value5 = val
        self.value6 = val
        self.value7 = val
        self.value8 = val
        self.value9 = val
        self.value10 = val
    }
}

struct Int10Struct {
    let value1, value2, value3, value4, value5, value6, value7, value8, value9, value10: Int
    init(_ val: Int) {
        self.value1 = val
        self.value2 = val
        self.value3 = val
        self.value4 = val
        self.value5 = val
        self.value6 = val
        self.value7 = val
        self.value8 = val
        self.value9 = val
        self.value10 = val
    }
}

func + (x: Int10Class, y: Int10Class) -> Int10Class {
    return IntClass(x.value + y.value)
}

func + (x: Int10Struct, y: Int10Struct) -> Int10Struct {
    return IntStruct(x.value + y.value)
}

Performance is measured using

// Measure Int10Class
measure("class (10 fields)") {
    var x = Int10Class(0)
    for _ in 1...10000000 {
        x = x + Int10Class(1)
    }
}

// Measure Int10Struct
measure("struct (10 fields)") {
    var y = Int10Struct(0)
    for _ in 1...10000000 {
        y = y + Int10Struct(1)
    }
}

func measure(name: String, @noescape block: () -> ()) {
    let t0 = CACurrentMediaTime()

    block()

    let dt = CACurrentMediaTime() - t0
    print("\(name) -> \(dt)")
}

Code can be found at https://github.com/knguyen2708/StructVsClassPerformance

UPDATE (27 Mar 2018):

As of Swift 4.0, Xcode 9.2, running Release build on iPhone 6S, iOS 11.2.6, Swift Compiler setting is -O -whole-module-optimization:

  • class version took 2.06 seconds
  • struct version took 4.17e-08 seconds (50,000,000 times faster)

(I no longer average multiple runs, as variances are very small, under 5%)

Note: the difference is a lot less dramatic without whole module optimization. I'd be glad if someone can point out what the flag actually does.


UPDATE (7 May 2016):

As of Swift 2.2.1, Xcode 7.3, running Release build on iPhone 6S, iOS 9.3.1, averaged over 5 runs, Swift Compiler setting is -O -whole-module-optimization:

  • class version took 2.159942142s
  • struct version took 5.83E-08s (37,000,000 times faster)

Note: as someone mentioned that in real-world scenarios, there will be likely more than 1 field in a struct, I have added tests for structs/classes with 10 fields instead of 1. Surprisingly, results don't vary much.


ORIGINAL RESULTS (1 June 2014):

(Ran on struct/class with 1 field, not 10)

As of Swift 1.2, Xcode 6.3.2, running Release build on iPhone 5S, iOS 8.3, averaged over 5 runs

  • class version took 9.788332333s
  • struct version took 0.010532942s (900 times faster)

OLD RESULTS (from unknown time)

(Ran on struct/class with 1 field, not 10)

With release build on my MacBook Pro:

  • The class version took 1.10082 sec
  • The struct version took 0.02324 sec (50 times faster)

WPF Label Foreground Color

The title "WPF Label Foreground Color" is very simple (exactly what I was looking for) but the OP's code is so cluttered it's easy to miss how simple it can be to set text foreground color on two different labels:

<StackPanel>
    <Label Foreground="Red">Red text</Label>
    <Label Foreground="Blue">Blue text</Label>
</StackPanel>

In summary, No, there was nothing wrong with your snippet.

invalid conversion from 'const char*' to 'char*'

Well, data.str().c_str() yields a char const* but your function Printfunc() wants to have char*s. Based on the name, it doesn't change the arguments but merely prints them and/or uses them to name a file, in which case you should probably fix your declaration to be

void Printfunc(int a, char const* loc, char const* stream)

The alternative might be to turn the char const* into a char* but fixing the declaration is preferable:

Printfunc(num, addr, const_cast<char*>(data.str().c_str()));

How to change default text color using custom theme?

Check if your activity layout overrides the theme, look for your activity layout located at layout/*your_activity*.xml and look for TextView that contains android:textColor="(some hex code") something like that on activity layout, and remove it. Then run your code again.

Why is php not running?

To answer the original question "Why is php not running?" The file your browser is asking for must have the .php extension. If the file has the .html extension, php will not be executed.

Error in launching AVD with AMD processor

For AMD processors:

Go to AVD manager and create a new virtual device as an ARM system image.

Resize UIImage and change the size of UIImageView

If you have the size of the image, why don't you set the frame.size of the image view to be of this size?

EDIT----

Ok, so seeing your comment I propose this:

UIImageView *imageView;
//so let's say you're image view size is set to the maximum size you want

CGFloat maxWidth = imageView.frame.size.width;
CGFloat maxHeight = imageView.frame.size.height;

CGFloat viewRatio = maxWidth / maxHeight;
CGFloat imageRatio = image.size.height / image.size.width;

if (imageRatio > viewRatio) {
    CGFloat imageViewHeight = round(maxWidth * imageRatio);
    imageView.frame = CGRectMake(0, ceil((self.bounds.size.height - imageViewHeight) / 2.f), maxWidth, imageViewHeight);
}
else if (imageRatio < viewRatio) {
    CGFloat imageViewWidth = roundf(maxHeight / imageRatio);
    imageView.frame = CGRectMake(ceil((maxWidth - imageViewWidth) / 2.f), 0, imageViewWidth, maxHeight);
} else {
    //your image view is already at the good size
}

This code will resize your image view to its image ratio, and also position the image view to the same centre as your "default" position.

PS: I hope you're setting imageView.layer.shouldRasterise = YES and imageView.layer.rasterizationScale = [UIScreen mainScreen].scale;

if you're using CALayer shadow effect ;) It will greatly improve the performance of your UI.

Timeout jQuery effects

You can do something like this:

$('.notice')
    .fadeIn()
    .animate({opacity: '+=0'}, 2000)   // Does nothing for 2000ms
    .fadeOut('fast');

Sadly, you can't just do .animate({}, 2000) -- I think this is a bug, and will report it.

How to Implement Custom Table View Section Headers and Footers with Storyboard

Similar to laszlo answer but you can reuse the same prototype cell for both the table cells and the section header cell. Add the first two functions below to your UIViewController subClass

override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell") as! DataCell
    cell.data1Label.text = "DATA KEY"
    cell.data2Label.text = "DATA VALUE"
    return cell
}

override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
    return 75
}

// Example of regular data cell dataDelegate to round out the example
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "DataCell", for: indexPath) as! PlayerCell

    cell.data1Label.text = "\(dataList[indexPath.row].key)"
    cell.data2Label.text = "\(dataList[indexPath.row].value)"
    return cell
}

Get value of div content using jquery

$('#field-function_purpose') will get you the element with ID field-function_purpose, which is your div element. text() returns you the content of the div.

var x = $('#field-function_purpose').text();

"The page has expired due to inactivity" - Laravel 5.5

My case was solved with SESSION_DOMAIN, in my local machine had to be set to xxx.localhost. It was causing conflicts with the production SESSION_DOMAIN, xxx.com that was set directly in the session.php config file.

Angular: Cannot Get /

Many answers dont really make sense but still have upvotes, makes me currious why that would still work in some cases.

In angular.json

"serve": {
  "builder": "@angular-devkit/build-angular:dev-server",
  "options": {
    "deployUrl": "/",
    "baseHref": "/",

worked for me.

Pass value to iframe from a window

We can use "postMessage" concept for sending data to an underlying iframe from main window.

you can checkout more about postMessage using this link add the below code inside main window page

// main window code
window.frames['myFrame'].contentWindow.postMessage("Hello World!");

we will pass "Hello World!" message to an iframe contentWindow with iframe id="myFrame".

now add the below code inside iframe source code

// iframe document code
function receive(event) {
    console.log("Received Message : " + event.data);
}
window.addEventListener('message', receive);

in iframe webpage we will attach an event listener to receive event and in 'receive' callback we will print the data to console

Drop unused factor levels in a subsetted data frame

Have tried most of the examples here if not all but none seem to be working in my case. After struggling for quite some time I have tried using as.character() on the factor column to change it to a col with strings which seems to working just fine.

Not sure for performance issues.

Setting state on componentDidMount()

It is not an anti-pattern to call setState in componentDidMount. In fact, ReactJS provides an example of this in their documentation:

You should populate data with AJAX calls in the componentDidMount lifecycle method. This is so you can use setState to update your component when the data is retrieved.

Example From Doc

componentDidMount() {
    fetch("https://api.example.com/items")
      .then(res => res.json())
      .then(
        (result) => {
          this.setState({
            isLoaded: true,
            items: result.items
          });
        },
        // Note: it's important to handle errors here
        // instead of a catch() block so that we don't swallow
        // exceptions from actual bugs in components.
        (error) => {
          this.setState({
            isLoaded: true,
            error
          });
        }
      )
  }

How do I add a margin between bootstrap columns without wrapping

You should work with padding on the inner container rather than with margin. Try this!

HTML

<div class="row info-panel">
    <div class="col-md-4" id="server_1">
       <div class="server-action-menu">
           Server 1
       </div>
   </div>
</div>

CSS

.server-action-menu {
    background-color: transparent;
    background-image: linear-gradient(to bottom, rgba(30, 87, 153, 0.2) 0%, rgba(125, 185, 232, 0) 100%);
    background-repeat: repeat;
    border-radius:10px;
    padding: 5px;
}

PHP error: "The zip extension and unzip command are both missing, skipping."

The shortest command to fix it on Debian and Ubuntu (dependencies will be installed automatically):

sudo apt install php-zip

Convert Float to Int in Swift

You can get an integer representation of your float by passing the float into the Integer initializer method.

Example:

Int(myFloat)

Keep in mind, that any numbers after the decimal point will be loss. Meaning, 3.9 is an Int of 3 and 8.99999 is an integer of 8.

wordpress contactform7 textarea cols and rows change in smaller screens

Code will be As below.

[textarea id:message 0x0 class:custom-class "Insert text here"]<!-- No Rows No columns -->

[textarea id:message x2 class:custom-class "Insert text here"]<!-- Only Rows -->

[textarea id:message 12x class:custom-class "Insert text here"]<!-- Only Columns -->

[textarea id:message 10x2 class:custom-class "Insert text here"]<!-- Both Rows and Columns -->

For Details: https://contactform7.com/text-fields/

How link to any local file with markdown syntax?

Thank you drifty0pine!

The first solution, it´s works!

[a relative link](../../some/dir/filename.md)
[Link to file in another dir on same drive](/another/dir/filename.md)
[Link to file in another dir on a different drive](/D:/dir/filename.md)

but I had need put more ../ until the folder where was my file, like this:

[FileToOpen](../../../../folderW/folderX/folderY/folderZ/FileToOpen.txt)

jQuery getJSON save result into variable

$.getJSon expects a callback functions either you pass it to the callback function or in callback function assign it to global variale.

var globalJsonVar;

    $.getJSON("http://127.0.0.1:8080/horizon-update", function(json){
               //do some thing with json  or assign global variable to incoming json. 
                globalJsonVar=json;
          });

IMO best is to call the callback function. which is nicer to eyes, readability aspects.

$.getJSON("http://127.0.0.1:8080/horizon-update", callbackFuncWithData);

function callbackFuncWithData(data)
{
 // do some thing with data 
}

Windows 7 - 'make' is not recognized as an internal or external command, operable program or batch file

This is an old question, but none of the answers here provide enough context for a beginner to choose which one to pick.

What is make?

make is a traditional Unix utility which reads a Makefile to decide what programs to run to reach a particular goal. Typically, that goal is to build a single piece of software; but make is general enough to be used for various other tasks, too, like assembling a PDF from a collection of TeX source files, or retrieving the newest versions of each of a set of web pages.

Besides encapsulating the steps to reach an individual target, make reduces processing time by avoiding to re-execute steps which are already complete. It does this by comparing time stamps between dependencies; if A depends on B but A is newer than B, there is no need to make A. Of course, in order for this to work properly, the Makefile needs to document all such dependencies.

A: B
    commands to produce A from B

Notice that the indentation needs to consist of a literal tab character. This is a common beginner mistake.

Common Versions of make

The original make was rather pedestrian. Its lineage continues to this day into BSD make, from which nmake is derived. Roughly speaking, this version provides the make functionality defined by POSIX, with a few minor enhancements and variations.

GNU make, by contrast, significantly extends the formalism, to the point where a GNU Makefile is unlikely to work with other versions (or occasionally even older versions of GNU make). There is a convention to call such files GNUmakefile instead of Makefile, but this convention is widely ignored, especially on platforms like Linux where GNU make is the de facto standard make.

Telltale signs that a Makefile uses GNU make conventions are the use of := instead of = for variable assignments (though this is not exclusively a GNU feature) and a plethora of functions like $(shell ...), $(foreach ...), $(patsubst ...) etc.

So Which Do I Need?

Well, it really depends on what you are hoping to accomplish.

If the software you are hoping to build has a vcproj file or similar, you probably want to use that instead, and not try to use make at all.

In the general case, MinGW make is a Windows port of GNU make for Windows, It should generally cope with any Makefile you throw at it.

If you know the software was written to use nmake and you already have it installed, or it is easy for you to obtain, maybe go with that.

You should understand that if the software was not written for, or explicitly ported to, Windows, it is unlikely to compile without significant modifications. In this scenario, getting make to run is the least of your problems, and you will need a good understanding of the differences between the original platform and Windows to have a chance of pulling it off yourself.

In some more detail, if the Makefile contains Unix commands like grep or curl or yacc then your system needs to have those commands installed, too. But quite apart from that, C or C++ (or more generally, source code in any language) which was written for a different platform might simply not work - at all, or as expected (which is often worse) - on Windows.

Get MAC address using shell script

This was the only thing that worked for me on Armbian:

dmesg | grep -oE 'mac=.*\w+' | cut -b '5-'

Unicode characters in URLs

What Tgr said. Background:

http://www.example.com/düsseldorf?neighbourhood=Lörick

That's not a URI. But it is an IRI.

You can't include an IRI in an HTML4 document; the type of attributes like href is defined as URI and not IRI. Some browsers will handle an IRI here anyway, but it's not really a good idea.

To encode an IRI into a URI, take the path and query parts, UTF-8-encode them then percent-encode the non-ASCII bytes:

http://www.example.com/d%C3%BCsseldorf?neighbourhood=L%C3%B6rick

If there are non-ASCII characters in the hostname part of the IRI, eg. http://??.???/, they have be encoded using Punycode instead.

Now you have a URI. It's an ugly URI. But most browsers will hide that for you: copy and paste it into the address bar or follow it in a link and you'll see it displayed with the original Unicode characters. Wikipedia have been using this for years, eg.:

http://en.wikipedia.org/wiki/?

The one browser whose behaviour is unpredictable and doesn't always display the pretty IRI version is...

...well, you know.

How to keep :active css style after clicking an element

I FIGURED IT OUT. SIMPLE, EFFECTIVE NO jQUERY

We're going to to be using a hidden checkbox.
This example includes one "on click - off click 'hover / active' state"

--

To make content itself clickable:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked ~ label
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<label for="activate-div">
  <div class="my-div">
    //MY DIV CONTENT
  </div>
</label>
_x000D_
_x000D_
_x000D_

To make button change content:

_x000D_
_x000D_
#activate-div{display:none}

.my-div{background-color:#FFF}

#activate-div:checked +
.my-div{background-color:#000}
_x000D_
<input type="checkbox" id="activate-div">
<div class="my-div">
  //MY DIV CONTENT
</div>

<label for="activate-div">
  //MY BUTTON STUFF
</label>
_x000D_
_x000D_
_x000D_

Hope it helps!!

How to tell which commit a tag points to in Git?

This will get you the current SHA1 hash

Abbreviated Commit Hash

git show <tag> --format="%h" --> 42e646e

Commit Hash

git show <tag> --format="%H" --> 42e646ea3483e156c58cf68925545fffaf4fb280

How to Change Margin of TextView

TextView forgot_pswrd = (TextView) findViewById(R.id.ForgotPasswordText);
forgot_pswrd.setOnTouchListener(this);     
LinearLayout.LayoutParams llp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
llp.setMargins(50, 0, 0, 0); // llp.setMargins(left, top, right, bottom);
forgot_pswrd.setLayoutParams(llp);

I did this and it worked perfectly. Maybe as you are giving the value in -ve, that's why your code is not working. You just put this code where you are creating the reference of the view.

How to make links in a TextView clickable?

Use below code:

String html = "<a href=\"http://yourdomain.com\">Your Domain Name</a>"
TextView textview = (TextView) findViewById(R.id.your_textview_id);
textview.setMovementMethod(LinkMovementMethod.getInstance());
textview.setText(Html.fromHtml(html));

How to get the last value of an ArrayList

If you can, swap out the ArrayList for an ArrayDeque, which has convenient methods like removeLast.

Dart: mapping a list (list.map)

I try this same method, but with a different list with more values in the function map. My problem was to forget a return statement. This is very important :)

 bottom: new TabBar(
      controller: _controller,
      isScrollable: true,
      tabs:
        moviesTitles.map((title) { return Tab(text: title)}).toList()
      ,
    ),

How to align an image dead center with bootstrap

You should use

<div class="row fluid-img">
  <img class="col-lg-12 col-xs-12" src="src.png">
</div>

.fluid-img {
    margin: 60px auto;
}

@media( min-width: 768px ){
        .fluid-img {
            max-width: 768px;
        }
}
@media screen and (min-width: 768px) {
        .fluid-img {
            padding-left: 0;
            padding-right: 0;
        }
}

How to format a java.sql.Timestamp(yyyy-MM-dd HH:mm:ss.S) to a date(yyyy-MM-dd HH:mm:ss)

You do not need to use substring at all since your format doesn't hold that info.

SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
String fechaStr = "2013-10-10 10:49:29.10000";  
Date fechaNueva = format.parse(fechaStr);

System.out.println(format.format(fechaNueva)); // Prints 2013-10-10 10:49:29

How do I use popover from Twitter Bootstrap to display an image?

This is what I used.

$('#foo').popover({
    placement : 'bottom',
    title : 'Title',
    content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});

and for the HTML

<b id="foo" rel="popover">text goes here</b>

Send request to curl with post data sourced from a file

If you are using form data to upload file,in which a parameter name must be specified , you can use:

curl -X POST -i -F "parametername=@filename" -F "additional_parm=param2" host:port/xxx

MySQL stored procedure return value

Update your SP and handle exception in it using declare handler with get diagnostics so that you will know if there is an exception. e.g.

CREATE DEFINER=`root`@`localhost` PROCEDURE `validar_egreso`(
IN codigo_producto VARCHAR(100),
IN cantidad INT,
OUT valido INT(11)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
    GET DIAGNOSTICS CONDITION 1
    @p1 = RETURNED_SQLSTATE, @p2 = MESSAGE_TEXT;
    SELECT @p1, @p2;
END
DECLARE resta INT(11);
SET resta = 0;

SELECT (s.stock - cantidad) INTO resta
FROM stock AS s
WHERE codigo_producto = s.codigo;

IF (resta > s.stock_minimo) THEN
    SET valido = 1;
ELSE
    SET valido = -1;
END IF;
SELECT valido;
END

Is there a standardized method to swap two variables in Python?

I know three ways to swap variables, but a, b = b, a is the simplest. There is

XOR (for integers)

x = x ^ y
y = y ^ x
x = x ^ y

Or concisely,

x ^= y
y ^= x
x ^= y

Temporary variable

w = x
x = y
y = w
del w

Tuple swap

x, y = y, x

How to programmatically take a screenshot on Android?

Take screenshot of a view in android.

public static Bitmap getViewBitmap(View v) {
    v.clearFocus();
    v.setPressed(false);

    boolean willNotCache = v.willNotCacheDrawing();
    v.setWillNotCacheDrawing(false);

    int color = v.getDrawingCacheBackgroundColor();
    v.setDrawingCacheBackgroundColor(0);

    if (color != 0) {
        v.destroyDrawingCache();
    }
    v.buildDrawingCache();
    Bitmap cacheBitmap = v.getDrawingCache();
    if (cacheBitmap == null) {
        return null;
    }

    Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);

    v.destroyDrawingCache();
    v.setWillNotCacheDrawing(willNotCache);
    v.setDrawingCacheBackgroundColor(color);

    return bitmap;
}

How can I get the client's IP address in ASP.NET MVC?

I had trouble using the above, and I needed the IP address from a controller. I used the following in the end:

System.Web.HttpContext.Current.Request.UserHostAddress

Passing an array of parameters to a stored procedure

What about using the XML data type instead of passing an array. I find that a better solution and works well in SQL 2005

How to print out the method name and line number and conditionally disable NSLog?

There are a new trick that no answer give. You can use printf instead NSLog. This will give you a clean log:

With NSLog you get things like this:

2011-11-03 13:43:55.632 myApp[3739:207] Hello Word

But with printf you get only:

Hello World

Use this code

#ifdef DEBUG
    #define NSLog(FORMAT, ...) fprintf(stderr,"%s\n", [[NSString stringWithFormat:FORMAT, ##__VA_ARGS__] UTF8String]);
#else
    #define NSLog(...) {}              
#endif

Is there a way to get the git root directory in one command?

As others have noted, the core of the solution is to use git rev-parse --show-cdup. However, there are a few of edge cases to address:

  1. When the cwd already is the root of the working tree, the command yields an empty string.
    Actually it produces an empty line, but command substitution strip off the trailing line break. The final result is an empty string.

    Most answers suggest prepending the output with ./ so that an empty output becomes "./" before it is fed to cd.

  2. When GIT_WORK_TREE is set to a location that is not the parent of the cwd, the output may be an absolute pathname.

    Prepending ./ is wrong in this situation. If a ./ is prepended to an absolute path, it becomes a relative path (and they only refer to the same location if the cwd is the root directory of the system).

  3. The output may contain whitespace.

    This really only applies in the second case, but it has an easy fix: use double quotes around the command substitution (and any subsequent uses of the value).

As other answers have noted, we can do cd "./$(git rev-parse --show-cdup)", but this breaks in the second edge case (and the third edge case if we leave off the double quotes).

Many shells treat cd "" as a no-op, so for those shells we could do cd "$(git rev-parse --show-cdup)" (the double quotes protect the empty string as an argument in the first edge case, and preserve whitespace in the third edge case). POSIX says the result of cd "" is unspecified, so it may be best to avoid making this assumption.

A solution that works in all of the above cases requires a test of some sort. Done explicitly, it might look like this:

cdup="$(git rev-parse --show-cdup)" && test -n "$cdup" && cd "$cdup"

No cd is done for the first edge case.

If it is acceptable to run cd . for the first edge case, then the conditional can be done in the expansion of the parameter:

cdup="$(git rev-parse --show-cdup)" && cd "${cdup:-.}"

How to convert IPython notebooks to PDF and HTML?

You can do it by 1st converting the notebook into HTML and then into PDF format:

Following steps I have implemented on: OS: Ubuntu, Anaconda-Jupyter notebook, Python 3

1 Save Notebook in HTML format:

  1. Start the jupyter notebook that you want to save in HTML format. First save the notebook properly so that HTML file will have a latest saved version of your code/notebook.

  2. Run the following command from the notebook itself:

    !jupyter nbconvert --to html your_notebook_name.ipynb

After execution will create HTML version of your notebook and will save it in the current working directory. You will see one html file will be added into the current directory with your_notebook_name.html name

(your_notebook_name.ipynb --> your_notebook_name.html).

2 Save html as PDF:

  1. Now open that your_notebook_name.html file (click on it). It will be opened in a new tab of your browser.
  2. Now go to print option. From here you can save this file in pdf file format.

Note that from print option we also have the flexibility of selecting a portion of a notebook to save in pdf format.

How to change value of ArrayList element in java

Change it to for(int i=0;i<=9;i++)

nginx 502 bad gateway

When I did sudo /etc/init.d/php-fpm start I got the following error:

Starting php-fpm: [28-Mar-2013 16:18:16] ERROR: [pool www] cannot get uid for user 'apache'

I guess /etc/php-fpm.d/www.conf needs to know the user that the webserver is running as and assumes it's apache when, for nginx, it's actually nginx, and needs to be changed.

Dynamic Height Issue for UITableView Cells (Swift)

For Swift 3 you can use the following:

func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

func tableView(_ tableView: UITableView, estimatedHeightForRowAt indexPath: IndexPath) -> CGFloat {
    return UITableViewAutomaticDimension
}

getting exception "IllegalStateException: Can not perform this action after onSaveInstanceState"

onSaveInstance will be called if a user rotates the screen so that it can load resources associated with the new orientation.

It's possible that this user rotated the screen followed by pressing the back button (because it's also possible that this user fumbled their phone while using your app)

Assign a synthesizable initial value to a reg in Verilog

You can combine the register declaration with initialization.

reg [7:0] data_reg = 8'b10101011;

Or you can use an initial block

reg [7:0] data_reg;
initial data_reg = 8'b10101011;

g++ ld: symbol(s) not found for architecture x86_64

finally solved my problem.

I created a new project in XCode with the sources and changed the C++ Standard Library from the default libc++ to libstdc++ as in this and this.

How can I select all options of multi-select select box on click?

If you are using JQuery 1.9+ then above answers will not work in Firefox.

So here is a code for latest jquery which will work in all browsers.

See live demo

Here is the code

var select_ids = [];
$(document).ready(function(e) {
    $('select#myselect option').each(function(index, element) {
        select_ids.push($(this).val());
    })
});

function selectAll()
{
    $('select#myselect').val(select_ids);
}

function deSelectAll()
{
    $('select#myselect').val('');
}

Hope this will help you... :)

Bootstrap button drop-down inside responsive table not visible because of scroll

We solved this issue here at work by applying a .dropup class to the dropdown when the dropdown is close to the bottom of a table.enter image description here

Hibernate table not mapped error in HQL query

In the Spring configuration typo applicationContext.xml where the sessionFactory configured put this property

<bean id="sessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
  <property name="packagesToScan" value="${package.name}"/>

Difference between getAttribute() and getParameter()

  • getParameter() returns http request parameters. Those passed from the client to the server. For example http://example.com/servlet?parameter=1. Can only return String

  • getAttribute() is for server-side usage only - you fill the request with attributes that you can use within the same request. For example - you set an attribute in a servlet, and read it from a JSP. Can be used for any object, not just string.

Break or return from Java 8 stream forEach?

A return in a lambda equals a continue in a for-each, but there is no equivalent to a break. You can just do a return to continue:

someObjects.forEach(obj -> {
   if (some_condition_met) {
      return;
   }
})

"error: assignment to expression with array type error" when I assign a struct field (C)

You are facing issue in

 s1.name="Paolo";

because, in the LHS, you're using an array type, which is not assignable.

To elaborate, from C11, chapter §6.5.16

assignment operator shall have a modifiable lvalue as its left operand.

and, regarding the modifiable lvalue, from chapter §6.3.2.1

A modifiable lvalue is an lvalue that does not have array type, [...]

You need to use strcpy() to copy into the array.

That said, data s1 = {"Paolo", "Rossi", 19}; works fine, because this is not a direct assignment involving assignment operator. There we're using a brace-enclosed initializer list to provide the initial values of the object. That follows the law of initialization, as mentioned in chapter §6.7.9

Each brace-enclosed initializer list has an associated current object. When no designations are present, subobjects of the current object are initialized in order according to the type of the current object: array elements in increasing subscript order, structure members in declaration order, and the first named member of a union.[....]

TypeScript function overloading

What is function overloading in general?

Function overloading or method overloading is the ability to create multiple functions of the same name with different implementations (Wikipedia)


What is function overloading in JS?

This feature is not possible in JS - the last defined function is taken in case of multiple declarations:

function foo(a1, a2) { return `${a1}, ${a2}` }
function foo(a1) { return `${a1}` } // replaces above `foo` declaration
foo(42, "foo") // "42"

... and in TS?

Overloads are a compile-time construct with no impact on the JS runtime:

function foo(s: string): string // overload #1 of foo
function foo(s: string, n: number): number // overload #2 of foo
function foo(s: string, n?: number): string | number {/* ... */} // foo implementation

A duplicate implementation error is triggered, if you use above code (safer than JS). TS chooses the first fitting overload in top-down order, so overloads are sorted from most specific to most broad.


Method overloading in TS: a more complex example

Overloaded class method types can be used in a similar way to function overloading:

class LayerFactory {
    createFeatureLayer(a1: string, a2: number): string
    createFeatureLayer(a1: number, a2: boolean, a3: string): number
    createFeatureLayer(a1: string | number, a2: number | boolean, a3?: string)
        : number | string { /*... your implementation*/ }
}

const fact = new LayerFactory()
fact.createFeatureLayer("foo", 42) // string
fact.createFeatureLayer(3, true, "bar") // number

The vastly different overloads are possible, as the function implementation is compatible to all overload signatures - enforced by the compiler.

More infos:

JavaScript associative array to JSON

Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:

let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
    tempArr.push(objectArr[element]);
});

let json = JSON.stringify(tempArr);

Extend contigency table with proportions (percentages)

Here's a tidyverse version:

library(tidyverse)
data(diamonds)

(as.data.frame(table(diamonds$cut)) %>% rename(Count=1,Freq=2) %>% mutate(Perc=100*Freq/sum(Freq)))

Or if you want a handy function:

getPercentages <- function(df, colName) {
  df.cnt <- df %>% select({{colName}}) %>% 
    table() %>%
    as.data.frame() %>% 
    rename({{colName}} :=1, Freq=2) %>% 
    mutate(Perc=100*Freq/sum(Freq))
}

Now you can do:

diamonds %>% getPercentages(cut)

or this:

df=diamonds %>% group_by(cut) %>% group_modify(~.x %>% getPercentages(clarity))
ggplot(df,aes(x=clarity,y=Perc))+geom_col()+facet_wrap(~cut)

Bind a function to Twitter Bootstrap Modal Close

I've seen many answers regarding the bootstrap events such as hide.bs.modal which triggers when the modal closes.

There's a problem with those events: any popups in the modal (popovers, tooltips, etc) will trigger that event.

There is another way to catch the event when a modal closes.

$(document).on('hidden','#modal:not(.in)', function(){} );

Bootstrap uses the in class when the modal is open. It is very important to use the hidden event since the class in is still defined when the event hideis triggered.

This solution will not work in IE8 since IE8 does not support the Jquery :not() selector.

Find out the history of SQL queries

For recent SQL:

select * from v$sql

For history:

select * from dba_hist_sqltext

Send password when using scp to copy files from one server to another

Here is how I resolved it.

It is not the most secure way however it solved my problem as security was not an issue on internal servers.

Create a new file say password.txt and store the password for the server where the file will be pasted. Save this to a location on the host server.

scp -W location/password.txt copy_file_location paste_file_location

Cheers!

Run cURL commands from Windows console

From Windows Command Prompt, run curl through Git Bash

"C:\\Users\\sizu\\AppData\\Local\\Programs\\Git\\bin\\sh.exe" --login -i -c "curl https://www.google.com"