Programs & Examples On #Agile project management

Agile project management is an alternative to traditional project management. **IMPORTANT NOTE:** Questions about project management are off-topic. Please ask on Project Management SE instead.

Difference between PACKETS and FRAMES

Packets and Frames are the names given to Protocol data units (PDUs) at different network layers

  • Segments/Datagrams are units of data in the Transport Layer.

    In the case of the internet, the term Segment typically refers to TCP, while Datagram typically refers to UDP. However Datagram can also be used in a more general sense and refer to other layers (link):

    Datagram

    A self-contained, independent entity of data carrying sufficient information to be routed from the source to the destination computer without reliance on earlier exchanges between this source and destination computer andthe transporting network.

  • Packets are units of data in the Network Layer (IP in case of the Internet)

  • Frames are units of data in the Link Layer (e.g. Wifi, Bluetooth, Ethernet, etc).

enter image description here

How to clear the cache of nginx?

If you want to clear the cache of specific files then you can use the proxy_cache_bypass directive. This is how you do it

location / {
    proxy_cache_bypass $cookie_nocache $arg_nocache;
    # ...
}

Now if you want bypass the cache you access the file by passing the nocache parameter

http://www.example.com/app.css?nocache=true

Excel Calculate the date difference from today from a cell of "7/6/2012 10:26:42"

=ROUND((TODAY()-A1)/365,0) will provide number of years between date in cell A1 and today's date

How to remove the first Item from a list?

You can also use list.remove(a[0]) to pop out the first element in the list.

>>>> a=[1,2,3,4,5]
>>>> a.remove(a[0])
>>>> print a
>>>> [2,3,4,5]

Change URL without refresh the page

When you use a function ...

<p onclick="update_url('/en/step2');">Link</p>

<script>
function update_url(url) {
    history.pushState(null, null, url);
}
</script>

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

Out of the box Swift Mailer can't do STARTTLS, however some nice guys have written a patch for it.

I found patching it was a bit of a chore (probably went about it the wrong way), so have zipped it up ready for download here: Swift Mailer with STARTTLS

Emulator in Android Studio doesn't start

I'd like to post a link to this answer as it might help out any persons in this thread running into issues starting a virtual device with more then 768 mb of memory; How to make an AVD with > 768MB RAM To emulate Galaxy devices

Byte Array to Hex String

Or, if you are a fan of functional programming:

>>> a = [133, 53, 234, 241]
>>> "".join(map(lambda b: format(b, "02x"), a))
8535eaf1
>>>

Turn a number into star rating display using jQuery and CSS

Here's a solution for you, using only one very tiny and simple image and one automatically generated span element:

CSS

span.stars, span.stars span {
    display: block;
    background: url(stars.png) 0 -16px repeat-x;
    width: 80px;
    height: 16px;
}

span.stars span {
    background-position: 0 0;
}

Image

alt text
(source: ulmanen.fi)

Note: do NOT hotlink to the above image! Copy the file to your own server and use it from there.

jQuery

$.fn.stars = function() {
    return $(this).each(function() {
        // Get the value
        var val = parseFloat($(this).html());
        // Make sure that the value is in 0 - 5 range, multiply to get width
        var size = Math.max(0, (Math.min(5, val))) * 16;
        // Create stars holder
        var $span = $('<span />').width(size);
        // Replace the numerical value with stars
        $(this).html($span);
    });
}

If you want to restrict the stars to only half or quarter star sizes, add one of these rows before the var size row:

val = Math.round(val * 4) / 4; /* To round to nearest quarter */
val = Math.round(val * 2) / 2; /* To round to nearest half */

HTML

<span class="stars">4.8618164</span>
<span class="stars">2.6545344</span>
<span class="stars">0.5355</span>
<span class="stars">8</span>

Usage

$(function() {
    $('span.stars').stars();
});

Output

Image from fugue icon set (www.pinvoke.com)
(source: ulmanen.fi)

Demo

http://www.ulmanen.fi/stuff/stars.php

This will probably suit your needs. With this method you don't have to calculate any three quarter or whatnot star widths, just give it a float and it'll give you your stars.


A small explanation on how the stars are presented might be in order.

The script creates two block level span elements. Both of the spans initally get a size of 80px * 16px and a background image stars.png. The spans are nested, so that the structure of the spans looks like this:

<span class="stars">
    <span></span>
</span>

The outer span gets a background-position of 0 -16px. That makes the gray stars in the outer span visible. As the outer span has height of 16px and repeat-x, it will only show 5 gray stars.

The inner span on the other hand has a background-position of 0 0 which makes only the yellow stars visible.

This would of course work with two separate imagefiles, star_yellow.png and star_gray.png. But as the stars have a fixed height, we can easily combine them into one image. This utilizes the CSS sprite technique.

Now, as the spans are nested, they are automatically overlayed over each other. In the default case, when the width of both spans is 80px, the yellow stars completely obscure the grey stars.

But when we adjust the width of the inner span, the width of the yellow stars decreases, revealing the gray stars.

Accessibility-wise, it would have been wiser to leave the float number inside the inner span and hide it with text-indent: -9999px, so that people with CSS turned off would at least see the floating point number instead of the stars.

Hopefully that made some sense.


Updated 2010/10/22

Now even more compact and harder to understand! Can also be squeezed down to a one liner:

$.fn.stars = function() {
    return $(this).each(function() {
        $(this).html($('<span />').width(Math.max(0, (Math.min(5, parseFloat($(this).html())))) * 16));
    });
}

How to open SharePoint files in Chrome/Firefox

You can use web-based protocol handlers for the links as per https://sharepoint.stackexchange.com/questions/70178/how-does-sharepoint-2013-enable-editing-of-documents-for-chrome-and-fire-fox

Basically, just prepend ms-word:ofe|u| to the links to your SharePoint hosted Word documents.

Parser Error Message: Could not load type 'TestMvcApplication.MvcApplication'

After a long hard look I came accross the real issue here.

The assemblies were corrupted by the FTP client I used to upload the files to a hosted environmet.

I changed my FTP client and all is working as intended.

Run exe file with parameters in a batch file

This should work:

start "" "c:\program files\php\php.exe" D:\mydocs\mp\index.php param1 param2

The start command interprets the first argument as a window title if it contains spaces. In this case, that means start considers your whole argument a title and sees no command. Passing "" (an empty title) as the first argument to start fixes the problem.

What does the red exclamation point icon in Eclipse mean?

The solution that worked for me is the following one given by Steve Hansen Smythe. I am just pasting it here. Thanks Steve.

"I found another scenario in which the red exclamation mark might appear. I copied a directory from one project to another. This directory included a hidden .svn directory (the original project had been committed to version control). When I checked my new project into SVN, the copied directory still contained the old SVN information, incorrectly identifying itself as an element in its original project.

I discovered the problem by looking at the Properties for the directory, selecting SVN Info, and reviewing the Resource URL. I fixed the problem by deleting the hidden .svn directory for my copied directory and refreshing my project. The red exclamation mark disappeared, and I was able to check in the directory and its contents correctly."

Update TextView Every Second

Use TextSwitcher (for nice text transition animation) and timer instead.

How to get the selected value from RadioButtonList?

The ASPX code will look something like this:

 <asp:RadioButtonList ID="rblist1" runat="server">

    <asp:ListItem Text ="Item1" Value="1" />
    <asp:ListItem Text ="Item2" Value="2" />
    <asp:ListItem Text ="Item3" Value="3" />
    <asp:ListItem Text ="Item4" Value="4" />

    </asp:RadioButtonList>

    <asp:Button ID="btn1" runat="server" OnClick="Button1_Click" Text="select value" />

And the code behind:

protected void Button1_Click(object sender, EventArgs e)
        {
            string selectedValue = rblist1.SelectedValue;
            Response.Write(selectedValue);
        }

Anaconda / Python: Change Anaconda Prompt User Path

If you want to access folder you specified using Anaconda Prompt, try typing

cd C:\Users\u354590

Merge or combine by rownames

Not perfect but close:

newcol<-sapply(rownames(t), function(rn){z[match(rn, rownames(z)), 5]})
cbind(data.frame(t), newcol)

using .join method to convert array to string without commas

The .join() method has a parameter for the separator string. If you want it to be empty instead of the default comma, use

arr.join("");

ERROR: Error 1005: Can't create table (errno: 121)

Foreign Key Constraint Names Have to be Unique Within a Database

Both @Dorvalla’s answer and this blog post mentioned above pointed me into the right direction to fix the problem for myself; quoting from the latter:

If the table you're trying to create includes a foreign key constraint, and you've provided your own name for that constraint, remember that it must be unique within the database.

I wasn’t aware of that. I have changed my foreign key constraint names according to the following schema which appears to be used by Ruby on Rails applications, too:

<TABLE_NAME>_<FOREIGN_KEY_COLUMN_NAME>_fk

For the OP’s table this would be Link_lession_id_fk, for example.

Installing Bower on Ubuntu

At Least from Ubuntu 12.04, an old version (0.6.x) of Node is in the standard repository. To install, just run:

sudo apt-get install nodejs

NPM comes with latest version of nodejs. Once you have that, then run

sudo npm install bower -g

Should be good to go after that. You may need to run some updates, but it should be fairly straight forward.

split string only on first instance of specified character

Mark F's solution is awesome but it's not supported by old browsers. Kennebec's solution is awesome and supported by old browsers but doesn't support regex.

So, if you're looking for a solution that splits your string only once, that is supported by old browsers and supports regex, here's my solution:

_x000D_
_x000D_
String.prototype.splitOnce = function(regex)_x000D_
{_x000D_
    var match = this.match(regex);_x000D_
    if(match)_x000D_
    {_x000D_
        var match_i = this.indexOf(match[0]);_x000D_
        _x000D_
        return [this.substring(0, match_i),_x000D_
        this.substring(match_i + match[0].length)];_x000D_
    }_x000D_
    else_x000D_
    { return [this, ""]; }_x000D_
}_x000D_
_x000D_
var str = "something/////another thing///again";_x000D_
_x000D_
alert(str.splitOnce(/\/+/)[1]);
_x000D_
_x000D_
_x000D_

How to convert a NumPy array to PIL image applying matplotlib colormap

  • input = numpy_image
  • np.unit8 -> converts to integers
  • convert('RGB') -> converts to RGB
  • Image.fromarray -> returns an image object

    from PIL import Image
    import numpy as np
    
    PIL_image = Image.fromarray(np.uint8(numpy_image)).convert('RGB')
    
    PIL_image = Image.fromarray(numpy_image.astype('uint8'), 'RGB')
    

How to get last inserted id?

You can also use a call to SCOPE_IDENTITY in SQL Server.

Is it possible to use 'else' in a list comprehension?

If you want an else you don't want to filter the list comprehension, you want it to iterate over every value. You can use true-value if cond else false-value as the statement instead, and remove the filter from the end:

table = ''.join(chr(index) if index in ords_to_keep else replace_with for index in xrange(15))

The term 'Get-ADUser' is not recognized as the name of a cmdlet

If the ActiveDirectory module is present add

import-module activedirectory

before your code.

To check if exist try:

get-module -listavailable

ActiveDirectory module is default present in windows server 2008 R2, install it in this way:

Import-Module ServerManager
Add-WindowsFeature RSAT-AD-PowerShell

For have it to work you need at least one DC in the domain as windows 2008 R2 and have Active Directory Web Services (ADWS) installed on it.

For Windows Server 2008 read here how to install it

plot a circle with pyplot

Similarly to scatter plot you can also use normal plot with circle line style. Using markersize parameter you can adjust radius of a circle:

import matplotlib.pyplot as plt

plt.plot(200, 2, 'o', markersize=7)

How to hide a TemplateField column in a GridView

This can be another way to do it and validate nulls

DataControlField dataControlField = UsersGrid.Columns.Cast<DataControlField>().SingleOrDefault(x => x.HeaderText == "Email");
            if (dataControlField != null)
                dataControlField.Visible = false;

UIDevice uniqueIdentifier deprecated - What to do now?

You may want to consider using OpenUDID which is a drop-in replacement for the deprecated UDID.

Basically, to match the UDID, the following features are required:

  1. unique or sufficiently unique (a low probability collision is probably very acceptable)
  2. persistence across reboots, restores, uninstalls
  3. available across apps of different vendors (useful to acquire users via CPI networks) -

OpenUDID fulfills the above and even has a built-in Opt-Out mechanism for later consideration.

Check http://OpenUDID.org it points to the corresponding GitHub. Hope this helps!

As a side note, I would shy away from any MAC address alternative. While the MAC address appears like a tempting and universal solution, be sure that this low hanging fruit is poisoned. The MAC address is very sensitive, and Apple may very well deprecate access to this one before you can even say "SUBMIT THIS APP"... the MAC network address is used to authenticate certain devices on private lans (WLANs) or other virtual private networks (VPNs). .. it's even more sensitive than the former UDID!

CMD: How do I recursively remove the "Hidden"-Attribute of files and directories

To make a batch file for its current directory and sub directories:

cd %~dp0
attrib -h -r -s /s /d /l *.*

Delete rows from multiple tables using a single query (SQL Express 2005) with a WHERE condition

DELETE TB1, TB2
    FROM customer_details
        LEFT JOIN customer_booking on TB1.cust_id = TB2.fk_cust_id
    WHERE TB1.cust_id = $id

Gitignore not working

I used something to generate common .gitignore for me and I ran into this. After reading @Ozesh answer I opened in VS Code because it has a nice indicator at bottom right showing type of line endings. It was LF so I converted to CRLF as suggested but no dice.

Then I looked next to the line endings and noticed it was saved using UTF16. So I resaved using UTF8 encoding an voila, it worked. I didn't think the CRLF mattered so I changed it back to LF to be sure and it still worked.

Of course this wasn't OPs issue since he had already committed the files so they were already indexed, but thought I'd share in case someone else stumbles across this.

TLDR; If you haven't already committed the files and .gitignore still isn't being respected then check file encoding and, make sure its UTF8 and if that doesn't work then maybe try messing with line endings.

How to convert a Hibernate proxy to a real entity object

The way I recommend with JPA 2 :

Object unproxied  = entityManager.unwrap(SessionImplementor.class).getPersistenceContext().unproxy(proxy);

Calculating the SUM of (Quantity*Price) from 2 different tables

I think this is along the lines of what you're looking for. It appears that you want to see the orderid, the subtotal for each item in the order and the total amount for the order.

select o1.orderID, o1.subtotal, sum(o2.UnitPrice * o2.Quantity) as order_total from
(
    select o.orderID, o.price * o.qty as subtotal
    from product p inner join orderitem o on p.ProductID= o.productID
    where o.orderID = @OrderId
)as o1
inner join orderitem o2 on o1.OrderID = o2.OrderID
group by o1.orderID, o1.subtotal

Java List.add() UnsupportedOperationException

You must initialize your List seeAlso :

List<String> seeAlso = new Vector<String>();

or

List<String> seeAlso = new ArrayList<String>();

Import / Export database with SQL Server Server Management Studio

for Microsoft SQL Server Management Studio 2012,2008.. First Copy your database file .mdf and log file .ldf & Paste in your sql server install file in Programs Files->Microsoft SQL Server->MSSQL10.SQLEXPRESS->MSSQL->DATA. Then open Microsoft Sql Server . Right Click on Databases -> Select Attach...option.

Store mysql query output into a shell variable

If you have particular database name and a host on which you want the query to be executed then follow below query:

outputofquery=$(mysql -u"$dbusername" -p"$dbpassword" -h"$dbhostname" -e "SELECT A, B, C FROM table_a;" $dbname)

So to run the mysql queries you need to install mysql client on linux

What's the fastest way of checking if a point is inside a polygon in python

Comparison of different methods

I found other methods to check if a point is inside a polygon (here). I tested two of them only (is_inside_sm and is_inside_postgis) and the results were the same as the other methods.

Thanks to @epifanio, I parallelized the codes and compared them with @epifanio and @user3274748 (ray_tracing_numpy) methods. Note that both methods had a bug so I fixed them as shown in their codes below.

One more thing that I found is that the code provided for creating a polygon does not generate a closed path np.linspace(0,2*np.pi,lenpoly)[:-1]. As a result, the codes provided in above GitHub repository may not work properly. So It's better to create a closed path (first and last points should be the same).

Codes

Method 1: parallelpointinpolygon

from numba import jit, njit
import numba
import numpy as np 

@jit(nopython=True)
def pointinpolygon(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in numba.prange(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside


@njit(parallel=True)
def parallelpointinpolygon(points, polygon):
    D = np.empty(len(points), dtype=numba.boolean) 
    for i in numba.prange(0, len(D)):   #<-- Fixed here, must start from zero
        D[i] = pointinpolygon(points[i,0], points[i,1], polygon)
    return D  

Method 2: ray_tracing_numpy_numba

@jit(nopython=True)
def ray_tracing_numpy_numba(points,poly):
    x,y = points[:,0], points[:,1]
    n = len(poly)
    inside = np.zeros(len(x),np.bool_)
    p2x = 0.0
    p2y = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        idx = np.nonzero((y > min(p1y,p2y)) & (y <= max(p1y,p2y)) & (x <= max(p1x,p2x)))[0]
        if len(idx):    # <-- Fixed here. If idx is null skip comparisons below.
            if p1y != p2y:
                xints = (y[idx]-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
            if p1x == p2x:
                inside[idx] = ~inside[idx]
            else:
                idxx = idx[x[idx] <= xints]
                inside[idxx] = ~inside[idxx]    

        p1x,p1y = p2x,p2y
    return inside 

Method 3: Matplotlib contains_points

path = mpltPath.Path(polygon,closed=True)  # <-- Very important to mention that the path 
                                           #     is closed (default is false)

Method 4: is_inside_sm (got it from here)

@jit(nopython=True)
def is_inside_sm(polygon, point):
    length = len(polygon)-1
    dy2 = point[1] - polygon[0][1]
    intersections = 0
    ii = 0
    jj = 1

    while ii<length:
        dy  = dy2
        dy2 = point[1] - polygon[jj][1]

        # consider only lines which are not completely above/bellow/right from the point
        if dy*dy2 <= 0.0 and (point[0] >= polygon[ii][0] or point[0] >= polygon[jj][0]):

            # non-horizontal line
            if dy<0 or dy2<0:
                F = dy*(polygon[jj][0] - polygon[ii][0])/(dy-dy2) + polygon[ii][0]

                if point[0] > F: # if line is left from the point - the ray moving towards left, will intersect it
                    intersections += 1
                elif point[0] == F: # point on line
                    return 2

            # point on upper peak (dy2=dx2=0) or horizontal line (dy=dy2=0 and dx*dx2<=0)
            elif dy2==0 and (point[0]==polygon[jj][0] or (dy==0 and (point[0]-polygon[ii][0])*(point[0]-polygon[jj][0])<=0)):
                return 2

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections & 1  


@njit(parallel=True)
def is_inside_sm_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_sm(polygon,points[i])
    return D  

Method 5: is_inside_postgis (got it from here)

@jit(nopython=True)
def is_inside_postgis(polygon, point):
    length = len(polygon)
    intersections = 0

    dx2 = point[0] - polygon[0][0]
    dy2 = point[1] - polygon[0][1]
    ii = 0
    jj = 1

    while jj<length:
        dx  = dx2
        dy  = dy2
        dx2 = point[0] - polygon[jj][0]
        dy2 = point[1] - polygon[jj][1]

        F =(dx-dx2)*dy - dx*(dy-dy2);
        if 0.0==F and dx*dx2<=0 and dy*dy2<=0:
            return 2;

        if (dy>=0 and dy2<0) or (dy2>=0 and dy<0):
            if F > 0:
                intersections += 1
            elif F < 0:
                intersections -= 1

        ii = jj
        jj += 1

    #print 'intersections =', intersections
    return intersections != 0  


@njit(parallel=True)
def is_inside_postgis_parallel(points, polygon):
    ln = len(points)
    D = np.empty(ln, dtype=numba.boolean) 
    for i in numba.prange(ln):
        D[i] = is_inside_postgis(polygon,points[i])
    return D  

Benchmark

enter image description here

Timing for 10 million points:

parallelpointinpolygon Elapsed time:      4.0122294425964355
Matplotlib contains_points Elapsed time: 14.117807388305664
ray_tracing_numpy_numba Elapsed time:     7.908452272415161
sm_parallel Elapsed time:                 0.7710440158843994
is_inside_postgis_parallel Elapsed time:  2.131121873855591

Here is the code.

import matplotlib.pyplot as plt
import matplotlib.path as mpltPath
from time import time
import numpy as np

np.random.seed(2)

time_parallelpointinpolygon=[]
time_mpltPath=[]
time_ray_tracing_numpy_numba=[]
time_is_inside_sm_parallel=[]
time_is_inside_postgis_parallel=[]
n_points=[]

for i in range(1, 10000002, 1000000): 
    n_points.append(i)
    
    lenpoly = 100
    polygon = [[np.sin(x)+0.5,np.cos(x)+0.5] for x in np.linspace(0,2*np.pi,lenpoly)]
    polygon = np.array(polygon)
    N = i
    points = np.random.uniform(-1.5, 1.5, size=(N, 2))
    
    
    #Method 1
    start_time = time()
    inside1=parallelpointinpolygon(points, polygon)
    time_parallelpointinpolygon.append(time()-start_time)

    # Method 2
    start_time = time()
    path = mpltPath.Path(polygon,closed=True)
    inside2 = path.contains_points(points)
    time_mpltPath.append(time()-start_time)

    # Method 3
    start_time = time()
    inside3=ray_tracing_numpy_numba(points,polygon)
    time_ray_tracing_numpy_numba.append(time()-start_time)

    # Method 4
    start_time = time()
    inside4=is_inside_sm_parallel(points,polygon)
    time_is_inside_sm_parallel.append(time()-start_time)

    # Method 5
    start_time = time()
    inside5=is_inside_postgis_parallel(points,polygon)
    time_is_inside_postgis_parallel.append(time()-start_time)


    
plt.plot(n_points,time_parallelpointinpolygon,label='parallelpointinpolygon')
plt.plot(n_points,time_mpltPath,label='mpltPath')
plt.plot(n_points,time_ray_tracing_numpy_numba,label='ray_tracing_numpy_numba')
plt.plot(n_points,time_is_inside_sm_parallel,label='is_inside_sm_parallel')
plt.plot(n_points,time_is_inside_postgis_parallel,label='is_inside_postgis_parallel')
plt.xlabel("N points")
plt.ylabel("time (sec)")
plt.legend(loc = 'best')
plt.show()

CONCLUSION

The fastest algorithms are:

1- is_inside_sm_parallel

2- is_inside_postgis_parallel

3- parallelpointinpolygon (@epifanio)

Make copy of an array

You can try using Arrays.copyOf() in Java

int[] a = new int[5]{1,2,3,4,5};
int[] b = Arrays.copyOf(a, a.length);

How to check if a character in a string is a digit or letter

import java.util.*;

public class String_char 
{

    public static void main(String arg[]){   

        Scanner in = new Scanner(System.in);
        System.out.println("Enter the value");
        String data;
        data = in.next();

        int len = data.length();
        for (int i = 0 ; i < len ; i++){
            char ch = data.charAt(i);

            if ((ch >= '0' && ch <= '9')){
                System.out.println("Number ");
            }
            else if((ch >= 'a' && ch <= 'z') || (ch >= 'A' && ch <= 'Z')){
            System.out.println("Character");
            }
            else{
                System.out.println("Symbol");
             }
        }
    } 
}

How do I check if a property exists on a dynamic anonymous type in c#?

This works for anonymous types, ExpandoObject, Nancy.DynamicDictionary or anything else that can be cast to IDictionary<string, object>.

    public static bool PropertyExists(dynamic obj, string name) {
        if (obj == null) return false;
        if (obj is IDictionary<string, object> dict) {
            return dict.ContainsKey(name);
        }
        return obj.GetType().GetProperty(name) != null;
    }

Implement paging (skip / take) functionality with this query

SQL 2008

Radim Köhler's answer works, but here is a shorter version:

select top 20 * from
(
select *,
ROW_NUMBER() OVER (ORDER BY columnid) AS ROW_NUM
from tablename
) x
where ROW_NUM>10

Source: https://forums.asp.net/post/4033909.aspx

How do I convert a byte array to Base64 in Java?

In case you happen to be using Spring framework along with java, there is an easy way around.

  1. Import the following.

    import org.springframework.util.Base64Utils;
  2. Convert like this.

    byte[] bytearr ={0,1,2,3,4};
    String encodedText = Base64Utils.encodeToString(bytearr);
    

    To decode you can use the decodeToString method of the Base64Utils class.

Android button with icon and text

You can use the Material Components Library and the MaterialButton component.
Use the app:icon and app:iconGravity="start" attributes.

Something like:

  <com.google.android.material.button.MaterialButton
        style="@style/Widget.MaterialComponents.Button.Icon"
        app:icon="@drawable/..."
        app:iconGravity="start"
        ../>

enter image description here

AngularJS - Trigger when radio button is selected

Should use ngChange instead of ngClick if trigger source is not from click.

Is the below what you want ? what exactly doesn't work in your case ?

var myApp = angular.module('myApp', []);

function MyCtrl($scope) {
    $scope.value = "none" ;
    $scope.isChecked = false;
    $scope.checkStuff = function () {
        $scope.isChecked = !$scope.isChecked;
    }
}


<div ng-controller="MyCtrl">
    <input type="radio" ng-model="value" value="one" ng-change="checkStuff()" />
    <span> {{value}} isCheck:{{isChecked}} </span>
</div>   

How to solve WAMP and Skype conflict on Windows 7?

I think it is better to change default port of Skype.

Open skype. Go to Tools, Options, Connections, change the port.

How to prevent ENTER keypress to submit a web form?

Simply add this attribute to your FORM tag:

onsubmit="return gbCanSubmit;"

Then, in your SCRIPT tag, add this:

var gbCanSubmit = false;

Then, when you make a button or for any other reason (like in a function) you finally permit a submit, simply flip the global boolean and do a .submit() call, similar to this example:

function submitClick(){

  // error handler code goes here and return false if bad data

  // okay, proceed...
  gbCanSubmit = true;
  $('#myform').submit(); // jQuery example

}

How to convert R Markdown to PDF?

I think you really need pandoc, which great software was designed and built just for this task :) Besides pdf, you could convert your md file to e.g. docx or odt among others.

Well, installing an up-to-date version of Pandoc might be challanging on Linux (as you would need the entire haskell-platform?to build from the sources), but really easy on Windows/Mac with only a few megabytes of download.

If you have the brewed/knitted markdown file you can just call pandoc in e.g bash or with the system function within R. A POC demo of that latter is implemented in the ?andoc.convert function of my little package (which you must be terribly bored of as I try to point your attention there at every opportunity).

Android: How to add R.raw to project?

Using IntelliJ Idea:

1) Invalidate Caches, and 2) right click on resources, New Resources directory, type = raw 3) build

note in step 2: I was concerned that simply adding a raw directory wouldn't be enough...

How can I use grep to show just filenames on Linux?

Your question How can I just get the file-names (with paths)

Your syntax example find . -iname "*php" -exec grep -H myString {} \;

My Command suggestion

sudo find /home -name *.php

The output from this command on my Linux OS:

compose-sample-3/html/mail/contact_me.php

As you require the filename with path, enjoy!

Send POST request with JSON data using Volley

JsonObjectRequest actually accepts JSONObject as body.

From this blog article,

final String url = "some/url";
final JSONObject jsonBody = new JSONObject("{\"type\":\"example\"}");

new JsonObjectRequest(url, jsonBody, new Response.Listener<JSONObject>() { ... });

Here is the source code and JavaDoc (@param jsonRequest):

/**
 * Creates a new request.
 * @param method the HTTP method to use
 * @param url URL to fetch the JSON from
 * @param jsonRequest A {@link JSONObject} to post with the request. Null is allowed and
 *   indicates no parameters will be posted along with request.
 * @param listener Listener to receive the JSON response
 * @param errorListener Error listener, or null to ignore errors.
 */
public JsonObjectRequest(int method, String url, JSONObject jsonRequest,
        Listener<JSONObject> listener, ErrorListener errorListener) {
    super(method, url, (jsonRequest == null) ? null : jsonRequest.toString(), listener,
                errorListener);
}

Java: Convert a String (representing an IP) to InetAddress

From the documentation of InetAddress.getByName(String host):

The host name can either be a machine name, such as "java.sun.com", or a textual representation of its IP address. If a literal IP address is supplied, only the validity of the address format is checked.

So you can use it.

Using curl to upload POST data with files

Catching the user id as path variable (recommended):

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "[email protected]" http://mysuperserver/media/1234/upload/

Catching the user id as part of the form:

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "[email protected];userid=1234" http://mysuperserver/media/upload/

or:

curl -i -X POST -H "Content-Type: multipart/form-data" 
-F "[email protected]" -F "userid=1234" http://mysuperserver/media/upload/

ImportError: numpy.core.multiarray failed to import

Just fixed this issue. import c2 or import numpy was not working. Uninstalled the most current version of numpy. Tried to install numpy==1.15.2 just like specified above, did not work. Tried numpy==1.19.3 IT worked. I guess not all versions work perfectly with all versions of python and dependencies. So keep uninstalling and install one that works.

Set a form's action attribute when submitting?

You can also set onSubmit attribute's value in form tag. You can set its value using Javascript.

Something like this:

<form id="whatever" name="whatever" onSubmit="return xyz();">
    Here is your entire form
    <input type="submit">
</form>;

<script type=text/javascript>
function xyz() {
  document.getElementById('whatever').action = 'whatever you want'
}
</script>

Remember that onSubmit has higher priority than action attribute. So whenever you specify onSubmit value, that operation will be performed first and then the form will move to action.

Ping site and return result in PHP

function urlExists($url=NULL)  
{  
    if($url == NULL) return false;  
    $ch = curl_init($url);  
    curl_setopt($ch, CURLOPT_TIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);  
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);  
    $data = curl_exec($ch);  
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);  
    curl_close($ch);  
    if($httpcode>=200 && $httpcode<300){  
        return true;  
    } else {  
        return false;  
    }  
}  

This was grabbed from this post on how to check if a URL exists. Because Twitter should provide an error message above 300 when it is in maintenance, or a 404, this should work perfectly.

Centering controls within a form in .NET (Winforms)?

myControl.Left = (this.ClientSize.Width - myControl.Width) / 2 ;
myControl.Top = (this.ClientSize.Height - myControl.Height) / 2;

How do I get a list of all subdomains of a domain?

You can only do this if you are connecting to a DNS server for the domain -and- AXFR is enabled for your IP address. This is the mechanism that secondary systems use to load a zone from the primary. In the old days, this was not restricted, but due to security concerns, most primary name servers have a whitelist of: secondary name servers + a couple special systems.

If the nameserver you are using allows this then you can use dig or nslookup.

For example:

#nslookup

>ls domain.com

NOTE: because nslookup is being deprecated for dig and other newere tools, some versions of nslookup do not support "ls", most notably Mac OS X's bundled version.

Get value of a merged cell of an excel from its cell address in vba

Even if it is really discouraged to use merge cells in Excel (use Center Across Selection for instance if needed), the cell that "contains" the value is the one on the top left (at least, that's a way to express it).

Hence, you can get the value of merged cells in range B4:B11 in several ways:

  • Range("B4").Value
  • Range("B4:B11").Cells(1).Value
  • Range("B4:B11").Cells(1,1).Value

You can also note that all the other cells have no value in them. While debugging, you can see that the value is empty.

Also note that Range("B4:B11").Value won't work (raises an execution error number 13 if you try to Debug.Print it) because it returns an array.

Sorting HashMap by values

package SortedSet;

import java.util.*;

public class HashMapValueSort {
public static void main(String[] args){
    final Map<Integer, String> map = new HashMap<Integer,String>();
    map.put(4,"Mango");
    map.put(3,"Apple");
    map.put(5,"Orange");
    map.put(8,"Fruits");
    map.put(23,"Vegetables");
    map.put(1,"Zebra");
    map.put(5,"Yellow");
    System.out.println(map);
    final HashMapValueSort sort = new HashMapValueSort();
    final Set<Map.Entry<Integer, String>> entry = map.entrySet();
    final Comparator<Map.Entry<Integer, String>> comparator = new Comparator<Map.Entry<Integer, String>>() {
        @Override
        public int compare(Map.Entry<Integer, String> o1, Map.Entry<Integer, String> o2) {
            String value1 = o1.getValue();
            String value2 = o2.getValue();
            return value1.compareTo(value2);
        }
    };
    final SortedSet<Map.Entry<Integer, String>> sortedSet = new TreeSet(comparator);
    sortedSet.addAll(entry);
    final Map<Integer,String> sortedMap =  new LinkedHashMap<Integer, String>();
    for(Map.Entry<Integer, String> entry1 : sortedSet ){
        sortedMap.put(entry1.getKey(),entry1.getValue());
    }
    System.out.println(sortedMap);
}
}

C string append

strcpy(str1+strlen(str1), str2);

Git: How to remove file from index without deleting files from any repository

I do not think a Git commit can record an intention like “stop tracking this file, but do not delete it”.

Enacting such an intention will require intervention outside Git in any repositories that merge (or rebase onto) a commit that deletes the file.


Save a Copy, Apply Deletion, Restore

Probably the easiest thing to do is to tell your downstream users to save a copy of the file, pull your deletion, then restore the file. If they are pulling via rebase and are ‘carrying’ modifications to the file, they will get conflicts. To resolve such conflicts, use git rm foo.conf && git rebase --continue (if the conflicting commit has changes besides those to the removed file) or git rebase --skip (if the conflicting commit has only changed to the removed file).

Restore File as Untracked After Pulling a Commit That Deletes It

If they have already pulled your deletion commit, they can still recover the previous version of the file with git show:

git show @{1}:foo.conf >foo.conf

Or with git checkout (per comment by William Pursell; but remember to re-remove it from the index!):

git checkout @{1} -- foo.conf && git rm --cached foo.conf

If they have taken other actions since pulling your deletion (or they are pulling with rebase into a detached HEAD), they may need something other than @{1}. They could use git log -g to find the commit just before they pulled your deletion.


In a comment, you mention that the file you want to “untrack, but keep” is some kind of configuration file that is required for running the software (directly out of a repository).

Keep File as a ‘Default’ and Manually/Automatically Activate It

If it is not completely unacceptable to continue to maintain the configuration file's content in the repository, you might be able to rename the tracked file from (e.g.) foo.conf to foo.conf.default and then instruct your users to cp foo.conf.default foo.conf after applying the rename commit. Or, if the users already use some existing part of the repository (e.g. a script or some other program configured by content in the repository (e.g. Makefile or similar)) to launch/deploy your software, you could incorporate a defaulting mechanism into the launch/deploy process:

test -f foo.conf || test -f foo.conf.default &&
    cp foo.conf.default foo.conf

With such a defaulting mechanism in place, users should be able to pull a commit that renames foo.conf to foo.conf.default without having to do any extra work. Also, you avoid having to manually copy a configuration file if you make additional installations/repositories in the future.

Rewriting History Requires Manual Intervention Anyway…

If it is unacceptable to maintain the content in the repository then you will likely want to completely eradicate it from history with something like git filter-branch --index-filter …. This amounts to rewriting history, which will require manual intervention for each branch/repository (see “Recovering From Upstream Rebase” section in the git rebase manpage). The special treatment required for your configuration file would be just another step that one must perform while recovering from the rewrite:

  1. Save a copy of the configuration file.
  2. Recover from the rewrite.
  3. Restore the configuration file.

Ignore It to Prevent Recurrence

Whatever method you use, you will probably want to include the configuration filename in a .gitignore file in the repository so that no one can inadvertently git add foo.conf again (it is possible, but requires -f/--force). If you have more than one configuration file, you might consider ‘moving’ them all into a single directory and ignoring the whole thing (by ‘moving’ I mean changing where the program expects to find its configuration files, and getting the users (or the launch/deploy mechanism) to copy/move the files to to their new location; you obviously would not want to git mv a file into a directory that you will be ignoring).

In Powershell what is the idiomatic way of converting a string to an int?

A quick true/false test of whether it will cast to [int]

[bool]($var -as [int] -is [int])

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

json.net has key method?

JObject implements IDictionary<string, JToken>, so you can use:

IDictionary<string, JToken> dictionary = x;
if (dictionary.ContainsKey("error_msg"))

... or you could use TryGetValue. It implements both methods using explicit interface implementation, so you can't use them without first converting to IDictionary<string, JToken> though.

Getting an option text/value with JavaScript

In jquery you could try this $("#select_id>option:selected").text()

Copy files on Windows Command Line with Progress

This technet link has some good info for copying large files. I used an exchange server utility mentioned in the article which shows progress and uses non buffered copy functions internally for faster transfer.

In another scenario, I used robocopy. Robocopy GUI makes it easier to get your command line options right.

Provide an image for WhatsApp link sharing

Following actions helped in my case.

Putting image under the same host.

<meta property="og:url" content="https://www.same-host.com/whatsapp-image.png" />

Passing needed image to WhatsApp specifically by detecting its user agent by leading substring, example

WhatsApp/2.18.380 A

Waiting few seconds before actually pushing send button, so WhatsApp will have time to retrieve image and description from og metadata.

Excel VBA function to print an array to the workbook

My tested version

Sub PrintArray(RowPrint, ColPrint, ArrayName, WorkSheetName)

Sheets(WorkSheetName).Range(Cells(RowPrint, ColPrint), _
Cells(RowPrint + UBound(ArrayName, 2) - 1, _
ColPrint + UBound(ArrayName, 1) - 1)) = _
WorksheetFunction.Transpose(ArrayName)

End Sub

Xcode couldn't find any provisioning profiles matching

I am now able to successfully build. Not sure exactly which step "fixed" things, but this was the sequence:

  • Tried automatic signing again. No go, so reverted to manual.
  • After reverting, I had no Eligible Profiles, all were ineligible. Strange.
  • I created a new certificate and profile, imported both. This too was "ineligible".
  • Removed the iOS platform and re-added it. I had tried this previously without luck.
  • After doing this, Xcode on its own defaulted to automatic signing. And this worked! Success!

While I am not sure exactly which parts were necessary, I think the previous certificates were the problem. I hate Xcode :(

Thanks for help.

How to join two JavaScript Objects, without using JQUERY

There are couple of different solutions to achieve this:

1 - Native javascript for-in loop:

const result = {};
let key;

for (key in obj1) {
  if(obj1.hasOwnProperty(key)){
    result[key] = obj1[key];
  }
}

for (key in obj2) {
  if(obj2.hasOwnProperty(key)){
    result[key] = obj2[key];
  }
}

2 - Object.keys():

const result = {};

Object.keys(obj1)
  .forEach(key => result[key] = obj1[key]);

Object.keys(obj2)
  .forEach(key => result[key] = obj2[key]);

3 - Object.assign():
(Browser compatibility: Chrome: 45, Firefox (Gecko): 34, Internet Explorer: No support, Edge: (Yes), Opera: 32, Safari: 9)

const result = Object.assign({}, obj1, obj2);

4 - Spread Operator:
Standardised from ECMAScript 2015 (6th Edition, ECMA-262):

Defined in several sections of the specification: Array Initializer, Argument Lists

Using this new syntax you could join/merge different objects into one object like this:

const result = {
  ...obj1,
  ...obj2,
};

5 - jQuery.extend(target, obj1, obj2):

Merge the contents of two or more objects together into the first object.

const target = {};

$.extend(target, obj1, obj2);

6 - jQuery.extend(true, target, obj1, obj2):

Run a deep merge of the contents of two or more objects together into the target. Passing false for the first argument is not supported.

const target = {};

$.extend(true, target, obj1, obj2);

7 - Lodash _.assignIn(object, [sources]): also named as _.extend:

const result = {};

_.assignIn(result, obj1, obj2);

8 - Lodash _.merge(object, [sources]):

const result = _.merge(obj1, obj2);

There are a couple of important differences between lodash's merge function and Object.assign:

1- Although they both receive any number of objects but lodash's merge apply a deep merge of those objects but Object.assign only merges the first level. For instance:

_.isEqual(_.merge({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
}), {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // true

BUT:

const result = Object.assign({
  x: {
    y: { key1: 'value1' },
  },
}, {
  x: {
    y: { key2: 'value2' },
  },
});
_.isEqual(result, {
  x: {
    y: {
      key1: 'value1',
      key2: 'value2',
    },
  },
}); // false
// AND
_.isEqual(result, {
  x: {
    y: {
      key2: 'value2',
    },
  },
}); // true

2- Another difference has to do with how Object.assign and _.merge interpret the undefined value:

_.isEqual(_.merge({x: 1}, {x: undefined}), { x: 1 }) // false

BUT:

_.isEqual(Object.assign({x: 1}, {x: undefined}), { x: undefined })// true

Update 1:

When using for in loop in JavaScript, we should be aware of our environment specially the possible prototype changes in the JavaScript types. For instance some of the older JavaScript libraries add new stuff to Array.prototype or even Object.prototype. To safeguard your iterations over from the added stuff we could use object.hasOwnProperty(key) to mke sure the key is actually part of the object you are iterating over.


Update 2:

I updated my answer and added the solution number 4, which is a new JavaScript feature but not completely standardized yet. I am using it with Babeljs which is a compiler for writing next generation JavaScript.


Update 3:
I added the difference between Object.assign and _.merge.

How do I filter an array with TypeScript in Angular 2?

You can check an example in Plunker over here plunker example filters

filter() {

    let storeId = 1;
    this.bookFilteredList = this.bookList
                                .filter((book: Book) => book.storeId === storeId);
    this.bookList = this.bookFilteredList; 
}

Oracle Age calculation from Date of birth and Today

You can try below method,

SELECT EXTRACT(YEAR FROM APP_SUBMITTED_DATE)-EXTRACT(YEAR FROM BIRTH_DATE) FROM SOME_TABLE;

It will compare years and give age accordingly.
You can also use SYSDATE instead of APP_SUBMITTED_DATE.

Regards.

How do I change the root directory of an Apache server?

I had to edit /etc/apache2/sites-available/default. The lines are the same as mentioned by RDL.

How to validate a file upload field using Javascript/jquery

I got this from some forum. I hope it will be useful for you.

<script type="text/javascript">
 function validateFileExtension(fld) {
    if(!/(\.bmp|\.gif|\.jpg|\.jpeg)$/i.test(fld.value)) {
        alert("Invalid image file type.");      
        fld.form.reset();
        fld.focus();        
        return false;   
    }   
    return true; 
 } </script> </head>
 <body> <form ...etc...  onsubmit="return
 validateFileExtension(this.fileField)"> <p> <input type="file"
 name="fileField"  onchange="return validateFileExtension(this)">
 <input type="submit" value="Submit"> </p> </form> </body>

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

Ruby objects and JSON serialization (without Rails)

Actually, there is a gem called Jsonable, https://github.com/treeder/jsonable. It's pretty sweet.

How exactly does the python any() function work?

>>> names = ['King', 'Queen', 'Joker']
>>> any(n in 'King and john' for n in names)
True

>>> all(n in 'King and Queen' for n in names)
False

It just reduce several line of code into one. You don't have to write lengthy code like:

for n in names:
    if n in 'King and john':
       print True
    else:
       print False

Bind class toggle to window scroll event

Maybe this can help :)

Controller

$scope.scrollevent = function($e){
   // Your code
}

Html

<div scroll scroll-event="scrollevent">//scrollable content</div>

Or

<body scroll scroll-event="scrollevent">//scrollable content</body>

Directive

.directive("scroll", function ($window) {
   return {
      scope: {
         scrollEvent: '&'
      },
      link : function(scope, element, attrs) {
        $("#"+attrs.id).scroll(function($e) { scope.scrollEvent != null ?  scope.scrollEvent()($e) : null })
      }
   }
})

Regex to validate date format dd/mm/yyyy

Found this reg ex here

^(((0[1-9]|[12]\d|3[01])\/(0[13578]|1[02])\/((19|[2-9]\d)\d{2}))|((0[1-9]|[12]\d|30)\/(0[13456789]|1[012])\/((19|[2-9]\d)\d{2}))|((0[1-9]|1\d|2[0-8])\/02\/((19|[2-9]\d)\d{2}))|(29\/02\/((1[6-9]|[2-9]\d)(0[48]|[2468][048]|[13579][26])|((16|[2468][048]|[3579][26])00))))$

This validates the format mm/dd/yyyy and valid dates correctly (but not m/d/yyyy).

Some tests

replace all occurrences in a string

Brighams answer uses literal regexp.

Solution with a Regex object.

var regex = new RegExp('\n', 'g');
text = text.replace(regex, '<br />');

TRY IT HERE : JSFiddle Working Example

Getting The ASCII Value of a character in a C# string

Just cast each character to an int:

for (int i = 0; i < str.length; i++)  
  Console.Write(((int)str[i]).ToString());

How to set Highcharts chart maximum yAxis value

Try this:

yAxis: {min: 0, max: 100}

See this jsfiddle example

How can I match multiple occurrences with a regex in JavaScript similar to PHP's preg_match_all()?

H?llo from 2020. Let me bring String.prototype.matchAll() to your attention:

let regexp = /(?:&|&amp;)?([^=]+)=([^&]+)/g;
let str = '1111342=Adam%20Franco&348572=Bob%20Jones';

for (let match of str.matchAll(regexp)) {
    let [full, key, value] = match;
    console.log(key + ' => ' + value);
}

Outputs:

1111342 => Adam%20Franco
348572 => Bob%20Jones

How to show progress bar while loading, using ajax

I know that are already many answers written for this solution however I want to show another javascript method (dependent on JQuery) in which you simply need to include ONLY a single JS File without any dependency on CSS or Gif Images in your code and that will take care of all progress bar related animations that happens during Ajax Request. You need to simnply pass javascript function like this

var objGlobalEvent = new RegisterGlobalEvents(true, "");

Preview of Fiddle Loader Type

Here is the working fiddle for the code. https://jsfiddle.net/vibs2006/c7wukc41/3/

Group By Eloquent ORM

try: ->unique('column')

example:

$users = User::get()->unique('column');

How to remove list elements in a for loop in Python?

Probably a bit late to answer this but I just found this thread and I had created my own code for it previously...

    list = [1,2,3,4,5]
    deleteList = []
    processNo = 0
    for item in list:
        if condition:
            print item
            deleteList.insert(0, processNo)
        processNo += 1

    if len(deleteList) > 0:
        for item in deleteList:
            del list[item]

It may be a long way of doing it but seems to work well. I create a second list that only holds numbers that relate to the list item to delete. Note the "insert" inserts the list item number at position 0 and pushes the remainder along so when deleting the items, the list is deleted from the highest number back to the lowest number so the list stays in sequence.

How to make a rest post call from ReactJS code?

React doesn't really have an opinion about how you make REST calls. Basically you can choose whatever kind of AJAX library you like for this task.

The easiest way with plain old JavaScript is probably something like this:

var request = new XMLHttpRequest();
request.open('POST', '/my/url', true);
request.setRequestHeader('Content-Type', 'application/json; charset=UTF-8');
request.send(data);

In modern browsers you can also use fetch.

If you have more components that make REST calls it might make sense to put this kind of logic in a class that can be used across the components. E.g. RESTClient.post(…)

How to encode a string in JavaScript for displaying in HTML?

You need to escape < and &. Escaping > too doesn't hurt:

function magic(input) {
    input = input.replace(/&/g, '&amp;');
    input = input.replace(/</g, '&lt;');
    input = input.replace(/>/g, '&gt;');
    return input;
}

Or you let the DOM engine do the dirty work for you (using jQuery because I'm lazy):

function magic(input) {
    return $('<span>').text(input).html();
}

What this does is creating a dummy element, assigning your string as its textContent (i.e. no HTML-specific characters have side effects since it's just text) and then you retrieve the HTML content of that element - which is the text but with special characters converted to HTML entities in cases where it's necessary.

AngularJS: Can't I set a variable value on ng-click?

While @tymeJV gave a correct answer, the way to do this to be inline with angular would be:

ng-click="hidePrefs()"

and then in your controller:

$scope.hidePrefs = function() {  
  $scope.prefs = false;
}

How to edit/save a file through Ubuntu Terminal

For editing use

vi galfit.feedme //if user has file editing permissions

or

sudo vi galfit.feedme //if user doesn't have file editing permissions

For inserting

Press i //Do required editing

For exiting

Press Esc

    :wq //for exiting and saving
    :q! //for exiting without saving

Moment js get first and last day of current month

I ran into some issues because I wasn't aware that moment().endOf() mutates the input date, so I used this work around.

_x000D_
_x000D_
let thisMoment = moment();
let endOfMonth = moment(thisMoment).endOf('month');
let startOfMonth = moment(thisMoment).startOf('month');
_x000D_
_x000D_
_x000D_

How to change lowercase chars to uppercase using the 'keyup' event?

Plain ol' javascript:

var input = document.getElementById('inputID');

input.onkeyup = function(){
    this.value = this.value.toUpperCase();
}

Javascript with jQuery:

$('#inputID').keyup(function(){
    this.value = this.value.toUpperCase();
});

jQuery ajax success callback function definition

You don't need to declare the variable. Ajax success function automatically takes up to 3 parameters: Function( Object data, String textStatus, jqXHR jqXHR )

When should I write the keyword 'inline' for a function/method?

I'd like to contribute to all of the great answers in this thread with a convincing example to disperse any remaining misunderstanding.

Given two source files, such as:

  • inline111.cpp:

    #include <iostream>
    
    void bar();
    
    inline int fun() {
      return 111;
    }
    
    int main() {
      std::cout << "inline111: fun() = " << fun() << ", &fun = " << (void*) &fun;
      bar();
    }
    
  • inline222.cpp:

    #include <iostream>
    
    inline int fun() {
      return 222;
    }
    
    void bar() {
      std::cout << "inline222: fun() = " << fun() << ", &fun = " << (void*) &fun;
    }
    

  • Case A:

    Compile:

    g++ -std=c++11 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x4029a0
    inline222: fun() = 111, &fun = 0x4029a0
    

    Discussion:

    1. Even thou you ought to have identical definitions of your inline functions, C++ compiler does not flag it if that is not the case (actually, due to separate compilation it has no ways to check it). It is your own duty to ensure this!

    2. Linker does not complain about One Definition Rule, as fun() is declared as inline. However, because inline111.cpp is the first translation unit (which actually calls fun()) processed by compiler, the compiler instantiates fun() upon its first call-encounter in inline111.cpp. If compiler decides not to expand fun() upon its call from anywhere else in your program (e.g. from inline222.cpp), the call to fun() will always be linked to its instance produced from inline111.cpp (the call to fun() inside inline222.cpp may also produce an instance in that translation unit, but it will remain unlinked). Indeed, that is evident from the identical &fun = 0x4029a0 print-outs.

    3. Finally, despite the inline suggestion to the compiler to actually expand the one-liner fun(), it ignores your suggestion completely, which is clear because fun() = 111 in both of the lines.


  • Case B:

    Compile (notice reverse order):

    g++ -std=c++11 inline222.cpp inline111.cpp
    

    Output:

    inline111: fun() = 222, &fun = 0x402980
    inline222: fun() = 222, &fun = 0x402980
    

    Discussion:

    1. This case asserts what have been discussed in Case A.

    2. Notice an important point, that if you comment out the actual call to fun() in inline222.cpp (e.g. comment out cout-statement in inline222.cpp completely) then, despite the compilation order of your translation units, fun() will be instantiated upon it's first call encounter in inline111.cpp, resulting in print-out for Case B as inline111: fun() = 111, &fun = 0x402980.


  • Case C:

    Compile (notice -O2):

    g++ -std=c++11 -O2 inline222.cpp inline111.cpp
    

    or

    g++ -std=c++11 -O2 inline111.cpp inline222.cpp
    

    Output:

    inline111: fun() = 111, &fun = 0x402900
    inline222: fun() = 222, &fun = 0x402900
    

    Discussion:

    1. As is described here, -O2 optimization encourages compiler to actually expand the functions that can be inlined (Notice also that -fno-inline is default without optimization options). As is evident from the outprint here, the fun() has actually been inline expanded (according to its definition in that particular translation unit), resulting in two different fun() print-outs. Despite this, there is still only one globally linked instance of fun() (as required by the standard), as is evident from identical &fun print-out.

On a CSS hover event, can I change another div's styling?

A pure solution without jQuery:

Javascript (Head)

function chbg(color) {
    document.getElementById('b').style.backgroundColor = color;
}   

HTML (Body)

<div id="a" onmouseover="chbg('red')" onmouseout="chbg('white')">This is element a</div>
<div id="b">This is element b</div>

JSFiddle: http://jsfiddle.net/YShs2/

Get Folder Size from Windows Command Line

So here is a solution for both your requests in the manner you originally asked for. It will give human readability filesize without the filesize limits everyone is experiencing. Compatible with Win Vista or newer. XP only available if Robocopy is installed. Just drop a folder on this batch file or use the better method mentioned below.

@echo off
setlocal enabledelayedexpansion
set "vSearch=Files :"

For %%i in (%*) do (
    set "vSearch=Files :"
    For /l %%M in (1,1,2) do ( 
        for /f "usebackq tokens=3,4 delims= " %%A in (`Robocopy "%%i" "%%i" /E /L /NP /NDL /NFL ^| find "!vSearch!"`) do (
            if /i "%%M"=="1" (
                set "filecount=%%A"
                set "vSearch=Bytes :"
            ) else (
                set "foldersize=%%A%%B"
            )
        )
    )
    echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!
    REM remove the word "REM" from line below to output to txt file
    REM echo Folder: %%~nxi FileCount: !filecount! Foldersize: !foldersize!>>Folder_FileCountandSize.txt
)
pause

To be able to use this batch file conveniently put it in your SendTo folder. This will allow you to right click a folder or selection of folders, click on the SendTo option, and then select this batch file.

To find the SendTo folder on your computer simplest way is to open up cmd then copy in this line as is.

explorer C:\Users\%username%\AppData\Roaming\Microsoft\Windows\SendTo

How to validate an email address in JavaScript

Do this:

[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-zA-Z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?\.)+[a-zA-Z0-9](?:[a-zA-Z0-9-]*[a-zA-Z0-9])?

Why? It's based on RFC 2822, which is a standard ALL email addresses MUST adhere to. And I'm not sure why you'd bother with something "simpler"... you're gonna copy and paste it anyway ;)

Often when storing email addresses in the database I make them lowercase and, in practice, regexs can usually be marked case insensitive. In those cases this is slightly shorter:

[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?

Here's an example of it being used in JavaScript (with the case insensitive flag i at the end).

var emailCheck=/^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?$/i;
console.log( emailCheck.test('[email protected]') );

Note:
Technically some emails can include quotes in the section before the @ symbol with escape characters inside the quotes (so your email user can be obnoxious and contain stuff like @ and "..." as long as it's written in quotes). NOBODY DOES THIS EVER! It's obsolete. But, it IS included in the true RFC 2822 standard, and omitted here.

More info: http://www.regular-expressions.info/email.html

How to add chmod permissions to file in Git?

Antwane's answer is correct, and this should be a comment but comments don't have enough space and do not allow formatting. :-) I just want to add that in Git, file permissions are recorded only1 as either 644 or 755 (spelled (100644 and 100755; the 100 part means "regular file"):

diff --git a/path b/path
new file mode 100644

The former—644—means that the file should not be executable, and the latter means that it should be executable. How that turns into actual file modes within your file system is somewhat OS-dependent. On Unix-like systems, the bits are passed through your umask setting, which would normally be 022 to remove write permission from "group" and "other", or 002 to remove write permission only from "other". It might also be 077 if you are especially concerned about privacy and wish to remove read, write, and execute permission from both "group" and "other".


1Extremely-early versions of Git saved group permissions, so that some repositories have tree entries with mode 664 in them. Modern Git does not, but since no part of any object can ever be changed, those old permissions bits still persist in old tree objects.

The change to store only 0644 or 0755 was in commit e44794706eeb57f2, which is before Git v0.99 and dated 16 April 2005.

JSON serialization/deserialization in ASP.Net Core

.net core

using System.Text.Json;

To serialize

var jsonStr = JsonSerializer.Serialize(MyObject)

Deserialize

var weatherForecast = JsonSerializer.Deserialize<MyObject>(jsonStr);

For more information about excluding properties and nulls check out This Microsoft side

If you can decode JWT, how are they secure?

I would suggest in taking a look into JWE using special algorithms which is not present in jwt.io to decrypt

Reference link: https://www.npmjs.com/package/node-webtokens

jwt.generate('PBES2-HS512+A256KW', 'A256GCM', payload, pwd, (error, token) => {
  jwt.parse(token).verify(pwd, (error, parsedToken) => {
    // other statements
  });
});

This answer may be too late or you might have already found out the way, but still, I felt it would be helpful for you and others as well.

A simple example which I have created: https://github.com/hansiemithun/jwe-example

Removing NA in dplyr pipe

I don't think desc takes an na.rm argument... I'm actually surprised it doesn't throw an error when you give it one. If you just want to remove NAs, use na.omit (base) or tidyr::drop_na:

outcome.df %>%
  na.omit() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

library(tidyr)
outcome.df %>%
  drop_na() %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

If you only want to remove NAs from the HeartAttackDeath column, filter with is.na, or use tidyr::drop_na:

outcome.df %>%
  filter(!is.na(HeartAttackDeath)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

outcome.df %>%
  drop_na(HeartAttackDeath) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

As pointed out at the dupe, complete.cases can also be used, but it's a bit trickier to put in a chain because it takes a data frame as an argument but returns an index vector. So you could use it like this:

outcome.df %>%
  filter(complete.cases(.)) %>%
  group_by(Hospital, State) %>%
  arrange(desc(HeartAttackDeath)) %>%
  head()

Passing two command parameters using a WPF binding

About using Tuple in Converter, it would be better to use 'object' instead of 'string', so that it works for all types of objects without limitation of 'string' object.

public class YourConverter : IMultiValueConverter 
{      
    public object Convert(object[] values, ...)     
    {   
        Tuple<object, object> tuple = new Tuple<object, object>(values[0], values[1]);
        return tuple;
    }      
} 

Then execution logic in Command could be like this

public void OnExecute(object parameter) 
{
    var param = (Tuple<object, object>) parameter;

    // e.g. for two TextBox object
    var txtZip = (System.Windows.Controls.TextBox)param.Item1;
    var txtCity = (System.Windows.Controls.TextBox)param.Item2;
}

and multi-bind with converter to create the parameters (with two TextBox objects)

<Button Content="Zip/City paste" Command="{Binding PasteClick}" >
    <Button.CommandParameter>
        <MultiBinding Converter="{StaticResource YourConvert}">
            <Binding ElementName="txtZip"/>
            <Binding ElementName="txtCity"/>
        </MultiBinding>
    </Button.CommandParameter>
</Button>

Angular 2 router no base href set

Angular 7,8 fix is in app.module.ts

import {APP_BASE_HREF} from '@angular/common';

inside @NgModule add

providers: [{provide: APP_BASE_HREF, useValue: '/'}]

how to change language for DataTable

Tradução para Português Brasil

    $('#table_id').DataTable({
    "language": {
        "sProcessing":    "Procesando...",
        "sLengthMenu":    "Exibir _MENU_ registros por página",
        "sZeroRecords":   "Nenhum resultado encontrado",
        "sEmptyTable":    "Nenhum resultado encontrado",
        "sInfo":          "Exibindo do _START_ até _END_ de um total de _TOTAL_ registros",
        "sInfoEmpty":     "Exibindo do 0 até 0 de um total de 0 registros",
        "sInfoFiltered":  "(Filtrado de um total de _MAX_ registros)",
        "sInfoPostFix":   "",
        "sSearch":        "Buscar:",
        "sUrl":           "",
        "sInfoThousands":  ",",
        "sLoadingRecords": "Cargando...",
        "oPaginate": {
            "sFirst":    "Primero",
            "sLast":    "Último",
            "sNext":    "Próximo",
            "sPrevious": "Anterior"
        },
        "oAria": {
            "sSortAscending":  ": Ativar para ordenar a columna de maneira ascendente",
            "sSortDescending": ": Ativar para ordenar a columna de maneira descendente"
        }
    }
});

How to place Text and an Image next to each other in HTML?

img {
    float:left;
}
h3 {
    float:right;
}

jsFiddle example

Note that you will probably want to use the style clear:both on whatever elements comes after the code you provided so that it doesn't slide up directly beneath the floated elements.

How to check heap usage of a running JVM from the command line?

For Java 8 you can use the following command line to get the heap space utilization in kB:

jstat -gc <PID> | tail -n 1 | awk '{split($0,a," "); sum=a[3]+a[4]+a[6]+a[8]; print sum}'

The command basically sums up:

  • S0U: Survivor space 0 utilization (kB).
  • S1U: Survivor space 1 utilization (kB).
  • EU: Eden space utilization (kB).
  • OU: Old space utilization (kB).

You may also want to include the metaspace and the compressed class space utilization. In this case you have to add a[10] and a[12] to the awk sum.

Loaded nib but the 'view' outlet was not set

select the files owner and goto open the identity inspecter give the class name to which it corresponds to. If none of the above methods works and still you can't see the view outlet then give new referencing outlet Connection to the File's Owner then you can able to see the view outlet. Click on the view Outlet to make a connection between the View Outlet and File's owner. Run the Application this works fine.

How to get the first day of the current week and month?

A one-line solution using Java 8 features

In Java

LocalDateTime firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay(); // 2020-06-08 00:00 MONDAY
LocalDateTime firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay(); // 2020-06-01 00:00
// Convert to milliseconds: 
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();

In Kotlin

val firstOfWeek = LocalDateTime.now().with(ChronoField.DAY_OF_WEEK, 1).toLocalDate().atStartOfDay() // 2020-06-08 00:00 MONDAY
val firstOfMonth = LocalDateTime.now().with(ChronoField.DAY_OF_MONTH , 1).toLocalDate().atStartOfDay() // 2020-06-01 00:00
// Convert to milliseconds: 
firstOfWeek.atZone(ZoneId.systemDefault()).toInstant().toEpochMilli()

Rebase array keys after unsetting elements

In my situation, I needed to retain unique keys with the array values, so I just used a second array:

$arr1 = array("alpha"=>"bravo","charlie"=>"delta","echo"=>"foxtrot");
unset($arr1);

$arr2 = array();
foreach($arr1 as $key=>$value) $arr2[$key] = $value;
$arr1 = $arr2
unset($arr2);

VBScript - How to make program wait until process has finished?

You need to tell the run to wait until the process is finished. Something like:

const DontWaitUntilFinished = false, ShowWindow = 1, DontShowWindow = 0, WaitUntilFinished = true
set oShell = WScript.CreateObject("WScript.Shell")
command = "cmd /c C:\windows\system32\wscript.exe <path>\myScript.vbs " & args
oShell.Run command, DontShowWindow, WaitUntilFinished

In the script itself, start Excel like so. While debugging start visible:

File = "c:\test\myfile.xls"
oShell.run """C:\Program Files\Microsoft Office\Office14\EXCEL.EXE"" " & File, 1, true

Javascript communication between browser tabs/windows

You can do this via local storage API. Note that this works only between 2 tabs. you can't put both sender and receiver on the same page:

On sender page:

localStorage.setItem("someKey", "someValue");

On the receiver page

    $(document).ready(function () {

        window.addEventListener('storage', storageEventHandler, false);

        function storageEventHandler(evt) {
            alert("storage event called key: " + evt.key);
        }
    });

Pass a local file in to URL in Java

have a look here for the full syntax: http://en.wikipedia.org/wiki/File_URI_scheme for unix-like systems it will be as @Alex said file:///your/file/here whereas for Windows systems would be file:///c|/path/to/file

Why use 'virtual' for class properties in Entity Framework model definitions?

It’s quite common to define navigational properties in a model to be virtual. When a navigation property is defined as virtual, it can take advantage of certain Entity Framework functionality. The most common one is lazy loading.

Lazy loading is a nice feature of many ORMs because it allows you to dynamically access related data from a model. It will not unnecessarily fetch the related data until it is actually accessed, thus reducing the up-front querying of data from the database.

From book "ASP.NET MVC 5 with Bootstrap and Knockout.js"

Cross-Origin Read Blocking (CORB)

Response headers are generally set on the server. Set 'Access-Control-Allow-Headers' to 'Content-Type' on server side

C# nullable string error

System.String is a reference type and already "nullable".

Nullable<T> and the ? suffix are for value types such as Int32, Double, DateTime, etc.

Installing a pip package from within a Jupyter Notebook not working

Try using some shell magic: %%sh %%sh pip install geocoder let me know if it works, thanks

HTML radio buttons allowing multiple selections

All radio buttons must have the same name attribute added.

What is the fastest way to compare two sets in Java?

public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof Set))
            return false;

        Set<String> a = this;
        Set<String> b = o;
        Set<String> thedifference_a_b = new HashSet<String>(a);


        thedifference_a_b.removeAll(b);
        if(thedifference_a_b.isEmpty() == false) return false;

        Set<String> thedifference_b_a = new HashSet<String>(b);
        thedifference_b_a.removeAll(a);

        if(thedifference_b_a.isEmpty() == false) return false;

        return true;
    }

Fitting polynomial model to data in R

To get a third order polynomial in x (x^3), you can do

lm(y ~ x + I(x^2) + I(x^3))

or

lm(y ~ poly(x, 3, raw=TRUE))

You could fit a 10th order polynomial and get a near-perfect fit, but should you?

EDIT: poly(x, 3) is probably a better choice (see @hadley below).

HTML Best Practices: Should I use &rsquo; or the special keyboard shortcut?

I don't think that one is better than the other in general; it depends on how you intend to use it.

  • If you want to store it in a DB column that has a charset/collation that does not support the right single quote character, you may run into storing it as the multi-byte character instead of 7-bit ASCII (&rsquo;).
  • If you are displaying it on an html element that specifies a charset that does not support it, it may not display in either case.
  • If many developers are going to be editing/viewing this file with editors/keyboards that do not support properly typing or displaying the character, you may want to use the entity
  • If you need to convert the file between various character encodings or formats, you may want to use the entity
  • If your HTML code may escape entities improperly, you may want to use the character.

In general I would lean more towards using the character because as you point out it is easier to read and type.

Multi-dimensional arraylist or list in C#?

Depending on your exact requirements, you may do best with a jagged array of sorts with:

List<string>[] results = new { new List<string>(), new List<string>() };

Or you may do well with a list of lists or some other such construct.

How do we check if a pointer is NULL pointer?

Well, this question was asked and answered way back in 2011, but there is nullptrin C++11. That's all I'm using currently.

You can read more from Stack Overflow and also from this article.

What is the HTML5 equivalent to the align attribute in table cells?

You can use inline css :
<td style = "text-align: center;">

sql query to get earliest date

Using "limit" and "top" will not work with all SQL servers (for example with Oracle). You can try a more complex query in pure sql:

select mt1.id, mt1."name", mt1.score, mt1."date" from mytable mt1
where mt1.id=2
and mt1."date"= (select min(mt2."date") from mytable mt2 where mt2.id=2)

"unexpected token import" in Nodejs5 and babel?

Involve following steps to resolve the issue:

1) Install the CLI and env preset

$ npm install --save-dev babel-cli babel-preset-env

2) Create a .babelrc file

{
  "presets": ["env"]
}

3) configure npm start in package.json

"scripts": {
    "start": "babel-node ./server/app.js",
    "test": "echo \"Error: no test specified\" && exit 1"
  }

4) then start app

$ npm start

Declaring static constants in ES6 classes?

Here's a few things you could do:

Export a const from the module. Depending on your use case, you could just:

export const constant1 = 33;

And import that from the module where necessary. Or, building on your static method idea, you could declare a static get accessor:

const constant1 = 33,
      constant2 = 2;
class Example {

  static get constant1() {
    return constant1;
  }

  static get constant2() {
    return constant2;
  }
}

That way, you won't need parenthesis:

const one = Example.constant1;

Babel REPL Example

Then, as you say, since a class is just syntactic sugar for a function you can just add a non-writable property like so:

class Example {
}
Object.defineProperty(Example, 'constant1', {
    value: 33,
    writable : false,
    enumerable : true,
    configurable : false
});
Example.constant1; // 33
Example.constant1 = 15; // TypeError

It may be nice if we could just do something like:

class Example {
    static const constant1 = 33;
}

But unfortunately this class property syntax is only in an ES7 proposal, and even then it won't allow for adding const to the property.

MS SQL 2008 - get all table names and their row counts in a DB

SELECT sc.name +'.'+ ta.name TableName
 ,SUM(pa.rows) RowCnt
 FROM sys.tables ta
 INNER JOIN sys.partitions pa
 ON pa.OBJECT_ID = ta.OBJECT_ID
 INNER JOIN sys.schemas sc
 ON ta.schema_id = sc.schema_id
 WHERE ta.is_ms_shipped = 0 AND pa.index_id IN (1,0)
 GROUP BY sc.name,ta.name
 ORDER BY SUM(pa.rows) DESC

See this:

Can't get ScriptManager.RegisterStartupScript in WebControl nested in UpdatePanel to work

I had an issue with Page.ClientScript.RegisterStartUpScript - I wasn't using an update panel, but the control was cached. This meant that I had to insert the script into a Literal (or could use a PlaceHolder) so when rendered from the cache the script is included.

A similar solution might work for you.

How to determine if Javascript array contains an object with an attribute that equals a given value?

Unless you want to restructure it like this:

vendors = {
    Magenic: {
      Name: 'Magenic',
      ID: 'ABC'
     },
    Microsoft: {
      Name: 'Microsoft',
      ID: 'DEF'
    } and so on... 
};

to which you can do if(vendors.Magnetic)

You will have to loop

How to find out if an item is present in a std::vector?

You can try this code:

#include <algorithm>
#include <vector>

// You can use class, struct or primitive data type for Item
struct Item {
    //Some fields
};
typedef std::vector<Item> ItemVector;
typedef ItemVector::iterator ItemIterator;
//...
ItemVector vtItem;
//... (init data for vtItem)
Item itemToFind;
//...

ItemIterator itemItr;
itemItr = std::find(vtItem.begin(), vtItem.end(), itemToFind);
if (itemItr != vtItem.end()) {
    // Item found
    // doThis()
}
else {
    // Item not found
    // doThat()
}

How to import an existing project from GitHub into Android Studio

You can directly import github projects into Android Studio. File -> New -> Project from Version Control -> GitHub. Then enter your github username and password.Select the repository and hit clone.

The github repo will be created as a new project in android studio.

Delete from a table based on date

This is pretty vague. Do you mean like in SQL:

DELETE FROM myTable
WHERE dateColumn < '2007'

Is there a way to make AngularJS load partials in the beginning and not at when needed?

Another method is to use HTML5's Application Cache to download all files once and keep them in the browser's cache. The above link contains much more information. The following information is from the article:

Change your <html> tag to include a manifest attribute:

<html manifest="http://www.example.com/example.mf">

A manifest file must be served with the mime-type text/cache-manifest.

A simple manifest looks something like this:

CACHE MANIFEST
index.html
stylesheet.css
images/logo.png
scripts/main.js
http://cdn.example.com/scripts/main.js

Once an application is offline it remains cached until one of the following happens:

  1. The user clears their browser's data storage for your site.
  2. The manifest file is modified. Note: updating a file listed in the manifest doesn't mean the browser will re-cache that resource. The manifest file itself must be altered.

What is Node.js' Connect, Express and "middleware"?

middleware as the name suggests actually middleware is sit between middle.. middle of what? middle of request and response..how request,response,express server sit in express app in this picture you can see requests are coming from client then the express server server serves those requests.. then lets dig deeper.. actually we can divide this whole express server's whole task in to small seperate tasks like in this way. how middleware sit between request and response small chunk of server parts doing some particular task and passed request to next one.. finally doing all the tasks response has been made.. all middle ware can access request object,response object and next function of request response cycle..

this is good example for explaining middleware in express youtube video for middleware

How to check if a string starts with one of several prefixes?

if(newStr4.startsWith("Mon") || newStr4.startsWith("Tues") || newStr4.startsWith("Weds") .. etc)

You need to include the whole str.startsWith(otherStr) for each item, since || only works with boolean expressions (true or false).

There are other options if you have a lot of things to check, like regular expressions, but they tend to be slower and more complicated regular expressions are generally harder to read.

An example regular expression for detecting day name abbreviations would be:

if(Pattern.matches("Mon|Tues|Wed|Thurs|Fri", stringToCheck)) {

JSON for List of int

JSON is perfectly capable of expressing lists of integers, and the JSON you have posted is valid. You can simply separate the integers by commas:

{
    "Id": "610",
    "Name": "15",
    "Description": "1.99",
    "ItemModList": [42, 47, 139]
}

When should I use Memcache instead of Memcached?

Memcached is a newer API, it also provides memcached as a session provider which could be great if you have a farm of server.

After the version is still really low 0.2 but I have used both and I didn't encounter major problem, so I would go to memcached since it's new.

How to delete an element from a Slice in Golang

I take the below approach to remove the item in slice. This helps in readability for others. And also immutable.

func remove(items []string, item string) []string {
    newitems := []string{}

    for _, i := range items {
        if i != item {
            newitems = append(newitems, i)
        }
    }

    return newitems
}

PDO's query vs execute

query runs a standard SQL statement and requires you to properly escape all data to avoid SQL Injections and other issues.

execute runs a prepared statement which allows you to bind parameters to avoid the need to escape or quote the parameters. execute will also perform better if you are repeating a query multiple times. Example of prepared statements:

$sth = $dbh->prepare('SELECT name, colour, calories FROM fruit
    WHERE calories < :calories AND colour = :colour');
$sth->bindParam(':calories', $calories);
$sth->bindParam(':colour', $colour);
$sth->execute();
// $calories or $color do not need to be escaped or quoted since the
//    data is separated from the query

Best practice is to stick with prepared statements and execute for increased security.

See also: Are PDO prepared statements sufficient to prevent SQL injection?

UINavigationBar custom back button without title

Create a UILabel with the title you want for your root view controller and assign it to the view controller's navigationItem.titleView.

Now set the title to an empty string and the next view controller you push will have a back button without text.

self.navigationItem.titleView = titleLabel; //Assuming you've created titleLabel above
self.title = @"";

How to make Twitter bootstrap modal full screen

For bootstrap 4 I have to add media query with max-width: none

@media (min-width: 576px) {
  .modal-dialog { max-width: none; }
}

.modal-dialog {
  width: 98%;
  height: 92%;
  padding: 0;
}

.modal-content {
  height: 99%;
}

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

tar -cvzf filename.tar.gz directory_to_compress/

Most tar commands have a z option to create a gziped version.

Though seems to me the question is how to circumvent Google. I'm not sure if renaming your output file would fool Google, but you could try. I.e.,

tar -cvzf filename.bla directory_to_compress/

and then send the filename.bla - contents will would be a zipped tar, so at the other end it could be retrieved as usual.

How to reset Android Studio

Linux Android Studio 0.8.6:

rm -R ~/.AndroidStudioBeta/config/

Linux Android Studio 1.0.0:

rm -R ~/.AndroidStudio/config/

prevent property from being serialized in web API

I'm late to the game, but an anonymous objects would do the trick:

[HttpGet]
public HttpResponseMessage Me(string hash)
{
    HttpResponseMessage httpResponseMessage;
    List<Something> somethings = ...

    var returnObjects = somethings.Select(x => new {
        Id = x.Id,
        OtherField = x.OtherField
    });

    httpResponseMessage = Request.CreateResponse(HttpStatusCode.OK, 
                                 new { result = true, somethings = returnObjects });

    return httpResponseMessage;
}

How to import a CSS file in a React Component

You need to use css-loader when creating bundle with webpack.

Install it:

npm install css-loader --save-dev

And add it to loaders in your webpack configs:

module.exports = {
  module: {
    loaders: [
      { test: /\.css$/, loader: "style-loader!css-loader" },
      // ...
    ]
  }
};

After this, you will be able to include css files in js.

Extracting text OpenCV

You can utilize a python implementation SWTloc.

Full Disclosure : I am the author of this library

To do that :-

First and Second Image

Notice that the text_mode here is 'lb_df', which stands for Light Background Dark Foreground i.e the text in this image is going to be in darker color than the background

from swtloc import SWTLocalizer
from swtloc.utils import imgshowN, imgshow

swtl = SWTLocalizer()
# Stroke Width Transform
swtl.swttransform(imgpaths='img1.jpg', text_mode = 'lb_df',
                  save_results=True, save_rootpath = 'swtres/',
                  minrsw = 3, maxrsw = 20, max_angledev = np.pi/3)
imgshow(swtl.swtlabelled_pruned13C)

# Grouping
respacket=swtl.get_grouped(lookup_radii_multiplier=0.9, ht_ratio=3.0)
grouped_annot_bubble = respacket[2]
maskviz = respacket[4]
maskcomb  = respacket[5]

# Saving the results
_=cv2.imwrite('img1_processed.jpg', swtl.swtlabelled_pruned13C)
imgshowN([maskcomb, grouped_annot_bubble], savepath='grouped_img1.jpg')

enter image description here enter image description here


enter image description here enter image description here

Third Image

Notice that the text_mode here is 'db_lf', which stands for Dark Background Light Foreground i.e the text in this image is going to be in lighter color than the background

from swtloc import SWTLocalizer
from swtloc.utils import imgshowN, imgshow

swtl = SWTLocalizer()
# Stroke Width Transform
swtl.swttransform(imgpaths=imgpaths[1], text_mode = 'db_lf',
              save_results=True, save_rootpath = 'swtres/',
              minrsw = 3, maxrsw = 20, max_angledev = np.pi/3)
imgshow(swtl.swtlabelled_pruned13C)

# Grouping
respacket=swtl.get_grouped(lookup_radii_multiplier=0.9, ht_ratio=3.0)
grouped_annot_bubble = respacket[2]
maskviz = respacket[4]
maskcomb  = respacket[5]

# Saving the results
_=cv2.imwrite('img1_processed.jpg', swtl.swtlabelled_pruned13C)
imgshowN([maskcomb, grouped_annot_bubble], savepath='grouped_img1.jpg')

enter image description here enter image description here

You will also notice that the grouping done is not so accurate, to get the desired results as the images might vary, try to tune the grouping parameters in swtl.get_grouped() function.

Is there a better way to iterate over two lists, getting one element from each list for each iteration?

Iterating through elements of two lists simultaneously is known as zipping, and python provides a built in function for it, which is documented here.

>>> x = [1, 2, 3]
>>> y = [4, 5, 6]
>>> zipped = zip(x, y)
>>> zipped
[(1, 4), (2, 5), (3, 6)]
>>> x2, y2 = zip(*zipped)
>>> x == list(x2) and y == list(y2)
True

[Example is taken from pydocs]

In your case, it will be simply:

for (lat, lon) in zip(latitudes, longitudes):
    ... process lat and lon

How does spring.jpa.hibernate.ddl-auto property exactly work in Spring?

For the record, the spring.jpa.hibernate.ddl-auto property is Spring Data JPA specific and is their way to specify a value that will eventually be passed to Hibernate under the property it knows, hibernate.hbm2ddl.auto.

The values create, create-drop, validate, and update basically influence how the schema tool management will manipulate the database schema at startup.

For example, the update operation will query the JDBC driver's API to get the database metadata and then Hibernate compares the object model it creates based on reading your annotated classes or HBM XML mappings and will attempt to adjust the schema on-the-fly.

The update operation for example will attempt to add new columns, constraints, etc but will never remove a column or constraint that may have existed previously but no longer does as part of the object model from a prior run.

Typically in test case scenarios, you'll likely use create-drop so that you create your schema, your test case adds some mock data, you run your tests, and then during the test case cleanup, the schema objects are dropped, leaving an empty database.

In development, it's often common to see developers use update to automatically modify the schema to add new additions upon restart. But again understand, this does not remove a column or constraint that may exist from previous executions that is no longer necessary.

In production, it's often highly recommended you use none or simply don't specify this property. That is because it's common practice for DBAs to review migration scripts for database changes, particularly if your database is shared across multiple services and applications.

How to build a Debian/Ubuntu package from source?

For what you want to do, you probably want to use the debian source diff, so your package is similar to the official one apart from the upstream version used. You can download the source diff from packages.debian.org, or can get it along with the .dsc and the original source archive by using "apt-get source".

Then you unpack your new version of the upstream source, change into that directory, and apply the diff you downloaded by doing

zcat ~/downloaded.diff.gz | patch -p1
chmod +x debian/rules

Then make the changes you wanted to compile options, and build the package by doing

dpkg-buildpackage -rfakeroot -us -uc

What does yield mean in PHP?

This function is using yield:

function a($items) {
    foreach ($items as $item) {
        yield $item + 1;
    }
}

It is almost the same as this one without:

function b($items) {
    $result = [];
    foreach ($items as $item) {
        $result[] = $item + 1;
    }
    return $result;
}

The only one difference is that a() returns a generator and b() just a simple array. You can iterate on both.

Also, the first one does not allocate a full array and is therefore less memory-demanding.

How to check if bootstrap modal is open, so I can use jquery validate?

You can use

$('#myModal').hasClass('in');

Bootstrap adds the in class when the modal is open and removes it when closed

Encrypt and decrypt a password in Java

You can use java.security.MessageDigest with SHA as your algorithm choice.

For reference,

Try available example here

Import SQL file into mysql

From the mysql console:

mysql> use DATABASE_NAME;

mysql> source path/to/file.sql;


make sure there is no slash before path if you are referring to a relative path... it took me a while to realize that! lol

add onclick function to a submit button

<button type="submit" name="uname" value="uname" onclick="browserlink(ex.google.com,home.html etc)or myfunction();"> submit</button>

if you want to open a page on the click of a button in HTML without any scripting language then you can use above code.

Disable Drag and Drop on HTML elements?

With jQuery it will be something like that:

$(document).ready(function() {
  $('#yourDiv').on('mousedown', function(e) {
      e.preventDefault();
  });
});

In my case I wanted to disable the user from drop text in the inputs so I used "drop" instead "mousedown".

$(document).ready(function() {
  $('input').on('drop', function(event) {
    event.preventDefault();
  });
});

Instead event.preventDefault() you can return false. Here's the difference.

And the code:

$(document).ready(function() {
  $('input').on('drop', function() {
    return false;
  });
});

Import CSV file with mixed data types

In R2013b or later you can use a table:

>> table = readtable('myfile.txt','Delimiter',';','ReadVariableNames',false)
>> table = 

    Var1    Var2     Var3     Var4     Var5        Var6          Var7         Var8      Var9    Var10
    ____    _____    _____    _____    _____    __________    __________    ________    ____    _____

      4     'abc'    'def'    'ghj'    'klm'    ''            ''            ''          NaN     NaN  
    NaN     ''       ''       ''       ''       'Test'        'text'        '0xFF'      NaN     NaN  
    NaN     ''       ''       ''       ''       'asdfhsdf'    'dsafdsag'    '0x0F0F'    NaN     NaN  

Here is more info.

Android: Force EditText to remove focus?

Add LinearLayout before EditText in your XML.

<LinearLayout 
    android:focusable="true"
    android:focusableInTouchMode="true" 
    android:clickable="true"
    android:layout_width="0px"
    android:layout_height="0px" />

Or you can do this same thing by adding these lines to view before your 'EditText'.

<Button
    android:id="@+id/btnSearch"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:focusable="true"
    android:focusableInTouchMode="true"
    android:gravity="center"
    android:text="Quick Search"
    android:textColor="#fff"
    android:textSize="13sp"
    android:textStyle="bold" />

<EditText
    android:id="@+id/edtSearch"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:layout_marginRight="5dp"
    android:gravity="left"
    android:hint="Name"
    android:maxLines="1"
    android:singleLine="true"
    android:textColorHint="@color/blue"
    android:textSize="13sp"
    android:textStyle="bold" />

Resize on div element

Just try this func (it may work not only for divs):

function resized(elem, func = function(){}, args = []){
    elem = jQuery(elem);
    func = func.bind(elem);
    var h = -1, w = -1;
    setInterval(function(){
        if (elem.height() != h || elem.width() != w){
            h = elem.height();
            w = elem.width();
            func.apply(null, args);
        }
    }, 100);
}

You can use it like this

resized(/*element*/ '.advs-columns-main > div > div', /*callback*/ function(a){
    console.log(a);
    console.log(this); //for accessing the jQuery element you passed
}, /*callback arguments in array*/ ['I\'m the first arg named "a"!']);

UPDATE: You can also use more progressive watcher (it can work for any objects, not only DOM elements):

function changed(elem, propsToBeChanged, func = function(){}, args = [], interval = 100){
        func = func.bind(elem);
        var currentVal = {call: {}, std: {}};
        $.each(propsToBeChanged, (property, needCall)=>{
            needCall = needCall ? 'call' : 'std';
            currentVal[needCall][property] = new Boolean(); // is a minimal and unique value, its equivalent comparsion with each other will always return false
        });
        setInterval(function(){
            $.each(propsToBeChanged, (property, needCall)=>{
                try{
                    var currVal = needCall ? elem[property]() : elem[property];
                } catch (e){ // elem[property] is not a function anymore
                    var currVal = elem[property];
                    needCall = false;
                    propsToBeChanged[property] = false;
                }
                needCall = needCall ? 'call' : 'std';
                if (currVal !== currentVal[needCall][property]){
                    currentVal[needCall][property] = currVal;
                    func.apply(null, args);
                }
            });
        }, interval);
    }

Just try it:

var b = '2',
    a = {foo: 'bar', ext: ()=>{return b}};
changed(a, {
// prop name || do eval like a function?
    foo:        false,
    ext:        true
}, ()=>{console.log('changed')})

It will log 'changed' every time when you change b, a.foo or a.ext directly

Class constants in python

Expanding on betabandido's answer, you could write a function to inject the attributes as constants into the module:

def module_register_class_constants(klass, attr_prefix):
    globals().update(
        (name, getattr(klass, name)) for name in dir(klass) if name.startswith(attr_prefix)
    )

class Animal(object):
    SIZE_HUGE = "Huge"
    SIZE_BIG = "Big"

module_register_class_constants(Animal, "SIZE_")

class Horse(Animal):
    def printSize(self):
        print SIZE_BIG

What is "String args[]"? parameter in main method Java

In Java args contains the supplied command-line arguments as an array of String objects.

In other words, if you run your program as java MyProgram one two then args will contain ["one", "two"].

If you wanted to output the contents of args, you can just loop through them like this...

public class ArgumentExample {
    public static void main(String[] args) {
        for(int i = 0; i < args.length; i++) {
            System.out.println(args[i]);
        }
    }
}

generate random double numbers in c++

If accuracy is an issue here you can create random numbers with a finer graduation by randomizing the significant bits. Let's assume we want to have a double between 0.0 and 1000.0.

On MSVC (12 / Win32) RAND_MAX is 32767 for example.

If you use the common rand()/RAND_MAX scheme your gaps will be as large as

1.0 / 32767.0 * ( 1000.0 - 0.0) = 0.0305 ...

In case of IEE 754 double variables (53 significant bits) and 53 bit randomization the smallest possible randomization gap for the 0 to 1000 problem will be

2^-53 * (1000.0 - 0.0) = 1.110e-13

and therefore significantly lower.

The downside is that 4 rand() calls will be needed to obtain the randomized integral number (assuming a 15 bit RNG).

double random_range (double const range_min, double const range_max)
{
  static unsigned long long const mant_mask53(9007199254740991);
  static double const i_to_d53(1.0/9007199254740992.0);
  unsigned long long const r( (unsigned long long(rand()) | (unsigned long long(rand()) << 15) | (unsigned long long(rand()) << 30) | (unsigned long long(rand()) << 45)) & mant_mask53 );
  return range_min + i_to_d53*double(r)*(range_max-range_min);
}

If the number of bits for the mantissa or the RNG is unknown the respective values need to be obtained within the function.

#include <limits>
using namespace std;
double random_range_p (double const range_min, double const range_max)
{
  static unsigned long long const num_mant_bits(numeric_limits<double>::digits), ll_one(1), 
    mant_limit(ll_one << num_mant_bits);
  static double const i_to_d(1.0/double(mant_limit));
  static size_t num_rand_calls, rng_bits;
  if (num_rand_calls == 0 || rng_bits == 0)
  {
    size_t const rand_max(RAND_MAX), one(1);
    while (rand_max > (one << rng_bits))
    {
      ++rng_bits;
    }
    num_rand_calls = size_t(ceil(double(num_mant_bits)/double(rng_bits)));
  }
  unsigned long long r(0);
  for (size_t i=0; i<num_rand_calls; ++i)
  {
    r |= (unsigned long long(rand()) << (i*rng_bits));
  }
  r = r & (mant_limit-ll_one);
  return range_min + i_to_d*double(r)*(range_max-range_min);
}

Note: I don't know whether the number of bits for unsigned long long (64 bit) is greater than the number of double mantissa bits (53 bit for IEE 754) on all platforms or not. It would probably be "smart" to include a check like if (sizeof(unsigned long long)*8 > num_mant_bits) ... if this is not the case.

HTML 'td' width and height

Following width worked well in HTML5: -

<table >
  <tr>
    <th style="min-width:120px">Month</th>
    <th style="min-width:60px">Savings</th>
  </tr>
  <tr>
    <td>January</td>
    <td>$100</td>
  </tr>
  <tr>
    <td>February</td>
    <td>$80</td>
  </tr>
</table>

Please note that

  • TD tag is without CSS style.

Windows: XAMPP vs WampServer vs EasyPHP vs alternative

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

Change image source with JavaScript

The problem was that you were using .src without needing it and you also needed to differentiate which img you wanted to change.

function changeImage(a, imgid) {
    document.getElementById(imgid).src=a;
}
<div id="main_img">
    <img id="img" src="1772031_29_b.jpg">
</div>
<div id="thumb_img">
    <img id="1" src='1772031_29_t.jpg'  onclick='changeImage("1772031_29_b.jpg", "1");'>
    <img id="2" src='1772031_55_t.jpg'  onclick='changeImage("1772031_55_b.jpg", "2");'>
    <img id="3" src='1772031_53_t.jpg'  onclick='changeImage("1772031_53_b.jpg", "3");'>
</div>

copy all files and folders from one drive to another drive using DOS (command prompt)

xcopy "C:\SomeFolderName" "D:\SomeFolderName" /h /i /c /k /e /r /y

Use the above command. It will definitely work.

In this command data will be copied from c:\ to D:\, even folders and system files as well. Here's what the flags do:

  • /h copies hidden and system files also
  • /i if destination does not exist and copying more than one file, assume that destination must be a directory
  • /c continue copying even if error occurs
  • /k copies attributes
  • /e copies directories and subdirectories, including empty ones
  • /r overwrites read-only files
  • /y suppress prompting to confirm whether you want to overwrite a file

Populating spinner directly in the layout xml

I'm not sure about this, but give it a shot.

In your strings.xml define:

<string-array name="array_name">
<item>Array Item One</item>
<item>Array Item Two</item>
<item>Array Item Three</item>
</string-array>

In your layout:

<Spinner 
        android:id="@+id/spinner"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:drawSelectorOnTop="true"
        android:entries="@array/array_name"
    />

I've heard this doesn't always work on the designer, but it compiles fine.

AWS S3 - How to fix 'The request signature we calculated does not match the signature' error?

For me I used axios and by deafult it sends header

content-type: application/x-www-form-urlencoded

so i change to send:

content-type: application/octet-stream

and also had to add this Content-Type to AWS signature

const params = {
    Bucket: bucket,
    Key: key,
    Expires: expires,
    ContentType = 'application/octet-stream'
}

const s3 = new AWS.S3()
s3.getSignedUrl('putObject', params)

'Framework not found' in Xcode

me too was getting this error , I moved the framework file to the root project folder and added to framework again and problem is solved.

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

To solve this issue you need to run your application by increasing the memory limit by using the option --max_old_space_size. By default the memory limit of Node.js is 512 mb.

node --max_old_space_size=2000  server.js 

ADB server version (36) doesn't match this client (39) {Not using Genymotion}

As mentioned by others here, that you could have two adb's running ... And to add to these answers from a Linux box perspective ( for the next newbie who is working from Linux );

  1. Uninstall your distro's android-tools ( use zypper or yum etc )

    # zypper -v rm android-tools
    
  2. Find where your other adb is

    # find /home -iname "*adb"|grep -i android
    

    Say it was at ;

    /home/developer/Android/Sdk/platform-tools/adb

  3. Then Make a softlink to it in the /usr/bin folder

     ln -s /home/developer/Android/Sdk/platform-tools/adb  /usr/bin/adb
    
  4. Then;

     # adb start-server
    

Angularjs autocomplete from $http

the easiest way to do that in angular or angularjs without external modules or directives is using list and datalist HTML5. You just get a json and use ng-repeat for feeding the options in datalist. The json you can fetch it from ajax.

in this example:

  • ctrl.query is the query that you enter when you type.
  • ctrl.msg is the message that is showing in the placeholder
  • ctrl.dataList is the json fetched

then you can add filters and orderby in the ng-reapet

!! list and datalist id must have the same name !!

 <input type="text" list="autocompleList" ng-model="ctrl.query" placeholder={{ctrl.msg}}>
<datalist id="autocompleList">
        <option ng-repeat="Ids in ctrl.dataList value={{Ids}}  >
</datalist>

UPDATE : is native HTML5 but be carreful with the type browser and version. check it out : https://caniuse.com/#search=datalist.

How to use greater than operator with date?

Adding this since this was not mentioned.

SELECT * FROM `la_schedule` WHERE date(start_date) > date('2012-11-18');

Because that's what actually works for me. Adding date() function on both comparison values.

Using Html.ActionLink to call action on different controller

this code worked for me in partial view:

<a href="/Content/[email protected]">@item.Title</a>

Swift error : signal SIGABRT how to solve it

If you run into this in Xcode 10 you will have to clean before build. Or, switch to the legacy build system. File -> Workspace Settings... -> Build System: Legacy Build System.

Extract file basename without path and extension in bash

Just an alternative that I came up with to extract an extension, using the posts in this thread with my own small knowledge base that was more familiar to me.

ext="$(rev <<< "$(cut -f "1" -d "." <<< "$(rev <<< "file.docx")")")"

Note: Please advise on my use of quotes; it worked for me but I might be missing something on their proper use (I probably use too many).

Simpler way to create dictionary of separate variables?

With python-varname you can easily do it:

pip install python-varname

from varname import Wrapper

foo = Wrapper(True)
bar = Wrapper(False)

your_dict = {val.name: val.value for val in (foo, bar)}

print(your_dict)

# {'foo': True, 'bar': False}

Disclaimer: I'm the author of that python-varname library.

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

SQL Update to the SUM of its joined values

Use a sub query similar to the below.

UPDATE P
SET extrasPrice = sub.TotalPrice from
BookingPitches p
inner join 
(Select PitchID, Sum(Price) TotalPrice
    from  dbo.BookingPitchExtras
    Where [Required] = 1
    Group by Pitchid
) as Sub
on p.Id = e.PitchId 
where p.BookingId = 1

How can I add an image file into json object?

You're only adding the File object to the JSON object. The File object only contains meta information about the file: Path, name and so on.

You must load the image and read the bytes from it. Then put these bytes into the JSON object.

REST API - why use PUT DELETE POST GET?

In short, REST emphasizes nouns over verbs. As your API becomes more complex, you add more things, rather than more commands.

Calculate average in java

If you're trying to get the integers from the command line args, you'll need something like this:

public static void main(String[] args) {
    int[] nums = new int[args.length];
    for(int i = 0; i < args.length; i++) {
        try {
            nums[i] = Integer.parseInt(args[i]);
        }
        catch(NumberFormatException nfe) {
            System.err.println("Invalid argument");
        }
    }

    // averaging code here
}

As for the actual averaging code, others have suggested how you can tweak that (so I won't repeat what they've said).

Edit: actually it's probably better to just put it inside the above loop and not use the nums array at all

Cannot find name 'require' after upgrading to Angular4

Will work in Angular 7+


I was facing the same issue, I was adding

"types": ["node"]

to tsconfig.json of root folder.

There was one more tsconfig.app.json under src folder and I got solved this by adding

"types": ["node"]

to tsconfig.app.json file under compilerOptions

{
  "extends": "../tsconfig.json",
  "compilerOptions": {
    "outDir": "../out-tsc/app",
    "types": ["node"]  ----------------------< added node to the array
  },
  "exclude": [
    "test.ts",
    "**/*.spec.ts"
  ]
}

Neither BindingResult nor plain target object for bean name available as request attribute

In the controller, you need to add the login object as an attribute of the model:

model.addAttribute("login", new Login());

Like this:

@RequestMapping(value = "/", method = RequestMethod.GET) 
public String displayLogin(Model model) { 
    model.addAttribute("login", new Login()); 
    return "login"; 
}

Error:java: invalid source release: 8 in Intellij. What does it mean?

I had the same issue the solution for me was to change my java version in the pom.xml file.

I changed it from 11 to 8. enter image description here

make: Nothing to be done for `all'

When you just give make, it makes the first rule in your makefile, i.e "all". You have specified that "all" depends on "hello", which depends on main.o, factorial.o and hello.o. So 'make' tries to see if those files are present.

If they are present, 'make' sees if their dependencies, e.g. main.o has a dependency main.c, have changed. If they have changed, make rebuilds them, else skips the rule. Similarly it recursively goes on building the files that have changed and finally runs the top most command, "all" in your case to give you a executable, 'hello' in your case.

If they are not present, make blindly builds everything under the rule.

Coming to your problem, it isn't an error but 'make' is saying that every dependency in your makefile is up to date and it doesn't need to make anything!

How to install APK from PC?

Just connect the device to the PC with a USB cable, then copy the .apk file to the device. On the device, touch the APK file in the file explorer to install it.

You could also offer the .apk on your website. People can download it, then touch it to install.

Extend contigency table with proportions (percentages)

I am not 100% certain, but I think this does what you want using prop.table. See mostly the last 3 lines. The rest of the code is just creating fake data.

set.seed(1234)

total_bill <- rnorm(50, 25, 3)
tip <- 0.15 * total_bill + rnorm(50, 0, 1)
sex <- rbinom(50, 1, 0.5)
smoker <- rbinom(50, 1, 0.3)
day <- ceiling(runif(50, 0,7))
time <- ceiling(runif(50, 0,3))
size <- 1 + rpois(50, 2)
my.data <- as.data.frame(cbind(total_bill, tip, sex, smoker, day, time, size))
my.data

my.table <- table(my.data$smoker)

my.prop <- prop.table(my.table)

cbind(my.table, my.prop)

Use space as a delimiter with cut command

To complement the existing, helpful answers; tip of the hat to QZ Support for encouraging me to post a separate answer:

Two distinct mechanisms come into play here:

  • (a) whether cut itself requires the delimiter (space, in this case) passed to the -d option to be a separate argument or whether it's acceptable to append it directly to -d.

  • (b) how the shell generally parses arguments before passing them to the command being invoked.

(a) is answered by a quote from the POSIX guidelines for utilities (emphasis mine)

If the SYNOPSIS of a standard utility shows an option with a mandatory option-argument [...] a conforming application shall use separate arguments for that option and its option-argument. However, a conforming implementation shall also permit applications to specify the option and option-argument in the same argument string without intervening characters.

In other words: In this case, because -d's option-argument is mandatory, you can choose whether to specify the delimiter as:

  • (s) EITHER: a separate argument
  • (d) OR: as a value directly attached to -d.

Once you've chosen (s) or (d), it is the shell's string-literal parsing - (b) - that matters:

  • With approach (s), all of the following forms are EQUIVALENT:

    • -d ' '
    • -d " "
    • -d \<space> # <space> used to represent an actual space for technical reasons
  • With approach (d), all of the following forms are EQUIVALENT:

    • -d' '
    • -d" "
    • "-d "
    • '-d '
    • d\<space>

The equivalence is explained by the shell's string-literal processing:

All solutions above result in the exact same string (in each group) by the time cut sees them:

  • (s): cut sees -d, as its own argument, followed by a separate argument that contains a space char - without quotes or \ prefix!.

  • (d): cut sees -d plus a space char - without quotes or \ prefix! - as part of the same argument.

The reason the forms in the respective groups are ultimately identical is twofold, based on how the shell parses string literals:

  • The shell allows literal to be specified as is through a mechanism called quoting, which can take several forms:
    • single-quoted strings: the contents inside '...' is taken literally and forms a single argument
    • double-quoted strings: the contents inside "..." also forms a single argument, but is subject to interpolation (expands variable references such as $var, command substitutions ($(...) or `...`), or arithmetic expansions ($(( ... ))).
    • \-quoting of individual characters: a \ preceding a single character causes that character to be interpreted as a literal.
  • Quoting is complemented by quote removal, which means that once the shell has parsed a command line, it removes the quote characters from the arguments (enclosing '...' or "..." or \ instances) - thus, the command being invoked never sees the quote characters.

FIND_IN_SET() vs IN()

SELECT  name
FROM    orders,company
WHERE   orderID = 1
        AND companyID IN (attachedCompanyIDs)

attachedCompanyIDs is a scalar value which is cast into INT (type of companyID).

The cast only returns numbers up to the first non-digit (a comma in your case).

Thus,

companyID IN ('1,2,3') = companyID IN (CAST('1,2,3' AS INT)) = companyID IN (1)

In PostgreSQL, you could cast the string into array (or store it as an array in the first place):

SELECT  name
FROM    orders
JOIN    company
ON      companyID = ANY (('{' | attachedCompanyIDs | '}')::INT[])
WHERE   orderID = 1

and this would even use an index on companyID.

Unfortunately, this does not work in MySQL since the latter does not support arrays.

You may find this article interesting (see #2):

Update:

If there is some reasonable limit on the number of values in the comma separated lists (say, no more than 5), so you can try to use this query:

SELECT  name
FROM    orders
CROSS JOIN
        (
        SELECT  1 AS pos
        UNION ALL
        SELECT  2 AS pos
        UNION ALL
        SELECT  3 AS pos
        UNION ALL
        SELECT  4 AS pos
        UNION ALL
        SELECT  5 AS pos
        ) q
JOIN    company
ON      companyID = CAST(NULLIF(SUBSTRING_INDEX(attachedCompanyIDs, ',', -pos), SUBSTRING_INDEX(attachedCompanyIDs, ',', 1 - pos)) AS UNSIGNED)

RegEx pattern any two letters followed by six numbers

You could try something like this:

[a-zA-Z]{2}[0-9]{6}

Here is a break down of the expression:

[a-zA-Z]    # Match a single character present in the list below
               # A character in the range between “a” and “z”
               # A character in the range between “A” and “Z”
   {2}         # Exactly 2 times
[0-9]       # Match a single character in the range between “0” and “9”
   {6}         # Exactly 6 times

This will match anywhere in a subject. If you need boundaries around the subject then you could do either of the following:

^[a-zA-Z]{2}[0-9]{6}$

Which ensures that the whole subject matches. I.e there is nothing before or after the subject.

or

\b[a-zA-Z]{2}[0-9]{6}\b

which ensures there is a word boundary on each side of the subject.

As pointed out by @Phrogz, you could make the expression more terse by replacing the [0-9] for a \d as in some of the other answers.

[a-zA-Z]{2}\d{6}

How do I dynamically assign properties to an object in TypeScript?

You can add this declaration to silence the warnings.

declare var obj: any;

How to uninstall mini conda? python

your have to comment that line in ~/.bashrc:

#export PATH=/home/jolth/miniconda3/bin:$PATH

and run:

source ~/.bashrc

How To: Execute command line in C#, get STD OUT results

Since the most answers here dont implement the using statemant for IDisposable and some other stuff wich I think could be nessecary I will add this answer.

For C# 8.0

// Start a process with the filename or path with filename e.g. "cmd". Please note the 
//using statemant
using myProcess.StartInfo.FileName = "cmd";
// add the arguments - Note add "/c" if you want to carry out tge  argument in cmd and  
// terminate
myProcess.StartInfo.Arguments = "/c dir";
// Allows to raise events
myProcess.EnableRaisingEvents = true;
//hosted by the application itself to not open a black cmd window
myProcess.StartInfo.UseShellExecute = false;
myProcess.StartInfo.CreateNoWindow = true;
// Eventhander for data
myProcess.Exited += OnOutputDataRecived;
// Eventhandler for error
myProcess.ErrorDataReceived += OnErrorDataReceived;
// Eventhandler wich fires when exited
myProcess.Exited += OnExited;
// Starts the process
myProcess.Start();
//read the output before you wait for exit
myProcess.BeginOutputReadLine();
// wait for the finish - this will block (leave this out if you dont want to wait for 
// it, so it runs without blocking)
process.WaitForExit();

// Handle the dataevent
private void OnOutputDataRecived(object sender, DataReceivedEventArgs e)
{
    //do something with your data
    Trace.WriteLine(e.Data);
}

//Handle the error
private void OnErrorDataReceived(object sender, DataReceivedEventArgs e)
{        
    Trace.WriteLine(e.Data);
    //do something with your exception
    throw new Exception();
}    

// Handle Exited event and display process information.
private void OnExited(object sender, System.EventArgs e)
{
     Trace.WriteLine("Process exited");
}

What happened to the .pull-left and .pull-right classes in Bootstrap 4?

Back in 2016 when this question was originally asked, the answer was:

$('.pull-right').addClass('pull-xs-right').removeClass('pull-right')

But now the accepted answer should be Robert Went's.

What is tail recursion?

Consider a simple function that adds the first N natural numbers. (e.g. sum(5) = 1 + 2 + 3 + 4 + 5 = 15).

Here is a simple JavaScript implementation that uses recursion:

function recsum(x) {
    if (x === 1) {
        return x;
    } else {
        return x + recsum(x - 1);
    }
}

If you called recsum(5), this is what the JavaScript interpreter would evaluate:

recsum(5)
5 + recsum(4)
5 + (4 + recsum(3))
5 + (4 + (3 + recsum(2)))
5 + (4 + (3 + (2 + recsum(1))))
5 + (4 + (3 + (2 + 1)))
15

Note how every recursive call has to complete before the JavaScript interpreter begins to actually do the work of calculating the sum.

Here's a tail-recursive version of the same function:

function tailrecsum(x, running_total = 0) {
    if (x === 0) {
        return running_total;
    } else {
        return tailrecsum(x - 1, running_total + x);
    }
}

Here's the sequence of events that would occur if you called tailrecsum(5), (which would effectively be tailrecsum(5, 0), because of the default second argument).

tailrecsum(5, 0)
tailrecsum(4, 5)
tailrecsum(3, 9)
tailrecsum(2, 12)
tailrecsum(1, 14)
tailrecsum(0, 15)
15

In the tail-recursive case, with each evaluation of the recursive call, the running_total is updated.

Note: The original answer used examples from Python. These have been changed to JavaScript, since Python interpreters don't support tail call optimization. However, while tail call optimization is part of the ECMAScript 2015 spec, most JavaScript interpreters don't support it.

How to deal with a slow SecureRandom generator?

There is a tool (on Ubuntu at least) that will feed artificial randomness into your system. The command is simply:

rngd -r /dev/urandom

and you may need a sudo at the front. If you don't have rng-tools package, you will need to install it. I tried this, and it definitely helped me!

Source: matt vs world

Showing data values on stacked bar chart in ggplot2

As hadley mentioned there are more effective ways of communicating your message than labels in stacked bar charts. In fact, stacked charts aren't very effective as the bars (each Category) doesn't share an axis so comparison is hard.

It's almost always better to use two graphs in these instances, sharing a common axis. In your example I'm assuming that you want to show overall total and then the proportions each Category contributed in a given year.

library(grid)
library(gridExtra)
library(plyr)

# create a new column with proportions
prop <- function(x) x/sum(x)
Data <- ddply(Data,"Year",transform,Share=prop(Frequency))

# create the component graphics
totals <- ggplot(Data,aes(Year,Frequency)) + geom_bar(fill="darkseagreen",stat="identity") + 
  xlab("") + labs(title = "Frequency totals in given Year")
proportion <- ggplot(Data, aes(x=Year,y=Share, group=Category, colour=Category)) 
+ geom_line() + scale_y_continuous(label=percent_format())+ theme(legend.position = "bottom") + 
  labs(title = "Proportion of total Frequency accounted by each Category in given Year")

# bring them together
grid.arrange(totals,proportion)

This will give you a 2 panel display like this:

Vertically stacked 2 panel graphic

If you want to add Frequency values a table is the best format.