Programs & Examples On #Klocwork

Klocwork Insight is a static source code analysis tool for C, C++, Java and C#.

What is the best way to trigger onchange event in react js

Expanding on the answer from Grin/Dan Abramov, this works across multiple input types. Tested in React >= 15.5

const inputTypes = [
    window.HTMLInputElement,
    window.HTMLSelectElement,
    window.HTMLTextAreaElement,
];

export const triggerInputChange = (node, value = '') => {

    // only process the change on elements we know have a value setter in their constructor
    if ( inputTypes.indexOf(node.__proto__.constructor) >-1 ) {

        const setValue = Object.getOwnPropertyDescriptor(node.__proto__, 'value').set;
        const event = new Event('input', { bubbles: true });

        setValue.call(node, value);
        node.dispatchEvent(event);

    }

};

How to solve "The specified service has been marked for deletion" error

I was having this issue when I was using Application Verifier to verify my win service. Even after I closed App Ver my service was blocked from deletion. Only removing the service from App Ver resolved the issue and service was deleted right away. Looks like some process still using your service after you tried to delete one.

Best way to store a key=>value array in JavaScript?

That's just what a JavaScript object is:

var myArray = {id1: 100, id2: 200, "tag with spaces": 300};
myArray.id3 = 400;
myArray["id4"] = 500;

You can loop through it using for..in loop:

for (var key in myArray) {
  console.log("key " + key + " has value " + myArray[key]);
}

See also: Working with objects (MDN).

In ECMAScript6 there is also Map (see the browser compatibility table there):

  • An Object has a prototype, so there are default keys in the map. This could be bypassed by using map = Object.create(null) since ES5, but was seldomly done.

  • The keys of an Object are Strings and Symbols, where they can be any value for a Map.

  • You can get the size of a Map easily while you have to manually keep track of size for an Object.

Double free or corruption after queue::push

Um, shouldn't the destructor be calling delete, rather than delete[]?

clientHeight/clientWidth returning different values on different browsers

It may be caused by IE's box model bug. To fix this, you can use the Box Model Hack.

How do I find where JDK is installed on my windows machine?

Plain and simple on Windows platforms:

where java

Is there an XSL "contains" directive?

From Zvon.org XSLT Reference:

XPath function: boolean contains (string, string) 

Hope this helps.

Sheet.getRange(1,1,1,12) what does the numbers in bracket specify?

Found these docu on the google docu pages:

  • row --- int --- top row of the range
  • column --- int--- leftmost column of the range
  • optNumRows --- int --- number of rows in the range.
  • optNumColumns --- int --- number of columns in the range

In your example, you would get (if you picked the 3rd row) "C3:O3", cause C --> O is 12 columns

edit

Using the example on the docu:

// The code below will get the number of columns for the range C2:G8
// in the active spreadsheet, which happens to be "4"
var count = SpreadsheetApp.getActiveSheet().getRange(2, 3, 6, 4).getNumColumns(); Browser.msgBox(count);

The values between brackets:
2: the starting row = 2
3: the starting col = C
6: the number of rows = 6 so from 2 to 8
4: the number of cols = 4 so from C to G

So you come to the range: C2:G8

Call to undefined function curl_init().?

The CURL extension ext/curl is not installed or enabled in your PHP installation. Check the manual for information on how to install or enable CURL on your system.

List All Google Map Marker Images

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|00D900",
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(12, 18)
);

Error in file(file, "rt") : cannot open the connection

The reason why you see this error I guess is because RStudio lost the path of your working directory.

(1) Go to session...

(2) Set working directory...

(3) Choose directory...

--> Then you can see a window pops up.

--> Choose the folder where you store your data.

This is the way without any code that you change your working directory. Hope this can help you.

enter image description here

How to make a smaller RatingBar?

There is no need to add a listener to the ?android:attr/ratingBarStyleSmall. Just add android:isIndicator=false and it will capture click events, e.g.

<RatingBar
  android:id="@+id/myRatingBar"
  style="?android:attr/ratingBarStyleSmall"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  android:numStars="5"
  android:isIndicator="false" />

Setting and getting localStorage with jQuery

You said you are attempting to get the text from a div and store it on local storage.

Please Note: Text and Html are different. In the question you mentioned text. html() will return Html content like <a>example</a>. if you want to get Text content then you have to use text() instead of html() then the result will be example instead of <a>example<a>. Anyway, I am using your terminology let it be Text.

Step 1: get the text from div.

what you did is not get the text from div but set the text to a div.

$('#test').html("Test"); 

is actually setting text to div and the output will be a jQuery object. That is why it sets it as [object Object].

To get the text you have to write like this
$('#test').html();

This will return a string not an object so the result will be Test in your case.

Step 2: set it to local storage.

Your approach is correct and you can write it as

localStorage.key=value

But the preferred approach is

localStorage.setItem(key,value); to set

localStorage.getItem(key); to get.

key and value must be strings.

so in your context code will become

$('#test').html("Test");
localStorage.content = $('#test').html();
$('#test').html(localStorage.content);

But I don't find any meaning in your code. Because you want to get the text from div and store it on local storage. And again you are reading the same from local storage and set to div. just like a=10; b=a; a=b;

If you are facing any other problems please update your question accordingly.

How to set the title text color of UIButton?

This is swift 5 compatible answer. If you want to use one of the built-in colours then you can simply use

button.setTitleColor(.red, for: .normal)

If you want some custom colours, then create an extension for a UIColor as below first.

import UIKit
extension UIColor {
    static var themeMoreButton = UIColor.init(red: 53/255, green: 150/255, blue: 36/255, alpha: 1)
}

Then use it for your button as below.

button.setTitleColor(UIColor.themeMoreButton, for: .normal)

Tip: You can use this method to store custom colours from rgba colour code and reuse it throughout your application.

CSS background image in :after element

As AlienWebGuy said, you can use background-image. I'd suggest you use background, but it will need three more properties after the URL:

background: url("http://www.gentleface.com/i/free_toolbar_icons_16x16_black.png") 0 0 no-repeat;

Explanation: the two zeros are x and y positioning for the image; if you want to adjust where the background image displays, play around with these (you can use both positive and negative values, e.g: 1px or -1px).

No-repeat says you don't want the image to repeat across the entire background. This can also be repeat-x and repeat-y.

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

Changing the default title of confirm() in JavaScript?

Not possible. You can however use a third party javascript library that emulates a popup window, and it will probably look better as well and be less intrusive.

server error:405 - HTTP verb used to access this page is not allowed

In my case, IIS was fine but.. uh.. all the files in the folder except web.config had been deleted (a manual deployment half-done on a test site).

Get value of Span Text

Judging by your other post: How to Get the inner text of a span in PHP. You're quite new to web programming, and need to learn about the differences between code on the client (JavaScript) and code on the server (PHP).

As for the correct approach to grabbing the span text from the client I recommend Johns answer.

These are a good place to get started.

JavaScript: https://stackoverflow.com/questions/11246/best-resources-to-learn-javascript

PHP: https://stackoverflow.com/questions/772349/what-is-a-good-online-tutorial-for-php

Also I recommend using jQuery (Once you've got some JavaScript practice) it will eliminate most of the cross-browser compatability issues that you're going to have. But don't use it as a crutch to learn on, it's good to understand JavaScript too. http://jquery.com/

How can I determine the URL that a local Git repository was originally cloned from?

The upstream's remote may not be called "origin", so here's a variation:

remote=$(git config --get branch.master.remote)
url=$(git config --get remote.$remote.url)
basename=$(basename "$url" .git)
echo $basename

Or:

basename $(git config --get remote.$(git config --get branch.master.remote).url) .git

For more useful variables there's:

$ git config -l

Invalid self signed SSL cert - "Subject Alternative Name Missing"

I had so many issues getting self-signed certificates working on macos/Chrome. Finally I found Mkcert, "A simple zero-config tool to make locally trusted development certificates with any names you'd like." https://github.com/FiloSottile/mkcert

curl Failed to connect to localhost port 80

I also had problem with refused connection on port 80. I didn't use localhost.

curl --data-binary "@/textfile.txt" "http://www.myserver.com/123.php"

Problem was that I had umlauts äåö in my textfile.txt.

For loop in multidimensional javascript array

An efficient way to loop over an Array is the built-in array method .map()

For a 1-dimensional array it would look like this:

function HandleOneElement( Cuby ) {
   Cuby.dimension
   Cuby.position_x
   ...
}
cubes.map(HandleOneElement) ; // the map function will pass each element

for 2-dimensional array:

cubes.map( function( cubeRow ) { cubeRow.map( HandleOneElement ) } )

for an n-dimensional array of any form:

Function.prototype.ArrayFunction = function(param) {
  if (param instanceof Array) {
    return param.map( Function.prototype.ArrayFunction, this ) ;
  }
  else return (this)(param) ;
}
HandleOneElement.ArrayFunction(cubes) ;

Can't use SURF, SIFT in OpenCV

Just change the version of opencv to 3.4.2.16 .Since it is patented it is not available in newer version.

Splitting string into multiple rows in Oracle

Without using connect by or regexp:

    with mytable as (
      select 108 name, 'test' project, 'Err1,Err2,Err3' error from dual
      union all
      select 109, 'test2', 'Err1' from dual
    )
    ,x as (
      select name
      ,project
      ,','||error||',' error
      from mytable
    )
    ,iter as (SELECT rownum AS pos
        FROM all_objects
    )
    select x.name,x.project
    ,SUBSTR(x.error
      ,INSTR(x.error, ',', 1, iter.pos) + 1
      ,INSTR(x.error, ',', 1, iter.pos + 1)-INSTR(x.error, ',', 1, iter.pos)-1
    ) error
    from x, iter
    where iter.pos < = (LENGTH(x.error) - LENGTH(REPLACE(x.error, ','))) - 1;

Explanation of BASE terminology

ACID and BASE are consistency models for RDBMS and NoSQL respectively. ACID transactions are far more pessimistic i.e. they are more worried about data safety. In the NoSQL database world, ACID transactions are less fashionable as some databases have loosened the requirements for immediate consistency, data freshness and accuracy in order to gain other benefits, like scalability and resiliency.

BASE stands for -

  • Basic Availability - The database appears to work most of the time.
  • Soft-state - Stores don't have to be write-consistent, nor do different replicas have to be mutually consistent all the time.
  • Eventual consistency - Stores exhibit consistency at some later point (e.g., lazily at read time).

Therefore BASE relaxes consistency to allow the system to process request even in an inconsistent state.

Example: No one would mind if their tweet were inconsistent within their social network for a short period of time. It is more important to get an immediate response than to have a consistent state of users' information.

How do I make a stored procedure in MS Access?

If you mean the type of procedure you find in SQL Server, prior to 2010, you can't. If you want a query that accepts a parameter, you can use the query design window:

 PARAMETERS SomeParam Text(10);
 SELECT Field FROM Table
 WHERE OtherField=SomeParam

You can also say:

CREATE PROCEDURE ProcedureName
   (Parameter1 datatype, Parameter2 datatype) AS
   SQLStatement

From: http://msdn.microsoft.com/en-us/library/aa139977(office.10).aspx#acadvsql_procs

Note that the procedure contains only one statement.

Change color when hover a font awesome icon?

if you want to change only the colour of the flag on hover use this:

http://jsfiddle.net/uvamhedx/

_x000D_
_x000D_
.fa-flag:hover {_x000D_
    color: red;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>_x000D_
_x000D_
<i class="fa fa-flag fa-3x"></i>
_x000D_
_x000D_
_x000D_

Filtering a pyspark dataframe using isin by exclusion

Got a gotcha for those with their headspace in Pandas and moving to pyspark

 from pyspark import SparkConf, SparkContext
 from pyspark.sql import SQLContext

 spark_conf = SparkConf().setMaster("local").setAppName("MyAppName")
 sc = SparkContext(conf = spark_conf)
 sqlContext = SQLContext(sc)

 records = [
     {"colour": "red"},
     {"colour": "blue"},
     {"colour": None},
 ]

 pandas_df = pd.DataFrame.from_dict(records)
 pyspark_df = sqlContext.createDataFrame(records)

So if we wanted the rows that are not red:

pandas_df[~pandas_df["colour"].isin(["red"])]

As expected in Pandas

Looking good, and in our pyspark DataFrame

pyspark_df.filter(~pyspark_df["colour"].isin(["red"])).collect()

Not what I expected

So after some digging, I found this: https://issues.apache.org/jira/browse/SPARK-20617 So to include nothingness in our results:

pyspark_df.filter(~pyspark_df["colour"].isin(["red"]) | pyspark_df["colour"].isNull()).show()

much ado about nothing

Better way to find index of item in ArrayList?

Java API specifies two methods you could use: indexOf(Object obj) and lastIndexOf(Object obj). The first one returns the index of the element if found, -1 otherwise. The second one returns the last index, that would be like searching the list backwards.

Find row number of matching value

For your first method change ws.Range("A") to ws.Range("A:A") which will search the entirety of column a, like so:

Sub Find_Bingo()

        Dim wb As Workbook
        Dim ws As Worksheet
        Dim FoundCell As Range
        Set wb = ActiveWorkbook
        Set ws = ActiveSheet

            Const WHAT_TO_FIND As String = "Bingo"

            Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
            If Not FoundCell Is Nothing Then
                MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
            Else
                MsgBox (WHAT_TO_FIND & " not found")
            End If
End Sub

For your second method, you are using Bingo as a variable instead of a string literal. This is a good example of why I add Option Explicit to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.

Additionally, when you are using With...End With you need a period . before you reference Cells, so Cells should be .Cells. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)

Change Bingo to "Bingo" and change Cells to .Cells

With Sheet1
        Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
        LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
        SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
    End With

If Not FoundCell Is Nothing Then
        MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
        MsgBox ("Bingo not found")
End If

Update

In my

With Sheet1
    .....
End With

The Sheet1 refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1. I can refer to that in code either with the code name of Sheet1 or I can refer to it with the index of Sheets("Sheet1"). The advantage to using a codename is that it does not change if you change the name of the worksheet.

Continuing this example, let's say I renamed Sheet1 to Data. Using Sheet1 would continue to work, as the code name doesn't change, but now using Sheets("Sheet1") would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data").

In the VB Editor you would see something like this:

code object explorer example

Notice how, even though I changed the name to Data, there is still a Sheet1 to the left. That is what I mean by codename.

The Data worksheet can be referenced in two ways:

Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name

Both should return Data

More discussion on worksheet code names can be found here.

How to add a hook to the application context initialization event?

Create your annotation

  @Retention(RetentionPolicy.RUNTIME)
    public @interface AfterSpringLoadComplete {
    }

Create class

    public class PostProxyInvokerContextListener implements ApplicationListener<ContextRefreshedEvent> {

    @Autowired
    ConfigurableListableBeanFactory factory;

    @Override
    public void onApplicationEvent(ContextRefreshedEvent event) {
        ApplicationContext context = event.getApplicationContext();
        String[] names = context.getBeanDefinitionNames();
        for (String name : names) {
            try {
                BeanDefinition definition = factory.getBeanDefinition(name);
                String originalClassName = definition.getBeanClassName();
                Class<?> originalClass = Class.forName(originalClassName);
                Method[] methods = originalClass.getMethods();
                for (Method method : methods) {
                    if (method.isAnnotationPresent(AfterSpringLoadComplete.class)){
                        Object bean = context.getBean(name);
                        Method currentMethod = bean.getClass().getMethod(method.getName(), method.getParameterTypes());
                        currentMethod.invoke(bean);
                    }
                }
            } catch (Exception ignored) {
            }
        }
    }
}

Register this class by @Component annotation or in xml

<bean class="ua.adeptius.PostProxyInvokerContextListener"/>

and use annotation where you wan on any method that you want to run after context initialized, like:

   @AfterSpringLoadComplete
    public void init() {}

Selecting all text in HTML text input when clicked

Here's a reusable version of Shoban's answer:

<input type="text" id="userid" name="userid"
 value="Please enter the user ID" onfocus="Clear(this);"
/>

function Clear(elem)
{
elem.value='';
}

That way you can reuse the clear script for multiple elements.

Run a string as a command within a Bash script

For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}' was working fine but unable to store output of command into variable. I had same issue I tried eval but didn't got output.

Here is answer for my problem: cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')

echo $cmd

My output is now 20200824

MySQL: how to get the difference between two timestamps in seconds

UNIX_TIMESTAMP(ts1) - UNIX_TIMESTAMP(ts2)

If you want an unsigned difference, add an ABS() around the expression.

Alternatively, you can use TIMEDIFF(ts1, ts2) and then convert the time result to seconds with TIME_TO_SEC().

Update just one gem with bundler

Here you can find a good explanation on the difference between

Update both gem and dependencies:

bundle update gem-name 

or

Update exclusively the gem:

bundle update --source gem-name

along with some nice examples of possible side-effects.

Update

As @Tim's answer says, as of Bundler 1.14 the officially-supported way to this is with bundle update --conservative gem-name.

Is there a way to programmatically scroll a scroll view to a specific edit text?

In my opinion the best way to scroll to a given rectangle is via View.requestRectangleOnScreen(Rect, Boolean). You should call it on a View you want to scroll to and pass a local rectangle you want to be visible on the screen. The second parameter should be false for smooth scrolling and true for immediate scrolling.

final Rect rect = new Rect(0, 0, view.getWidth(), view.getHeight());
view.requestRectangleOnScreen(rect, false);

No Exception while type casting with a null in java

You can cast null to any reference type. You can also call methods which handle a null as an argument, e.g. System.out.println(Object) does, but you cannot reference a null value and call a method on it.

BTW There is a tricky situation where it appears you can call static methods on null values.

Thread t = null;
t.yield(); // Calls static method Thread.yield() so this runs fine.

JOptionPane Yes or No window

You are always checking for a true condition, hence your message will always show.

You should replace your if (true) statement with if ( n == JOptionPane.YES_OPTION)

When one of the showXxxDialog methods returns an integer, the possible values are:

YES_OPTION NO_OPTION CANCEL_OPTION OK_OPTION CLOSED_OPTION

From here

How do I resize an image using PIL and maintain its aspect ratio?

Just updating this question with a more modern wrapper This library wraps Pillow (a fork of PIL) https://pypi.org/project/python-resize-image/

Allowing you to do something like this :-

from PIL import Image
from resizeimage import resizeimage

fd_img = open('test-image.jpeg', 'r')
img = Image.open(fd_img)
img = resizeimage.resize_width(img, 200)
img.save('test-image-width.jpeg', img.format)
fd_img.close()

Heaps more examples in the above link.

Android: How to enable/disable option menu item on button click?

On all android versions, easiest way: use this to SHOW a menu action icon as disabled AND make it FUNCTION as disabled as well:

@Override
public boolean onPrepareOptionsMenu(Menu menu) {

    MenuItem item = menu.findItem(R.id.menu_my_item);

    if (myItemShouldBeEnabled) {
        item.setEnabled(true);
        item.getIcon().setAlpha(255);
    } else {
        // disabled
        item.setEnabled(false);
        item.getIcon().setAlpha(130);
    }
}

Fire event on enter key press for a textbox

<asp:Panel ID="Panel2" runat="server" DefaultButton="bttxt">
    <telerik:RadNumericTextBox ID="txt" runat="server">
    </telerik:RadNumericTextBox>
    <asp:LinkButton ID="bttxt" runat="server" Style="display: none;" OnClick="bttxt_Click" />
</asp:Panel>

 

protected void txt_TextChanged(object sender, EventArgs e)
{
    //enter code here
}

Adding a JAR to an Eclipse Java library

You might also consider using a build tool like Maven to manage your dependencies. It is very easy to setup and helps manage those dependencies automatically in eclipse. Definitely worth the effort if you have a large project with a lot of external dependencies.

Should I return EXIT_SUCCESS or 0 from main()?

EXIT_FAILURE, either in a return statement in main or as an argument to exit(), is the only portable way to indicate failure in a C or C++ program. exit(1) can actually signal successful termination on VMS, for example.

If you're going to be using EXIT_FAILURE when your program fails, then you might as well use EXIT_SUCCESS when it succeeds, just for the sake of symmetry.

On the other hand, if the program never signals failure, you can use either 0 or EXIT_SUCCESS. Both are guaranteed by the standard to signal successful completion. (It's barely possible that EXIT_SUCCESS could have a value other than 0, but it's equal to 0 on every implementation I've ever heard of.)

Using 0 has the minor advantage that you don't need #include <stdlib.h> in C, or #include <cstdlib> in C++ (if you're using a return statement rather than calling exit()) -- but for a program of any significant size you're going to be including stdlib directly or indirectly anyway.

For that matter, in C starting with the 1999 standard, and in all versions of C++, reaching the end of main() does an implicit return 0; anyway, so you might not need to use either 0 or EXIT_SUCCESS explicitly. (But at least in C, I consider an explicit return 0; to be better style.)

(Somebody asked about OpenVMS. I haven't used it in a long time, but as I recall odd status values generally denote success while even values denote failure. The C implementation maps 0 to 1, so that return 0; indicates successful termination. Other values are passed unchanged, so return 1; also indicates successful termination. EXIT_FAILURE would have a non-zero even value.)

Using numpy to build an array of all combinations of two arrays

Pandas merge offers a naive, fast solution to the problem:

# given the lists
x, y, z = [1, 2, 3], [4, 5], [6, 7]

# get dfs with same, constant index 
x = pd.DataFrame({'x': x}, index=np.repeat(0, len(x))
y = pd.DataFrame({'y': y}, index=np.repeat(0, len(y))
z = pd.DataFrame({'z': z}, index=np.repeat(0, len(z))

# get all permutations stored in a new df
df = pd.merge(x, pd.merge(y, z, left_index=True, righ_index=True),
              left_index=True, right_index=True)

What is the use of a private static variable in Java?

Of course it can be accessed as ClassName.var_name, but only from inside the class in which it is defined - that's because it is defined as private.

public static or private static variables are often used for constants. For example, many people don't like to "hard-code" constants in their code; they like to make a public static or private static variable with a meaningful name and use that in their code, which should make the code more readable. (You should also make such constants final).

For example:

public class Example {
    private final static String JDBC_URL = "jdbc:mysql://localhost/shopdb";
    private final static String JDBC_USERNAME = "username";
    private final static String JDBC_PASSWORD = "password";

    public static void main(String[] args) {
        Connection conn = DriverManager.getConnection(JDBC_URL,
                                         JDBC_USERNAME, JDBC_PASSWORD);

        // ...
    }
}

Whether you make it public or private depends on whether you want the variables to be visible outside the class or not.

Why is it faster to check if dictionary contains the key, rather than catch the exception in case it doesn't?

On the one hand, throwing exceptions is inherently expensive, because the stack has to be unwound etc.
On the other hand, accessing a value in a dictionary by its key is cheap, because it's a fast, O(1) operation.

BTW: The correct way to do this is to use TryGetValue

obj item;
if(!dict.TryGetValue(name, out item))
    return null;
return item;

This accesses the dictionary only once instead of twice.
If you really want to just return null if the key doesn't exist, the above code can be simplified further:

obj item;
dict.TryGetValue(name, out item);
return item;

This works, because TryGetValue sets item to null if no key with name exists.

UITableView load more when scrolling to bottom like Facebook application

You can do that by adding a check on where you're at in the cellForRowAtIndexPath: method. This method is easy to understand and to implement :

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // Classic start method
    static NSString *cellIdentifier = @"MyCell";
    MyCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if (!cell)
    {
        cell = [[MyCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:MainMenuCellIdentifier];
    }

    MyData *data = [self.dataArray objectAtIndex:indexPath.row];
    // Do your cell customisation
    // cell.titleLabel.text = data.title;

    BOOL lastItemReached = [data isEqual:[[self.dataArray] lastObject]]; 
    if (!lastItemReached && indexPath.row == [self.dataArray count] - 1)
    {
        [self launchReload];
    }
}

EDIT : added a check on last item to prevent recursion calls. You'll have to implement the method defining whether the last item has been reached or not.

EDIT2 : explained lastItemReached

How to deselect a selected UITableView cell?

Swift 3/4

In ViewController:

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
}

In Custom Cell:

override func awakeFromNib() {
    super.awakeFromNib()
    selectionStyle = .none
}

Construct pandas DataFrame from items in nested dictionary

A pandas MultiIndex consists of a list of tuples. So the most natural approach would be to reshape your input dict so that its keys are tuples corresponding to the multi-index values you require. Then you can just construct your dataframe using pd.DataFrame.from_dict, using the option orient='index':

user_dict = {12: {'Category 1': {'att_1': 1, 'att_2': 'whatever'},
                  'Category 2': {'att_1': 23, 'att_2': 'another'}},
             15: {'Category 1': {'att_1': 10, 'att_2': 'foo'},
                  'Category 2': {'att_1': 30, 'att_2': 'bar'}}}

pd.DataFrame.from_dict({(i,j): user_dict[i][j] 
                           for i in user_dict.keys() 
                           for j in user_dict[i].keys()},
                       orient='index')


               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

An alternative approach would be to build your dataframe up by concatenating the component dataframes:

user_ids = []
frames = []

for user_id, d in user_dict.iteritems():
    user_ids.append(user_id)
    frames.append(pd.DataFrame.from_dict(d, orient='index'))

pd.concat(frames, keys=user_ids)

               att_1     att_2
12 Category 1      1  whatever
   Category 2     23   another
15 Category 1     10       foo
   Category 2     30       bar

Hexadecimal To Decimal in Shell Script

To convert from hex to decimal, there are many ways to do it in the shell or with an external program:

With :

$ echo $((16#FF))
255

with :

$ echo "ibase=16; FF" | bc
255

with :

$ perl -le 'print hex("FF");'
255

with :

$ printf "%d\n" 0xFF
255

with :

$ python -c 'print(int("FF", 16))'
255

with :

$ ruby -e 'p "FF".to_i(16)'
255

with :

$ nodejs <<< "console.log(parseInt('FF', 16))"
255

with :

$ rhino<<EOF
print(parseInt('FF', 16))
EOF
...
255

with :

$ groovy -e 'println Integer.parseInt("FF",16)'
255

LEFT JOIN in LINQ to entities?

You can read an article i have written for joins in LINQ here

var query = 
from  u in Repo.T_Benutzer
join bg in Repo.T_Benutzer_Benutzergruppen
    on u.BE_ID equals bg.BEBG_BE
into temp
from j in temp.DefaultIfEmpty()
select new
{
    BE_User = u.BE_User,
    BEBG_BG = (int?)j.BEBG_BG// == null ? -1 : j.BEBG_BG
            //, bg.Name 
}

The following is the equivalent using extension methods:

var query = 
Repo.T_Benutzer
.GroupJoin
(
    Repo.T_Benutzer_Benutzergruppen,
    x=>x.BE_ID,
    x=>x.BEBG_BE,
    (o,i)=>new {o,i}
)
.SelectMany
(
    x => x.i.DefaultIfEmpty(),
    (o,i) => new
    {
        BE_User = o.o.BE_User,
        BEBG_BG = (int?)i.BEBG_BG
    }
);

How to add items to array in nodejs

var array = [];

//length array now = 0
array[array.length] = 'hello';
//length array now = 1
//            0
//array = ['hello'];//length = 1

How can I catch all the exceptions that will be thrown through reading and writing a file?

Do you mean catch an Exception of any type that is thrown, as opposed to just specific Exceptions?

If so:

try {
   //...file IO...
} catch(Exception e) {
   //...do stuff with e, such as check its type or log it...
}

How to set column widths to a jQuery datatable?

Configuration Options:

$(document).ready(function () {

  $("#companiesTable").dataTable({
    "sPaginationType": "full_numbers",
    "bJQueryUI": true,
    "bAutoWidth": false, // Disable the auto width calculation 
    "aoColumns": [
      { "sWidth": "30%" }, // 1st column width 
      { "sWidth": "30%" }, // 2nd column width 
      { "sWidth": "40%" } // 3rd column width and so on 
    ]
  });
});

Specify the css for the table:

table.display {
  margin: 0 auto;
  width: 100%;
  clear: both;
  border-collapse: collapse;
  table-layout: fixed;         // add this 
  word-wrap:break-word;        // add this 
}

HTML:

<table id="companiesTable" class="display"> 
  <thead>
    <tr>
      <th>Company name</th>
      <th>Address</th>
      <th>Town</th>
    </tr>
  </thead>
  <tbody>

    <% for(Company c: DataRepository.GetCompanies()){ %>
      <tr>  
        <td><%=c.getName()%></td>
        <td><%=c.getAddress()%></td>
        <td><%=c.getTown()%></td>
      </tr>
    <% } %>

  </tbody>
</table>

It works for me!

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

To switch between tabs action class does not always works on all browser and on all webdriver. the best way is to use robot class. try this code.

        String website = "https://www.google.com";
        String website1 = "https://www.msn.com/en-in/";
        String controlpath = "C:\\Libraries\\msedgedriver.exe";
        System.setProperty("webdriver.edge.driver", controlpath);
        driver = new EdgeDriver();
        driver.manage().window().maximize(); //  Maximize browser
        driver.get(website);
        System.out.println("Google page");
        
        Robot robot = new Robot();                          
        robot.keyPress(KeyEvent.VK_CONTROL); 
        robot.keyPress(KeyEvent.VK_T); 
        robot.keyRelease(KeyEvent.VK_CONTROL); 
        robot.keyRelease(KeyEvent.VK_T);
        
        //Switch focus to new tab
        ArrayList<String> tabs = new ArrayList<String> (driver.getWindowHandles());
        //System.out.println("Handle info"+ driver.getWindowHandles());
        driver.switchTo().window(tabs.get(1));
    
        //Launch URL in the new tab
        driver.get(website1);
        System.out.println("msn page");
        Thread.sleep(5000);
        driver.switchTo().window(tabs.get(0));
        Thread.sleep(5000);

How to send a JSON object using html form data

The accepted answer is out of date; nowadays you can simply add enctype="application/json" to your form tag and the browser will jsonify the data automatically.

The spec for this behavior is here: https://www.w3.org/TR/html-json-forms/

PHP/MySQL insert row then get 'id'

Another possible answer will be:

When you define the table, with the columns and data it'll have. The column id can have the property AUTO_INCREMENT.

By this method, you don't have to worry about the id, it'll be made automatically.

For example (taken from w3schools )

CREATE TABLE Persons
(
ID int NOT NULL AUTO_INCREMENT,
LastName varchar(255) NOT NULL,
FirstName varchar(255),
Address varchar(255),
City varchar(255),
PRIMARY KEY (ID)
)

Hope this will be helpful for someone.

Edit: This is only the part where you define how to generate an automatic ID, to obtain it after created, the previous answers before are right.

Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ' '

For the OP's command:

select compid,2, convert(datetime, '01/01/' + CONVERT(char(4),cal_yr) ,101) ,0,  Update_dt, th1, th2, th3_pc , Update_id, Update_dt,1
from  #tmp_CTF** 

I get this error:

Msg 102, Level 15, State 1, Line 2
Incorrect syntax near '*'.

when debugging something like this split the long line up so you'll get a better row number:

select compid
,2
, convert(datetime
, '01/01/' 
+ CONVERT(char(4)
,cal_yr) 
,101) 
,0
,  Update_dt
, th1
, th2
, th3_pc 
, Update_id
, Update_dt
,1
from  #tmp_CTF** 

this now results in:

Msg 102, Level 15, State 1, Line 16
Incorrect syntax near '*'.

which is probably just from the OP not putting the entire command in the question, or use [ ] braces to signify the table name:

from [#tmp_CTF**]

if that is the table name.

Your password does not satisfy the current policy requirements

There are some moments where finding a quick solution is great. But if you can avoid lowing passwords restrictions, it can keep you from having big headache in future.

Next link is from the official documentation https://dev.mysql.com/doc/refman/5.6/en/validate-password.html, where they expose an example exactly like your one, and they solve it.

The only one problem you have is that your password is not strong enough to satisfy the actual minimum policy (not recommended to remove). So you can try different passwords as you can see in the example.

CodeIgniter: Create new helper?

Just define a helper in application helper directory then call from your controller just function name like

helper name = new_helper.php
function test_method($data){
 return $data
}   

in controller load the helper

$this->load->new_helper();
$result =  test_method('Hello world!');
if($result){
 echo $result
}

output will be

Hello World!

java.io.StreamCorruptedException: invalid stream header: 7371007E

If you are sending multiple objects, it's often simplest to put them some kind of holder/collection like an Object[] or List. It saves you having to explicitly check for end of stream and takes care of transmitting explicitly how many objects are in the stream.

EDIT: Now that I formatted the code, I see you already have the messages in an array. Simply write the array to the object stream, and read the array on the server side.

Your "server read method" is only reading one object. If it is called multiple times, you will get an error since it is trying to open several object streams from the same input stream. This will not work, since all objects were written to the same object stream on the client side, so you have to mirror this arrangement on the server side. That is, use one object input stream and read multiple objects from that.

(The error you get is because the objectOutputStream writes a header, which is expected by objectIutputStream. As you are not writing multiple streams, but simply multiple objects, then the next objectInputStream created on the socket input fails to find a second header, and throws an exception.)

To fix it, create the objectInputStream when you accept the socket connection. Pass this objectInputStream to your server read method and read Object from that.

Using the Web.Config to set up my SQL database connection string?

http://www.connectionstrings.com is a site where you can find a lot of connection strings. All that you need to do is copy-paste and modify it to suit your needs. It is sure to have all the connection strings for all of your needs.

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Move entire line up and down in Vim

:m.+1 or :m.-2 would do if you're moving a single line. Here's my script to move multiple lines. In visual mode, Alt-up/Alt-down will move the lines containing the visual selection up/down by one line. In insert mode or normal mode, Alt-up/Alt-down will move the current line if no count prefix is given. If there's a count prefix, Alt-up/Alt-down will move that many lines beginning from the current line up/down by one line.

function! MoveLines(offset) range
    let l:col = virtcol('.')
    let l:offset = str2nr(a:offset)
    exe 'silent! :' . a:firstline . ',' . a:lastline . 'm'
        \ . (l:offset > 0 ? a:lastline + l:offset : a:firstline + l:offset)
    exe 'normal ' . l:col . '|'
endf

imap <silent> <M-up> <C-O>:call MoveLines('-2')<CR>
imap <silent> <M-down> <C-O>:call MoveLines('+1')<CR>
nmap <silent> <M-up> :call MoveLines('-2')<CR>
nmap <silent> <M-down> :call MoveLines('+1')<CR>
vmap <silent> <M-up> :call MoveLines('-2')<CR>gv
vmap <silent> <M-down> :call MoveLines('+1')<CR>gv

jQuery Combobox/select autocomplete?

I know this has been said earlier, but jQuery Autocomplete will do exactly what you need. You should check out the docs as the autocomplete is very customizable. If you are familiar with javascript then you should be able to work this out. If not I can give you a few pointers, as I have done this once before, but beware I am not well versed in javascript myself either, so bear with me on this.

I think the first thing you should do is just get a simple autocomplete text field working on your page, and then you can customize it from there.

The autocomplete widget accepts JSON data as it's 'source:' option. So you should set-up your app to produce the 20 top level categories, and subcategories in JSON format.

The next thing to know is that when the user types into your textfield, the autocomplete widget will send the typed values in a parameter called "term".

So let's say you first set-up your site to deliver the JSON data from a URL like this:

/categories.json

Then your autocomplete source: option would be 'source: /categories.json'.

When a user types into the textfield, such as 'first-cata...' the autocomplete widget will start sending the value in the 'term' parameter like this:

/categories.json?term=first-cata

This will return JSON data back to the widget filtered by anything that matches 'first-cata', and this is displayed as an autocomplete suggestion.

I am not sure what you are programming in, but you can specify how the 'term' parameter finds a match. So you can customize this, so that the term finds a match in the middle of a word if you want. Example, if the user types 'or' you code could make a match on 'sports'.

Lastly, you made a comment that you want to be able to select a category name but have the autocomplete widget submit the category ID not the name.

This can easily be done with a hidden field. This is what is shown in the jQuery autocomplete docs.

When a user selects a category, your JavaScript should update a hidden field with the ID.

I know this answer is not very detailed, but that is mainly because I am not sure what you are programming in, but the above should point you in the right direction. The thing to know is that you can do practically any customizing you want with this widget, if you are willing to spend the time to learn it.

These are the broad strokes, but you can look here for some notes I made when I implemented something similar to what you want in a Rails app.

Hope this helped.

move_uploaded_file gives "failed to open stream: Permission denied" error

It happens if SELinux is enabled. Disable that in /etc/selinux/config by setting SELINUX=disabled and restart the server.

How to Get enum item name from its value

I have had excellent success with a technique which resembles the X macros pointed to by @RolandXu. We made heavy use of the stringize operator, too. The technique mitigates the maintenance nightmare when you have an application domain where items appear both as strings and as numerical tokens.

It comes in particularily handy when machine readable documentation is available so that the macro X(...) lines can be auto-generated. A new documentation would immediately result in a consistent program update covering the strings, enums and the dictionaries translating between them in both directions. (We were dealing with PCL6 tokens).

And while the preprocessor code looks pretty ugly, all those technicalities can be hidden in the header files which never have to be touched again, and neither do the source files. Everything is type safe. The only thing that changes is a text file containing all the X(...) lines, and that is possibly auto generated.

Can you put two conditions in an xslt test attribute?

Not quite, the AND has to be lower-case.

<xsl:when test="4 &lt; 5 and 1 &lt; 2">
<!-- do something -->
</xsl:when>

Pointer to 2D arrays in C

//defines an array of 280 pointers (1120 or 2240 bytes)
int  *pointer1 [280];

//defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
int (*pointer2)[280];      //pointer to an array of 280 integers
int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers

Using pointer2 or pointer3 produce the same binary except manipulations as ++pointer2 as pointed out by WhozCraig.

I recommend using typedef (producing same binary code as above pointer3)

typedef int myType[100][280];
myType *pointer3;

Note: Since C++11, you can also use keyword using instead of typedef

using myType = int[100][280];
myType *pointer3;

in your example:

myType *pointer;                // pointer creation
pointer = &tab1;                // assignation
(*pointer)[5][12] = 517;        // set (write)
int myint = (*pointer)[5][12];  // get (read)

Note: If the array tab1 is used within a function body => this array will be placed within the call stack memory. But the stack size is limited. Using arrays bigger than the free memory stack produces a stack overflow crash.

The full snippet is online-compilable at gcc.godbolt.org

int main()
{
    //defines an array of 280 pointers (1120 or 2240 bytes)
    int  *pointer1 [280];
    static_assert( sizeof(pointer1) == 2240, "" );

    //defines a pointer (4 or 8 bytes depending on 32/64 bits platform)
    int (*pointer2)[280];      //pointer to an array of 280 integers
    int (*pointer3)[100][280]; //pointer to an 2D array of 100*280 integers  
    static_assert( sizeof(pointer2) == 8, "" );
    static_assert( sizeof(pointer3) == 8, "" );

    // Use 'typedef' (or 'using' if you use a modern C++ compiler)
    typedef int myType[100][280];
    //using myType = int[100][280];

    int tab1[100][280];

    myType *pointer;                // pointer creation
    pointer = &tab1;                // assignation
    (*pointer)[5][12] = 517;        // set (write)
    int myint = (*pointer)[5][12];  // get (read)

    return myint;
}

Angular 1 - get current URL parameters

In your route configuration you typically define a route like,

.when('somewhere/:param1/:param2')

You can then either get the route in the resolve object by using $route.current.params or in a controller, $routeParams. In either case the parameters is extracted using the mapping of the route, so param1 can be accessed by $routeParams.param1 in the controller.

Edit: Also note that the mapping has to be exact

/some/folder/:param1

Will only match a single parameter.

/some/folder/:param1/:param2 

Will only match two parameters.

This is a bit different then most dynamic server side routes. For example NodeJS (Express) route mapping where you can supply only a single route with X number of parameters.

How to auto adjust the div size for all mobile / tablet display formats?

You question is a bit unclear as to what you want, but judging from your comments, I assume you want each bubble to cover the screen, both vertically and horizontally. In that case, the vertical part is the tricky part.

As many others have answered, you first need to make sure that you are setting the viewport meta tag to trigger mobile devices to use their "ideal" viewport instead of the emulated "desktop width" viewport. The easiest and most fool proof version of this tag is as follows:

<meta name="viewport" content="width=device-width, initial-scale=1">

Source: PPK, probably the leading expert on how this stuff works. (See http://quirksmode.org/presentations/Spring2014/viewports_jqueryeu.pdf).

Essentially, the above makes sure that media queries and CSS measurements correspond to the ideal display of a virtual "point" on any given device — instead of shrinking pages to work with non-optimized desktop layouts. You don't need to understand the details of it, but it's important.

Now that we have a correct (non-faked) mobile viewport to work with, adjusting to the height of the viewport is still a tricky subject. Generally, web pages are fine to expand vertically, but not horizontally. So when you set height: 100% on something, that measurement has to relate to something else. At the topmost level, this is the size of the HTML element. But when the HTML element is taller than the screen (and expands to contain the contents), your measurements in percentages will be screwed up.

Enter the vh unit: it works like percentages, but works in relation to the viewport, not the containing block. MDN info page here: https://developer.mozilla.org/en-US/docs/Web/CSS/length#Viewport-percentage_lengths

Using that unit works just like you'd expect:

.bubble { height: 100vh; } /* be as tall as the viewport height. Done. */

It works on a lot of browsers (IE9 and up, modern Firefox, Safari, Chrome, Opera etc) but not all (support info here: http://caniuse.com/#search=vh). The downside in the browsers where it does work is that there is a massive bug in iOS6-7 that makes this technique unusable for this very case (details here: https://github.com/scottjehl/Device-Bugs/issues/36). It will be fixed in iOS8 though.

Depending on the HTML structure of your project, you may get away with using height: 100% on each element that is supposed to be as tall as the screen, as long as the following conditions are met:

  1. The element is a direct child element of <body>.
  2. Both the html and body elements have a 100% height set.

I have used that technique in the past, but it was long ago and I'm not sure it works on most mobile devices. Try it and see.

The next choice is to use a JavaScript helper to resize your elements to fit the viewport. Either a polyfill fixing the vh issues or something else altogether. Sadly, not every layout is doable in CSS.

How to save a bitmap on internal storage

To Save your bitmap in sdcard use the following code

Store Image

private void storeImage(Bitmap image) {
    File pictureFile = getOutputMediaFile();
    if (pictureFile == null) {
        Log.d(TAG,
                "Error creating media file, check storage permissions: ");// e.getMessage());
        return;
    } 
    try {
        FileOutputStream fos = new FileOutputStream(pictureFile);
        image.compress(Bitmap.CompressFormat.PNG, 90, fos);
        fos.close();
    } catch (FileNotFoundException e) {
        Log.d(TAG, "File not found: " + e.getMessage());
    } catch (IOException e) {
        Log.d(TAG, "Error accessing file: " + e.getMessage());
    }  
}

To Get the Path for Image Storage

/** Create a File for saving an image or video */
private  File getOutputMediaFile(){
    // To be safe, you should check that the SDCard is mounted
    // using Environment.getExternalStorageState() before doing this. 
    File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
            + "/Android/data/"
            + getApplicationContext().getPackageName()
            + "/Files"); 

    // This location works best if you want the created images to be shared
    // between applications and persist after your app has been uninstalled.

    // Create the storage directory if it does not exist
    if (! mediaStorageDir.exists()){
        if (! mediaStorageDir.mkdirs()){
            return null;
        }
    } 
    // Create a media file name
    String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
    File mediaFile;
        String mImageName="MI_"+ timeStamp +".jpg";
        mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
    return mediaFile;
} 

EDIT From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.

public onClick(View v){

switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
} 
}

Eclipse plugin for generating a class diagram

Try Amateras. It is a very good plugin for generating UML diagrams including class diagram.

Enable UTF-8 encoding for JavaScript

I think you just need to make

<meta http-equiv="Content-Type" content="text/html;charset=UTF-8">

Before calling your .js files or code

What is the argument for printf that formats a long?

I think you mean:

unsigned long n;
printf("%lu", n);   // unsigned long

or

long n;
printf("%ld", n);   // signed long

How do I use DrawerLayout to display over the ActionBar/Toolbar and under the status bar?

EDIT: The new Design Support Library supports this and the previous method is no longer required.

This can now be achieved using the new Android Design Support Library.

You can see the Cheesesquare sample app by Chris Banes which demos all the new features.


Previous method:

Since there is no complete solution posted, here is the way I achieved the desired result.

First include a ScrimInsetsFrameLayout in your project.

/*
* Copyright 2014 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
*     http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

/**
* A layout that draws something in the insets passed to 
* {@link #fitSystemWindows(Rect)}, i.e. the area above UI chrome
* (status and navigation bars, overlay action bars).
*/
public class ScrimInsetsFrameLayout extends FrameLayout {
    private Drawable mInsetForeground;

    private Rect mInsets;
    private Rect mTempRect = new Rect();
    private OnInsetsCallback mOnInsetsCallback;

    public ScrimInsetsFrameLayout(Context context) {
        super(context);
        init(context, null, 0);
    }

    public ScrimInsetsFrameLayout(Context context, AttributeSet attrs) {
        super(context, attrs);
        init(context, attrs, 0);
    }

    public ScrimInsetsFrameLayout(
        Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init(context, attrs, defStyle);
    }

    private void init(Context context, AttributeSet attrs, int defStyle) {
        final TypedArray a = context.obtainStyledAttributes(attrs,
                R.styleable.ScrimInsetsView, defStyle, 0);
        if (a == null) {
            return;
        }
        mInsetForeground = a.getDrawable(
            R.styleable.ScrimInsetsView_insetForeground);
        a.recycle();

        setWillNotDraw(true);
    }

    @Override
    protected boolean fitSystemWindows(Rect insets) {
        mInsets = new Rect(insets);
        setWillNotDraw(mInsetForeground == null);
        ViewCompat.postInvalidateOnAnimation(this);
        if (mOnInsetsCallback != null) {
            mOnInsetsCallback.onInsetsChanged(insets);
        }
        return true; // consume insets
    }

    @Override
    public void draw(Canvas canvas) {
        super.draw(canvas);

        int width = getWidth();
        int height = getHeight();
        if (mInsets != null && mInsetForeground != null) {
            int sc = canvas.save();
            canvas.translate(getScrollX(), getScrollY());

            // Top
            mTempRect.set(0, 0, width, mInsets.top);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Bottom
            mTempRect.set(0, height - mInsets.bottom, width, height);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Left
            mTempRect.set(
                0, 
                mInsets.top, 
                mInsets.left, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            // Right
            mTempRect.set(
                width - mInsets.right, 
                mInsets.top, width, 
                height - mInsets.bottom);
            mInsetForeground.setBounds(mTempRect);
            mInsetForeground.draw(canvas);

            canvas.restoreToCount(sc);
        }
    }

    @Override
    protected void onAttachedToWindow() {
        super.onAttachedToWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(this);
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        super.onDetachedFromWindow();
        if (mInsetForeground != null) {
            mInsetForeground.setCallback(null);
        }
    }

    /**
     * Allows the calling container to specify a callback for custom 
     * processing when insets change (i.e. when {@link #fitSystemWindows(Rect)}
     * is called. This is useful for setting padding on UI elements 
     * based on UI chrome insets (e.g. a Google Map or a ListView). 
     * When using with ListView or GridView, remember to set
     * clipToPadding to false.
     */
    public void setOnInsetsCallback(OnInsetsCallback onInsetsCallback) {
        mOnInsetsCallback = onInsetsCallback;
    }

    public static interface OnInsetsCallback {
        public void onInsetsChanged(Rect insets);
    }
}

Then create a styleable so that the insetForeground can be set.

values/attrs.xml

<declare-styleable name="ScrimInsetsView">
    <attr name="insetForeground" format="reference|color" />
</declare-styleable>

Update your activity's xml file and make sure android:fitsSystemWindows is set to true on both the DrawerLayout as well as the ScrimInsetsFrameLayout.

layout/activity_main.xml

<android.support.v4.widget.DrawerLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/drawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true"
    tools:context=".MainActivity">

    <!-- The main content view -->
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <!-- Your main content -->

    </LinearLayout>

    <!-- The navigation drawer -->
    <com.example.app.util.ScrimInsetsFrameLayout 
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/scrimInsetsFrameLayout"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="@color/white"
        android:elevation="10dp"
        android:fitsSystemWindows="true"
        app:insetForeground="#4000">

        <!-- Your drawer content -->

    </com.example.app.util.ScrimInsetsFrameLayout>

</android.support.v4.widget.DrawerLayout>

Inside the onCreate method of your activity set the status bar background color on the drawer layout.

MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // ...

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
    mDrawerLayout.setStatusBarBackgroundColor(
        getResources().getColor(R.color.primary_dark));
}

Finally update your app's theme so that the DrawerLayout is behind the status bar.

values-v21/styles.xml

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:windowDrawsSystemBarBackgrounds">true</item>
    <item name="android:statusBarColor">@android:color/transparent</item>
</style>

Result:

How to round up with excel VBA round()?

VBA uses bankers rounding in an attempt to compensate for the bias in always rounding up or down on .5; you can instead;

WorksheetFunction.Round(cells(1,1).value * cells(1,2).value, 2)

ping response "Request timed out." vs "Destination Host unreachable"

As khaos said, a destination unreachable could also mean that something is blocking the way from or to your destination. For example an ACL that filters bad IP addresses.

Parse date without timezone javascript

I have the same issue. I get a date as a String, for example: '2016-08-25T00:00:00', but I need to have Date object with correct time. To convert String into object, I use getTimezoneOffset:

var date = new Date('2016-08-25T00:00:00')
var userTimezoneOffset = date.getTimezoneOffset() * 60000;
new Date(date.getTime() - userTimezoneOffset);

getTimezoneOffset() will return ether negative or positive value. This must be subtracted to work in every location in world.

PHP: How to remove specific element from an array?

if (in_array('strawberry', $array)) 
{
    unset($array[array_search('strawberry',$array)]);
}

What is the difference between primary, unique and foreign key constraints, and indexes?

Primary key mainly prevent duplication and shows the uniqueness of columns Foreign key mainly shows relationship on two tables

What is the quickest way to HTTP GET in Python?

If you are working with HTTP APIs specifically, there are also more convenient choices such as Nap.

For example, here's how to get gists from Github since May 1st 2014:

from nap.url import Url
api = Url('https://api.github.com')

gists = api.join('gists')
response = gists.get(params={'since': '2014-05-01T00:00:00Z'})
print(response.json())

More examples: https://github.com/kimmobrunfeldt/nap#examples

How to see an HTML page on Github as a normal rendered HTML page to see preview in browser, without downloading?

You can use RawGit:
https://rawgit.com/necolas/css3-social-signin-buttons/master/index.html

It works better (at the time of this writing) than http://htmlpreview.github.com/, serving files with proper Content-Type headers. Additionally, it also provides CDN URL for use in production.

Working with select using AngularJS's ng-options

One thing to note is that ngModel is required for ngOptions to work... note the ng-model="blah" which is saying "set $scope.blah to the selected value".

Try this:

<select ng-model="blah" ng-options="item.ID as item.Title for item in items"></select>

Here's more from AngularJS's documentation (if you haven't seen it):

for array data sources:

  • label for value in array
  • select as label for value in array
  • label group by group for value in array = select as label group by group for value in array

for object data sources:

  • label for (key , value) in object
  • select as label for (key , value) in object
  • label group by group for (key, value) in object
  • select as label group by group for (key, value) in object

For some clarification on option tag values in AngularJS:

When you use ng-options, the values of option tags written out by ng-options will always be the index of the array item the option tag relates to. This is because AngularJS actually allows you to select entire objects with select controls, and not just primitive types. For example:

app.controller('MainCtrl', function($scope) {
   $scope.items = [
     { id: 1, name: 'foo' },
     { id: 2, name: 'bar' },
     { id: 3, name: 'blah' }
   ];
});
<div ng-controller="MainCtrl">
   <select ng-model="selectedItem" ng-options="item as item.name for item in items"></select>
   <pre>{{selectedItem | json}}</pre>
</div>

The above will allow you to select an entire object into $scope.selectedItem directly. The point is, with AngularJS, you don't need to worry about what's in your option tag. Let AngularJS handle that; you should only care about what's in your model in your scope.

Here is a plunker demonstrating the behavior above, and showing the HTML written out


Dealing with the default option:

There are a few things I've failed to mention above relating to the default option.

Selecting the first option and removing the empty option:

You can do this by adding a simple ng-init that sets the model (from ng-model) to the first element in the items your repeating in ng-options:

<select ng-init="foo = foo || items[0]" ng-model="foo" ng-options="item as item.name for item in items"></select>

Note: This could get a little crazy if foo happens to be initialized properly to something "falsy". In that case, you'll want to handle the initialization of foo in your controller, most likely.

Customizing the default option:

This is a little different; here all you need to do is add an option tag as a child of your select, with an empty value attribute, then customize its inner text:

<select ng-model="foo" ng-options="item as item.name for item in items">
   <option value="">Nothing selected</option>
</select>

Note: In this case the "empty" option will stay there even after you select a different option. This isn't the case for the default behavior of selects under AngularJS.

A customized default option that hides after a selection is made:

If you wanted your customized default option to go away after you select a value, you can add an ng-hide attribute to your default option:

<select ng-model="foo" ng-options="item as item.name for item in items">
   <option value="" ng-if="foo">Select something to remove me.</option>
</select>

Deleting DataFrame row in Pandas based on column value

If you want to delete rows based on multiple values of the column, you could use:

df[(df.line_race != 0) & (df.line_race != 10)]

To drop all rows with values 0 and 10 for line_race.

CSS blur on background image but not on content

backdrop-filter

Unfortunately Mozilla has really dropped the ball and taken it's time with the feature. I'm personally hoping it makes it in to the next Firefox ESR as that is what the next major version of Waterfox will use.

MDN (Mozilla Developer Network) article: https://developer.mozilla.org/en-US/docs/Web/CSS/backdrop-filter

Mozilla implementation: https://bugzilla.mozilla.org/show_bug.cgi?id=1178765

From the MDN documentation page:

/* URL to SVG filter */
backdrop-filter: url(commonfilters.svg#filter);

/* <filter-function> values */
backdrop-filter: blur(2px);
backdrop-filter: brightness(60%);
backdrop-filter: contrast(40%);
backdrop-filter: drop-shadow(4px 4px 10px blue);
backdrop-filter: grayscale(30%);
backdrop-filter: hue-rotate(120deg);
backdrop-filter: invert(70%);
backdrop-filter: opacity(20%);
backdrop-filter: sepia(90%);
backdrop-filter: saturate(80%);

/* Multiple filters */
backdrop-filter: url(filters.svg#filter) blur(4px) saturate(150%);

SQL Client for Mac OS X that works with MS SQL Server

This will be the second question in a row I've answered with this, so I think it's worth pointing out that I have no affiliation with this product, but I use it and love it and think it's the right answer to this question too: DbVisualizer.

Remove quotes from String in Python

To add to @Christian's comment:

Replace all single or double quotes in a string:

s = "'asdfa sdfa'"

import re
re.sub("[\"\']", "", s)

Remove all elements contained in another array

The filter method should do the trick:

const myArray = ['a', 'b', 'c', 'd', 'e', 'f', 'g'];
const toRemove = ['b', 'c', 'g'];

// ES5 syntax
const filteredArray = myArray.filter(function(x) { 
  return toRemove.indexOf(x) < 0;
});

If your toRemove array is large, this sort of lookup pattern can be inefficient. It would be more performant to create a map so that lookups are O(1) rather than O(n).

const toRemoveMap = toRemove.reduce(
  function(memo, item) {
    memo[item] = memo[item] || true;
    return memo;
  },
  {} // initialize an empty object
);

const filteredArray = myArray.filter(function (x) {
  return toRemoveMap[x];
});

// or, if you want to use ES6-style arrow syntax:
const toRemoveMap = toRemove.reduce((memo, item) => ({
  ...memo,
  [item]: true
}), {});

const filteredArray = myArray.filter(x => toRemoveMap[x]);

What's the "average" requests per second for a production web application?

OpenStreetMap seems to have 10-20 per second

Wikipedia seems to be 30000 to 70000 per second spread over 300 servers (100 to 200 requests per second per machine, most of which is caches)

Geograph is getting 7000 images per week (1 upload per 95 seconds)

How to get Git to clone into current directory

simply put a dot next to it

git clone [email protected]:user/my-project.git .

From git help clone:

Cloning into an existing directory is only allowed if the directory is empty.

So make sure the directory is empty (check with ls -a), otherwise the command will fail.

CSS: how to add white space before element's content?

/* Most Accurate Setting if you only want
   to do this with CSS Pseudo Element */
p:before { 
   content: "\00a0";
   padding-right: 5px; /* If you need more space b/w contents */
}

Inline instantiation of a constant List

You'll need to use a static readonly list instead. And if you want the list to be immutable then you might want to consider using ReadOnlyCollection<T> rather than List<T>.

private static readonly ReadOnlyCollection<string> _metrics =
    new ReadOnlyCollection<string>(new[]
        {
            SourceFile.LOC,
            SourceFile.MCCABE,
            SourceFile.NOM,
            SourceFile.NOA,
            SourceFile.FANOUT,
            SourceFile.FANIN,
            SourceFile.NOPAR,
            SourceFile.NDC,
            SourceFile.CALLS
        });

public static ReadOnlyCollection<string> Metrics
{
    get { return _metrics; }
}

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Why can't I center with margin: 0 auto?

You need to define the width of the element you are centering, not the parent element.

#header ul {
    margin: 0 auto;
    width: 90%;
}

Edit: Ok, I've seen the testpage now, and here is how I think you want it:

#header ul {
    list-style:none;
    margin:0 auto;
    width:90%;
}

/* Remove the float: left; property, it interferes with display: inline and 
 * causes problems. (float: left; makes the element implicitly a block-level
 * element. It is still good to use display: inline on it to overcome a bug
 * in IE6 and below that doubles horizontal margins for floated elements)
 * The styles below is the full style for the list-items. 
 */
#header ul li {
    color:#CCCCCC;
    display:inline;
    font-size:20px;
    padding-right:20px;
}

How can I check for IsPostBack in JavaScript?

Lots of options here.

For a pure JS solution, have your page submit to itself, but with additional URL parameter (mypage.html?postback=true) - you can then get the page url with window.location.href, and parse that using a split or regex to look for your variable.

The much easier one, assuming you sending back to some sort of scripting language to proces the page (php/perl/asp/cf et. al), is to have them echo a line of javascript in the page setting a variable:

<html>

<?php
if ($_POST['myVar']) {
    //postback
    echo '<script>var postingBack = true;</script>';
    //Do other processing
} else {
    echo '<script>var postingBack = false;</script>'
 } ?>
<script>
function myLoader() {
     if (postingBack == false) {
          //Do stuff
     }
 }

<body onLoad="myLoader():"> ...

How do I specify a password to 'psql' non-interactively?

If its not too late to add most of the options in one answer:

There are a couple of options:

  1. set it in the pgpass file. link
  1. set an environment variable and get it from there:

    export PGPASSWORD='password'

and then run your psql to login or even run the command from there:

 psql -h clustername -U username -d testdb
  1. On windows you will have to use "set" :

    set PGPASSWORD=pass and then login to the psql bash.

Whoops, looks like something went wrong. Laravel 5.0

Simply type in terminal in your command prompt go to laravel directory path and type php artisan key:generate then key will be generated. Paste that key in config/app.php key variable. Your problem will be solved. I also did like that inorder to solve the problem...

How to set Default Controller in asp.net MVC 4 & MVC 5

Set below code in RouteConfig.cs in App_Start folder

public static void RegisterRoutes(RouteCollection routes)
{
 routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
 routes.MapRoute(
 name: "Default",
 url: "{controller}/{action}/{id}",
 defaults: new { controller = "Account", action = "Login", id = UrlParameter.Optional });
}

IF still not working then do below steps

Second Way : You simple follow below steps,

1) Right click on your Project

2) Select Properties

3) Select Web option and then Select Specific Page (Controller/View) and then set your login page

Here, Account is my controller and Login is my action method (saved in Account Controller)

Please take a look attachedenter image description here screenshot.

What is the difference between .py and .pyc files?

.pyc contain the compiled bytecode of Python source files. The Python interpreter loads .pyc files before .py files, so if they're present, it can save some time by not having to re-compile the Python source code. You can get rid of them if you want, but they don't cause problems, they're not big, and they may save some time when running programs.

fatal: early EOF fatal: index-pack failed

In my case the problem was none of the git configuration parameters but the fact that my repository had one file exceeding the maximum file size allowed on my system. I was able to check it trying to download a large file and getting an "File Size Limit Exceeded" on Debian.

After that I edited my /etc/security/limits.conf file adding et the end of it the following lines:

  • hard fsize 1000000
  • soft fsize 1000000

To actually "apply" the new limit values you need to re-login

Get current time in seconds since the Epoch on Linux, Bash

This is an extension to what @pellucide has done, but for Macs:

To determine the number of seconds since epoch (Jan 1 1970) for any given date (e.g. Oct 21 1973)

$ date -j -f "%b %d %Y %T" "Oct 21 1973 00:00:00" "+%s"
120034800

Please note, that for completeness, I have added the time part to the format. The reason being is that date will take whatever date part you gave it and add the current time to the value provided. For example, if you execute the above command at 4:19PM, without the '00:00:00' part, it will add the time automatically. Such that "Oct 21 1973" will be parsed as "Oct 21 1973 16:19:00". That may not be what you want.

To convert your timestamp back to a date:

$ date -j -r 120034800
Sun Oct 21 00:00:00 PDT 1973

Apple's man page for the date implementation: https://developer.apple.com/library/mac/documentation/Darwin/Reference/ManPages/man1/date.1.html

Get second child using jQuery

I didn't see it mentioned here, but you can also use CSS spec selectors. See the docs

$('#parentContainer td:nth-child(2)')

Zsh: Conda/Pip installs command not found

FYI for anyone having this same issue keep in mind that you need to make sure that you have the right version of anaconda in that export path:

anaconda2 or anaconda3 

Spent way too long on that minor issue.

Code signing is required for product type 'Application' in SDK 'iOS 10.0' - StickerPackExtension requires a development team error

In unit test target

Xcode 7:

  • Must have provisioning profiles set (the same as in app target)
  • Must have "don't sign" under certificates

Xcode 8:

  • Must have 'None' set for provisioning profiles
  • Must have certificates set (the same as in app target)
  • (Must also have 'None' set for deprecated provisioning profiles)

CSS hexadecimal RGBA?

Chrome 52+ supports alpha hex:

background: #56ff0077;

What does the construct x = x || y mean?

What is the double pipe operator (||)?

The double pipe operator (||) is the logical OR operator . In most languages it works the following way:

  • If the first value is false, it checks the second value. If that's true, it returns true and if the second value is false, it returns false.
  • If the first value is true, it always returns true, no matter what the second value is.

So basically it works like this function:

function or(x, y) {
  if (x) {
    return true;
  } else if (y) {
    return true;
  } else {
    return false;
  }
}

If you still don't understand, look at this table:

      | true   false  
------+---------------
true  | true   true   
false | true   false  

In other words, it's only false when both values are false.

How is it different in JavaScript?

JavaScript is a bit different, because it's a loosely typed language. In this case it means that you can use || operator with values that are not booleans. Though it makes no sense, you can use this operator with for example a function and an object:

(function(){}) || {}

What happens there?

If values are not boolean, JavaScript makes implicit conversion to boolean. It means that if the value is falsey (e.g. 0, "", null, undefined (see also All falsey values in JavaScript)), it will be treated as false; otherwise it's treated as true.

So the above example should give true, because empty function is truthy. Well, it doesn't. It returns the empty function. That's because JavaScript's || operator doesn't work as I wrote at the beginning. It works the following way:

  • If the first value is falsey, it returns the second value.
  • If the first value is truthy, it returns the first value.

Surprised? Actually, it's "compatible" with the traditional || operator. It could be written as following function:

function or(x, y) {
  if (x) {
    return x;
  } else {
    return y;
  }
}

If you pass a truthy value as x, it returns x, that is, a truthy value. So if you use it later in if clause:

(function(x, y) {
  var eitherXorY = x || y;
  if (eitherXorY) {
    console.log("Either x or y is truthy.");
  } else {
    console.log("Neither x nor y is truthy");
  }
}(true/*, undefined*/));

you get "Either x or y is truthy.".

If x was falsey, eitherXorY would be y. In this case you would get the "Either x or y is truthy." if y was truthy; otherwise you'd get "Neither x nor y is truthy".

The actual question

Now, when you know how || operator works, you can probably make out by yourself what does x = x || y mean. If x is truthy, x is assigned to x, so actually nothing happens; otherwise y is assigned to x. It is commonly used to define default parameters in functions. However, it is often considered a bad programming practice, because it prevents you from passing a falsey value (which is not necessarily undefined or null) as a parameter. Consider following example:

function badFunction(/* boolean */flagA) {
  flagA = flagA || true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

It looks valid at the first sight. However, what would happen if you passed false as flagA parameter (since it's boolean, i.e. can be true or false)? It would become true. In this example, there is no way to set flagA to false.

It would be a better idea to explicitly check whether flagA is undefined, like that:

function goodFunction(/* boolean */flagA) {
  flagA = typeof flagA !== "undefined" ? flagA : true;
  console.log("flagA is set to " + (flagA ? "true" : "false"));
}

Though it's longer, it always works and it's easier to understand.


You can also use the ES6 syntax for default function parameters, but note that it doesn't work in older browsers (like IE). If you want to support these browsers, you should transpile your code with Babel.

See also Logical Operators on MDN.

Event system in Python

You may have a look at pymitter (pypi). Its a small single-file (~250 loc) approach "providing namespaces, wildcards and TTL".

Here's a basic example:

from pymitter import EventEmitter

ee = EventEmitter()

# decorator usage
@ee.on("myevent")
def handler1(arg):
   print "handler1 called with", arg

# callback usage
def handler2(arg):
    print "handler2 called with", arg
ee.on("myotherevent", handler2)

# emit
ee.emit("myevent", "foo")
# -> "handler1 called with foo"

ee.emit("myotherevent", "bar")
# -> "handler2 called with bar"

Return index of highest value in an array

$newarr=arsort($arr);
$max_key=array_shift(array_keys($new_arr));

How to implement class constants?

Angular 2 Provides a very nice feature called as Opaque Constants. Create a class & Define all the constants there using opaque constants.

import { OpaqueToken } from "@angular/core";

export let APP_CONFIG = new OpaqueToken("my.config");

export interface MyAppConfig {
    apiEndpoint: string;
}

export const AppConfig: MyAppConfig = {    
    apiEndpoint: "http://localhost:8080/api/"    
};

Inject it in providers in app.module.ts

You will be able to use it across every components.

EDIT for Angular 4 :

For Angular 4 the new concept is Injection Token & Opaque token is Deprecated in Angular 4.

Injection Token Adds functionalities on top of Opaque Tokens, it allows to attach type info on the token via TypeScript generics, plus Injection tokens, removes the need of adding @Inject

Example Code

Angular 2 Using Opaque Tokens

const API_URL = new OpaqueToken('apiUrl'); //no Type Check


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      new Inject(API_URL) //notice the new Inject
    ]
  }
]

Angular 4 Using Injection Tokens

const API_URL = new InjectionToken<string>('apiUrl'); // generic defines return value of injector


providers: [
  {
    provide: DataService,
    useFactory: (http, apiUrl) => {
      // create data service
    },
    deps: [
      Http,
      API_URL // no `new Inject()` needed!
    ]
  }
]

Injection tokens are designed logically on top of Opaque tokens & Opaque tokens are deprecated in Angular 4.

JSON.Net Self referencing loop detected

Sometimes you have loops becouse your type class have references to other classes and that classes have references to your type class, thus you have to select the parameters that you need exactly in the json string, like this code.

List<ROficina> oficinas = new List<ROficina>();
oficinas = /*list content*/;
var x = JsonConvert.SerializeObject(oficinas.Select(o => new
            {
                o.IdOficina,
                o.Nombre
            }));

Check free disk space for current partition in bash

To know the usage of the specific directory in GB's or TB's in linux the command is,

df -h /dir/inner_dir/

 or

df -sh /dir/inner_dir/

and to know the usage of the specific directory in bits in linux the command is,

df-k /dir/inner_dir/

How to embed new Youtube's live video permanent URL?

The embed URL for a channel's live stream is:

https://www.youtube.com/embed/live_stream?channel=CHANNEL_ID

You can find your CHANNEL_ID at https://www.youtube.com/account_advanced

Run a PostgreSQL .sql file using command line arguments

you could even do it in this way:

sudo -u postgres psql -d myDataBase -a -f myInsertFile

If you have sudo access on machine and it's not recommended for production scripts just for test on your own machine it's the easiest way.

First Heroku deploy failed `error code=H10`

In my case, my Procfile was pointing to the wrong file (bot.js which I previously used) so once I updated it, the error was gone.

How can I set the PATH variable for javac so I can manually compile my .java works?

Step 1: Set the PATH variable JAVA_HOME to the path of the JDK present on the system. Step 2: in the Path variable add the path of the C:\Program Files\Java\jdk(version)\bin

This should solve the problem. Happy coding!!

Editing the git commit message in GitHub

You need to git push -f assuming that nobody has pulled the other commit before. Beware, you're changing history.

Wait for page load in Selenium

Explicitly wait or conditional wait in this wait until given this condition.

WebDriverWait wait = new WebDriverWait(wb, 60);
wait.until(ExpectedConditions.elementToBeClickable(By.name("value")));

This will wait for every web element for 60 seconds.

Use implicitly wait for wait of every element on page till that given time.

driver.manage().timeouts().implicitlyWait(60, TimeUnit.SECONDS);

This will wait for every web element for 60 seconds.

How do I perform HTML decoding/encoding using Python/Django?

You can also use django.utils.html.escape

from django.utils.html import escape

something_nice = escape(request.POST['something_naughty'])

How to prevent sticky hover effects for buttons on touch devices

Some of the sticky or stuck :hover :focus :active problems on mobile devices may be caused by missing <meta name="viewport" content="width=device-width"> as the browsers try to manipulate the screen.

'gulp' is not recognized as an internal or external command

I just encountered this on Windows 10 and the latest NodeJS (14.15.1). In my case our admins have our profiles and true "home" folder remotely mount onto our work machine(s). Npm wanted to put its cache over on the remote server and that has worked until this release.

I was unaware that npm has a .npmrc file available. I added one to my actual machine's C:\Users\my-id folder and it contains:

prefix=C:\Users\my-id\nodejs\npm
cache=c:\Users\my-id\nodejs\npm-cache

I also added these paths to my PATH environment variable.

I went to the APPDATA folder on my work machine and the remote "home" server and deleted all the npm related Roaming folders. I deleted the node_modules folder in my project.

I closed all open windows and reopened them. I brought up a command prompt in my project dir and re inited npm and reinstalled the modules I wanted.

After that everything is rolling along.

How to read all files in a folder from Java?

Simple example that works with Java 1.7 to recursively list files in directories specified on the command-line:

import java.io.File;

public class List {
    public static void main(String[] args) {
        for (String f : args) {
            listDir(f);
        }
    }

    private static void listDir(String dir) {
        File f = new File(dir);
        File[] list = f.listFiles();

        if (list == null) {
            return;
        }

        for (File entry : list) {
            System.out.println(entry.getName());
            if (entry.isDirectory()) {
                listDir(entry.getAbsolutePath());
            }
        }
    }
}

How to convert CSV file to multiline JSON?

def read():
    noOfElem = 200  # no of data you want to import
    csv_file_name = "hashtag_donaldtrump.csv"  # csv file name
    json_file_name = "hashtag_donaldtrump.json"  # json file name

    with open(csv_file_name, mode='r') as csv_file:
        csv_reader = csv.DictReader(csv_file)
        with open(json_file_name, 'w') as json_file:
            i = 0
            json_file.write("[")
            
            for row in csv_reader:
                i = i + 1
                if i == noOfElem:
                    json_file.write("]")
                    return

                json_file.write(json.dumps(row))

                if i != noOfElem - 1:
                    json_file.write(",")

Change the above three parameter, everything will be done.

Embed youtube videos that play in fullscreen automatically

This was pretty well answered over here: How to make a YouTube embedded video a full page width one?

If you add '?rel=0&autoplay=1' to the end of the url in the embed code (like this)

<iframe id="video" src="//www.youtube.com/embed/5iiPC-VGFLU?rel=0&autoplay=1" frameborder="0" allowfullscreen></iframe>

of the video it should play on load. Here's a demo over at jsfiddle.

Check if all values of array are equal

This works. You create a method on Array by using prototype.

if (Array.prototype.allValuesSame === undefined) {
  Array.prototype.allValuesSame = function() {
    for (let i = 1; i < this.length; i++) {
      if (this[i] !== this[0]) {
        return false;
      }
    }
    return true;
  }
}

Call this in this way:

let a = ['a', 'a', 'a'];
let b = a.allValuesSame(); // true
a = ['a', 'b', 'a'];
b = a.allValuesSame();     // false

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It happens because of not very straight forward Servlet specification. If you are working with a native HttpServletRequest implementation you cannot get both the URL encode body and the parameters. Spring does some workarounds, which make it even more strange and nontransparent.

In such cases Spring (version 3.2.4) re-renders a body for you using data from the getParameterMap() method. It mixes GET and POST parameters and breaks the parameter order. The class, which is responsible for the chaos is ServletServerHttpRequest. Unfortunately it cannot be replaced, but the class StringHttpMessageConverter can be.

The clean solution is unfortunately not simple:

  1. Replacing StringHttpMessageConverter. Copy/Overwrite the original class adjusting method readInternal().
  2. Wrapping HttpServletRequest overwriting getInputStream(), getReader() and getParameter*() methods.

In the method StringHttpMessageConverter#readInternal following code must be used:

    if (inputMessage instanceof ServletServerHttpRequest) {
        ServletServerHttpRequest oo = (ServletServerHttpRequest)inputMessage;
        input = oo.getServletRequest().getInputStream();
    } else {
        input = inputMessage.getBody();
    }

Then the converter must be registered in the context.

<mvc:annotation-driven>
    <mvc:message-converters register-defaults="true/false">
        <bean class="my-new-converter-class"/>
   </mvc:message-converters>
</mvc:annotation-driven>

The step two is described here: Http Servlet request lose params from POST body after read it once

What is Ruby's double-colon `::`?

Ruby on rails uses :: for namespace resolution.

class User < ActiveRecord::Base

  VIDEOS_COUNT = 10
  Languages = { "English" => "en", "Spanish" => "es", "Mandarin Chinese" => "cn"}

end

To use it :

User::VIDEOS_COUNT
User::Languages
User::Languages.values_at("Spanish") => "en"

Also, other usage is : When using nested routes

OmniauthCallbacksController is defined under users.

And routed as:

devise_for :users, controllers: {omniauth_callbacks: "users/omniauth_callbacks"}


class Users::OmniauthCallbacksController < Devise::OmniauthCallbacksController

end

How can two strings be concatenated?

Given the matrix, tmp, that you created:

paste(tmp[1,], collapse = ",")

I assume there is some reason why you're creating a matrix using cbind, as opposed to simply:

tmp <- "GAD,AB"

Bower: ENOGIT Git is not installed or not in the PATH

In Linux:

if you dont have installed git use:

sudo apt-get update
sudo apt-get install git

with command which git you will know the directory where is and then add in path if it is not in that enviroment variable.

Difference between partition key, composite key and clustering key in Cassandra?

Primary Key: Is composed of partition key(s) [and optional clustering keys(or columns)]
Partition Key: The hash value of Partition key is used to determine the specific node in a cluster to store the data
Clustering Key: Is used to sort the data in each of the partitions(or responsible node and it's replicas)

Compound Primary Key: As said above, the clustering keys are optional in a Primary Key. If they aren't mentioned, it's a simple primary key. If clustering keys are mentioned, it's a Compound primary key.

Composite Partition Key: Using just one column as a partition key, might result in wide row issues (depends on use case/data modeling). Hence the partition key is sometimes specified as a combination of more than one column.

Regarding confusion of which one is mandatory, which one can be skipped etc. in a query, trying to imagine Cassandra as a giant HashMap helps. So in a HashMap, you can't retrieve the values without the Key.
Here, the Partition keys play the role of that key. So each query needs to have them specified. Without which Cassandra won't know which node to search for.
The clustering keys (columns, which are optional) help in further narrowing your query search after Cassandra finds out the specific node(and it's replicas) responsible for that specific Partition key.

How can I select from list of values in Oracle

If you are seeking to convert a comma delimited list of values:

select column_value 
from table(sys.dbms_debug_vc2coll('One', 'Two', 'Three', 'Four'));

-- Or

select column_value 
from table(sys.dbms_debug_vc2coll(1,2,3,4));

If you wish to convert a string of comma delimited values then I would recommend Justin Cave's regular expression SQL solution.

How to get the anchor from the URL using jQuery?

For current window, you can use this:

var hash = window.location.hash.substr(1);

To get the hash value of the main window, use this:

var hash = window.top.location.hash.substr(1);

If you have a string with an URL/hash, the easiest method is:

var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:

var hash = $(location).attr('hash');

Difference between map and collect in Ruby?

Ruby aliases the method Array#map to Array#collect; they can be used interchangeably. (Ruby Monk)

In other words, same source code :

               static VALUE
rb_ary_collect(VALUE ary)
{
long i;
VALUE collect;

RETURN_SIZED_ENUMERATOR(ary, 0, 0, ary_enum_length);
collect = rb_ary_new2(RARRAY_LEN(ary));
for (i = 0; i < RARRAY_LEN(ary); i++) {
    rb_ary_push(collect, rb_yield(RARRAY_AREF(ary, i)));
}
return collect;
}

http://ruby-doc.org/core-2.2.0/Array.html#method-i-map

Use async await with Array.map

I'd recommend using Promise.all as mentioned above, but if you really feel like avoiding that approach, you can do a for or any other loop:

const arr = [1,2,3,4,5];
let resultingArr = [];
for (let i in arr){
  await callAsynchronousOperation(i);
  resultingArr.push(i + 1)
}

how to open popup window using jsp or jquery?

The following JavaScript will open a new browser window, 450px wide by 300px high with scrollbars:

window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");

You can add this to a link like so:

<a href='#' onclick='javascript:window.open("http://myurl", "_blank", "scrollbars=1,resizable=1,height=300,width=450");' title='Pop Up'>Pop Up</a>

onclick on a image to navigate to another page using Javascript

I'd set up your HTML like so:

<img src="../images/bottle.jpg" alt="bottle" class="thumbnails" id="bottle" />

Then use the following code:

<script>
var images = document.getElementsByTagName("img");
for(var i = 0; i < images.length; i++) {
    var image = images[i];
    image.onclick = function(event) {
         window.location.href = this.id + '.html';
    };
}
</script>

That assigns an onclick event handler to every image on the page (this may not be what you want, you can limit it further if necessary) that changes the current page to the value of the images id attribute plus the .html extension. It's essentially the pure Javascript implementation of @JanPöschko's jQuery answer.

ASP.NET Core form POST results in a HTTP 415 Unsupported Media Type response

As addition of good answers, You don't have to use [FromForm] to get form data in controller. Framework automatically convert form data to model as you wish. You can implement like following.

[HttpPost]
public async Task<IActionResult> Submit(MyModel model)
{
    //...
}

Difference between single and double quotes in Bash

Single quotes won't interpolate anything, but double quotes will. For example: variables, backticks, certain \ escapes, etc.

Example:

$ echo "$(echo "upg")"
upg
$ echo '$(echo "upg")'
$(echo "upg")

The Bash manual has this to say:

3.1.2.2 Single Quotes

Enclosing characters in single quotes (') preserves the literal value of each character within the quotes. A single quote may not occur between single quotes, even when preceded by a backslash.

3.1.2.3 Double Quotes

Enclosing characters in double quotes (") preserves the literal value of all characters within the quotes, with the exception of $, `, \, and, when history expansion is enabled, !. The characters $ and ` retain their special meaning within double quotes (see Shell Expansions). The backslash retains its special meaning only when followed by one of the following characters: $, `, ", \, or newline. Within double quotes, backslashes that are followed by one of these characters are removed. Backslashes preceding characters without a special meaning are left unmodified. A double quote may be quoted within double quotes by preceding it with a backslash. If enabled, history expansion will be performed unless an ! appearing in double quotes is escaped using a backslash. The backslash preceding the ! is not removed.

The special parameters * and @ have special meaning when in double quotes (see Shell Parameter Expansion).

Getting the IP address of the current machine using Java

This is a working example of the ACCEPTED answer above! This NetIdentity class will store both the internal host ip, as well as the local loopback. If you're on a DNS based server, as mentioned above, you may need to add some more checks, or possible go the Configuration File Route.

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.net.UnknownHostException;
import java.util.Enumeration;

/**
 * Class that allows a device to identify itself on the INTRANET.
 * 
 * @author Decoded4620 2016
 */
public class NetIdentity {

    private String loopbackHost = "";
    private String host = "";

    private String loopbackIp = "";
    private String ip = "";
    public NetIdentity(){

        try{
            Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();

            while(interfaces.hasMoreElements()){
                NetworkInterface i = interfaces.nextElement();
                if(i != null){
                    Enumeration<InetAddress> addresses = i.getInetAddresses();
                    System.out.println(i.getDisplayName());
                    while(addresses.hasMoreElements()){
                        InetAddress address = addresses.nextElement();
                        String hostAddr = address.getHostAddress();

                        // local loopback
                        if(hostAddr.indexOf("127.") == 0 ){
                            this.loopbackIp = address.getHostAddress();
                            this.loopbackHost = address.getHostName();
                        }

                        // internal ip addresses (behind this router)
                        if( hostAddr.indexOf("192.168") == 0 || 
                                hostAddr.indexOf("10.") == 0 || 
                                hostAddr.indexOf("172.16") == 0 ){
                            this.host = address.getHostName();
                            this.ip = address.getHostAddress();
                        }


                        System.out.println("\t\t-" + address.getHostName() + ":" + address.getHostAddress() + " - "+ address.getAddress());
                    }
                }
            }
        }
        catch(SocketException e){

        }
        try{
            InetAddress loopbackIpAddress = InetAddress.getLocalHost();
            this.loopbackIp = loopbackIpAddress.getHostName();
            System.out.println("LOCALHOST: " + loopbackIp);
        }
        catch(UnknownHostException e){
            System.err.println("ERR: " + e.toString());
        }
    }

    public String getLoopbackHost(){
        return loopbackHost;
    }

    public String getHost(){
        return host;
    }
    public String getIp(){
        return ip;
    }
    public String getLoopbackIp(){
        return loopbackIp;
    }
}

When I run this code I actually get a print out like this:

    Software Loopback Interface 1
        -127.0.0.1:127.0.0.1 - [B@19e1023e
        -0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
        -VIKING.yourisp.com:192.168.1.142 - [B@64b8f8f4
        -fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
Intel Edison USB RNDIS Device
Driver for user-mode network applications
Cisco Systems VPN Adapter for 64-bit Windows
VirtualBox Host-Only Ethernet Adapter
        -VIKING:192.168.56.1 - [B@3cd1f1c8
        -VIKING:fe80:0:0:0:d599:3cf0:5462:cb7%eth4 - [B@3a4afd8d
LogMeIn Hamachi Virtual Ethernet Adapter
        -VIKING:25.113.118.39 - [B@1996cd68
        -VIKING:2620:9b:0:0:0:0:1971:7627 - [B@3339ad8e
        -VIKING:fe80:0:0:0:51bf:994d:4656:8486%eth5 - [B@555590
Bluetooth Device (Personal Area Network)
        -fe80:0:0:0:4c56:8009:2bca:e16b%eth6:fe80:0:0:0:4c56:8009:2bca:e16b%eth6 - [B@3c679bde
Bluetooth Device (RFCOMM Protocol TDI)
Intel(R) Ethernet Connection (2) I218-V
        -fe80:0:0:0:4093:d169:536c:7c7c%eth7:fe80:0:0:0:4093:d169:536c:7c7c%eth7 - [B@16b4a017
Microsoft Wi-Fi Direct Virtual Adapter
        -fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1:fe80:0:0:0:103e:cdf0:c0ac:1751%wlan1 - [B@8807e25
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0000
VirtualBox Host-Only Ethernet Adapter-WFP Native MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0001
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0002
VirtualBox Host-Only Ethernet Adapter-VirtualBox NDIS Light-Weight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0003
VirtualBox Host-Only Ethernet Adapter-QoS Packet Scheduler-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0004
VirtualBox Host-Only Ethernet Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
VirtualBox Host-Only Ethernet Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0000
Intel(R) Ethernet Connection (2) I218-V-WFP Native MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0001
Intel(R) Ethernet Connection (2) I218-V-Shrew Soft Lightweight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0002
Intel(R) Ethernet Connection (2) I218-V-VirtualBox NDIS Light-Weight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0003
Intel(R) Ethernet Connection (2) I218-V-QoS Packet Scheduler-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0004
Intel(R) Ethernet Connection (2) I218-V-WFP 802.3 MAC Layer LightWeight Filter-0000
Intel(R) Ethernet Connection (2) I218-V-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-WFP Native MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-Virtual WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-Native WiFi Filter Driver-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Broadcom 802.11ac Network Adapter-Shrew Soft Lightweight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Broadcom 802.11ac Network Adapter-VirtualBox NDIS Light-Weight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Broadcom 802.11ac Network Adapter-QoS Packet Scheduler-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0006
Broadcom 802.11ac Network Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Broadcom 802.11ac Network Adapter-HHD Software NDIS 6.0 Filter Driver-0007
Microsoft Wi-Fi Direct Virtual Adapter-WFP Native MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-Native WiFi Filter Driver-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0002
Microsoft Wi-Fi Direct Virtual Adapter-Shrew Soft Lightweight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0003
Microsoft Wi-Fi Direct Virtual Adapter-VirtualBox NDIS Light-Weight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0004
Microsoft Wi-Fi Direct Virtual Adapter-QoS Packet Scheduler-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0005
Microsoft Wi-Fi Direct Virtual Adapter-WFP 802.3 MAC Layer LightWeight Filter-0000
Microsoft Wi-Fi Direct Virtual Adapter-HHD Software NDIS 6.0 Filter Driver-0006

For my use I'm setting up a Upnp Server, it helped to understand the 'pattern' that i was looking for. Some of the objects returned are Ethernet Adapters, Network Adapters, Virtual Network Adapters, Drivers, and VPN Client Adapters. Not everything has an Address either. So you'll want to skip out on interface objects that don't.

You can also add this to the loop for the current NetworkInterface i

while(interfaces.hasMoreElements()){
    Enumeration<InetAddress> addresses = i.getInetAddresses();
    System.out.println(i.getDisplayName());
    System.out.println("\t- name:" + i.getName());
    System.out.println("\t- idx:" + i.getIndex());
    System.out.println("\t- max trans unit (MTU):" + i.getMTU());
    System.out.println("\t- is loopback:" + i.isLoopback());
    System.out.println("\t- is PPP:" + i.isPointToPoint());
    System.out.println("\t- isUp:" + i.isUp());
    System.out.println("\t- isVirtual:" + i.isVirtual());
    System.out.println("\t- supportsMulticast:" + i.supportsMulticast());
}

And You'll see information in your output much like this:

Software Loopback Interface 1
    - name:lo
    - idx:1
    - max trans unit (MTU):-1
    - is loopback:true
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [127.0.0.1(VIKING-192.168.56.1)]127.0.0.1:127.0.0.1 - [B@19e1023e
        -ADRESS: [0:0:0:0:0:0:0:1(VIKING-192.168.56.1)]0:0:0:0:0:0:0:1:0:0:0:0:0:0:0:1 - [B@7cef4e59
Broadcom 802.11ac Network Adapter
    - name:wlan0
    - idx:2
    - max trans unit (MTU):1500
    - is loopback:false
    - is PPP:false
    - isUp:true
    - isVirtual:false
    - supportsMulticast:true
        -ADRESS: [VIKING.monkeybrains.net(VIKING-192.168.56.1)]VIKING.monkeybrains.net:192.168.1.142 - [B@64b8f8f4
        -ADRESS: [fe80:0:0:0:81fa:31d:21c9:85cd%wlan0(VIKING-192.168.56.1)]fe80:0:0:0:81fa:31d:21c9:85cd%wlan0:fe80:0:0:0:81fa:31d:21c9:85cd%wlan0 - [B@2db0f6b2
Microsoft Kernel Debug Network Adapter
    - name:eth0
    - idx:3
    - max trans unit (MTU):-1
    - is loopback:false
    - is PPP:false
    - isUp:false
    - isVirtual:false
    - supportsMulticast:true

Fatal error: Class 'ZipArchive' not found in

First of all, The solution for remote server:

If you are using cpanel you may have zip extension installed but not activate. You need to active it. For this case you need to go to cpanel > inside software section > click on PHP version. Then find zip and check it. Now save.

You should see like the image. enter image description here

Refresh page. The error should disappear.

Note: If you dont found, contact server provider. They will install for you.

What is the maximum number of edges in a directed graph with n nodes?

In addition to the intuitive explanation Chris Smith has provided, we can consider why this is the case from a different perspective: considering undirected graphs.

To see why in a DIRECTED graph the answer is n*(n-1), consider an undirected graph (which simply means that if there is a link between two nodes (A and B) then you can go in both ways: from A to B and from B to A). The maximum number of edges in an undirected graph is n(n-1)/2 and obviously in a directed graph there are twice as many.

Good, you might ask, but why are there a maximum of n(n-1)/2 edges in an undirected graph? For that, Consider n points (nodes) and ask how many edges can one make from the first point. Obviously, n-1 edges. Now how many edges can one draw from the second point, given that you connected the first point? Since the first and the second point are already connected, there are n-2 edges that can be done. And so on. So the sum of all edges is:

Sum = (n-1)+(n-2)+(n-3)+...+3+2+1 

Since there are (n-1) terms in the Sum, and the average of Sum in such a series is ((n-1)+1)/2 {(last + first)/2}, Sum = n(n-1)/2

How can I see an the output of my C programs using Dev-C++?

When a program is not showing or displaying an output on the screen, using system("pause"); is the solution to it on a Windows profile.

Java Package Does Not Exist Error

I had the exact same problem when manually compiling through the command line, my solution was I didn't include the -sourcepath directory so that way all the subdirectory java files would be compiled too!

How to test if a list contains another list?

I tried to make this as efficient as possible.

It uses a generator; those unfamiliar with these beasts are advised to check out their documentation and that of yield expressions.

Basically it creates a generator of values from the subsequence that can be reset by sending it a true value. If the generator is reset, it starts yielding again from the beginning of sub.

Then it just compares successive values of sequence with the generator yields, resetting the generator if they don't match.

When the generator runs out of values, i.e. reaches the end of sub without being reset, that means that we've found our match.

Since it works for any sequence, you can even use it on strings, in which case it behaves similarly to str.find, except that it returns False instead of -1.

As a further note: I think that the second value of the returned tuple should, in keeping with Python standards, normally be one higher. i.e. "string"[0:2] == "st". But the spec says otherwise, so that's how this works.

It depends on if this is meant to be a general-purpose routine or if it's implementing some specific goal; in the latter case it might be better to implement a general-purpose routine and then wrap it in a function which twiddles the return value to suit the spec.

def reiterator(sub):
    """Yield elements of a sequence, resetting if sent ``True``."""
    it = iter(sub)
    while True:
        if (yield it.next()):
            it = iter(sub)

def find_in_sequence(sub, sequence):
    """Find a subsequence in a sequence.

    >>> find_in_sequence([2, 1], [-1, 0, 1, 2])
    False
    >>> find_in_sequence([-1, 1, 2], [-1, 0, 1, 2])
    False
    >>> find_in_sequence([0, 1, 2], [-1, 0, 1, 2])
    (1, 3)
    >>> find_in_sequence("subsequence",
    ...                  "This sequence contains a subsequence.")
    (25, 35)
    >>> find_in_sequence("subsequence", "This one doesn't.")
    False

    """
    start = None
    sub_items = reiterator(sub)
    sub_item = sub_items.next()
    for index, item in enumerate(sequence):
        if item == sub_item:
            if start is None: start = index
        else:
            start = None
        try:
            sub_item = sub_items.send(start is None)
        except StopIteration:
            # If the subsequence is depleted, we win!
            return (start, index)
    return False

How to open up a form from another form in VB.NET?

Private Sub Button3_Click(sender As System.Object, e As System.EventArgs) _
                          Handles Button3.Click

    Dim box = New AboutBox1()
    box.Show()

End Sub

Set date input field's max date to today

You will need Javascript to do this:

HTML

<input id="datefield" type='date' min='1899-01-01' max='2000-13-13'></input>

JS

var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
 if(dd<10){
        dd='0'+dd
    } 
    if(mm<10){
        mm='0'+mm
    } 

today = yyyy+'-'+mm+'-'+dd;
document.getElementById("datefield").setAttribute("max", today);

JSFiddle demo

image.onload event and browser cache

If the src is already set then the event is firing in the cached case before you even get the event handler bound. So, you should trigger the event based off .complete also.

code sample:

$("img").one("load", function() {
   //do stuff
}).each(function() {
   if(this.complete || /*for IE 10-*/ $(this).height() > 0)
     $(this).load();
});

What is the correct syntax of ng-include?

    <ng-include src="'views/sidepanel.html'"></ng-include>

OR

    <div ng-include="'views/sidepanel.html'"></div>

OR

    <div ng-include src="'views/sidepanel.html'"></div>

Points To Remember:

--> No spaces in src

--> Remember to use single quotation in double quotation for src

Why is String immutable in Java?

String is immutable for several reasons, here is a summary:

  • Security: parameters are typically represented as String in network connections, database connection urls, usernames/passwords etc. If it were mutable, these parameters could be easily changed.
  • Synchronization and concurrency: making String immutable automatically makes them thread safe thereby solving the synchronization issues.
  • Caching: when compiler optimizes your String objects, it sees that if two objects have same value (a="test", and b="test") and thus you need only one string object (for both a and b, these two will point to the same object).
  • Class loading: String is used as arguments for class loading. If mutable, it could result in wrong class being loaded (because mutable objects change their state).

That being said, immutability of String only means you cannot change it using its public API. You can in fact bypass the normal API using reflection. See the answer here.

In your example, if String was mutable, then consider the following example:

  String a="stack";
  System.out.println(a);//prints stack
  a.setValue("overflow");
  System.out.println(a);//if mutable it would print overflow

How to create a generic array?

Problem is that while runtime generic type is erased so new E[10] would be equivalent to new Object[10].

This would be dangerous because it would be possible to put in array other data than of E type. That is why you need to explicitly say that type you want by either

How can I round a number in JavaScript? .toFixed() returns a string?

Number.prototype.toFixed is a function designed to format a number before printing it out. It's from the family of toString, toExponential and toPrecision.

To round a number, you would do this:

someNumber = 42.008;
someNumber = Math.round( someNumber * 1e2 ) / 1e2;
someNumber === 42.01;

// if you need 3 digits, replace 1e2 with 1e3 etc.
// or just copypaste this function to your code:

function toFixedNumber(num, digits, base){
  var pow = Math.pow(base||10, digits);
  return Math.round(num*pow) / pow;
}

.

Or if you want a “native-like” function, you can extend the prototype:

Number.prototype.toFixedNumber = function(digits, base){
  var pow = Math.pow(base||10, digits);
  return Math.round(this*pow) / pow;
}
someNumber = 42.008;
someNumber = someNumber.toFixedNumber(2);
someNumber === 42.01;


//or even hexadecimal

someNumber = 0xAF309/256  //which is af3.09
someNumber = someNumber.toFixedNumber(1, 16);
someNumber.toString(16) === "af3.1";

However, bear in mind that polluting the prototype is considered bad when you're writing a module, as modules shouldn't have any side effects. So, for a module, use the first function.

Passing Arrays to Function in C++

The simple answer is that arrays are ALWAYS passed by reference and the int arg[] simply lets the compiler know to expect an array

GitLab remote: HTTP Basic: Access denied and fatal Authentication

I was also facing the same issue. The reason for the problem was authentication error. To solve this problem go to Control Panel -> Credential Manager -> Generic Credentials here find your gitlab credential and edit them. Make sure your ID password is right or not

enter image description here

SQL Server - calculate elapsed time between two datetime stamps in HH:MM:SS format

select convert(varchar, Max(Time) - Min(Time) , 108) from logTable where id=...

What is the easiest way to get the current day of the week in Android?

Use the Java Calendar class.

Calendar calendar = Calendar.getInstance();
int day = calendar.get(Calendar.DAY_OF_WEEK); 

switch (day) {
    case Calendar.SUNDAY:
        // Current day is Sunday
        break;
    case Calendar.MONDAY:
        // Current day is Monday
        break;
    case Calendar.TUESDAY:
        // etc.
        break;
}

Why do I get "warning longer object length is not a multiple of shorter object length"?

You don't give a reproducible example but your warning message tells you exactly what the problem is.

memb only has a length of 10. I'm guessing the length of dih_y2$MemberID isn't a multiple of 10. When using ==, R spits out a warning if it isn't a multiple to let you know that it's probably not doing what you're expecting it to do. == does element-wise checking for equality. I suspect what you want to do is find which of the elements of dih_y2$MemberID are also in the vector memb. To do this you would want to use the %in% operator.

dih_col <- which(dih_y2$MemeberID %in% memb)

How to create a file in Ruby

Use:

File.open("out.txt", [your-option-string]) {|f| f.write("write your stuff here") }

where your options are:

  • r - Read only. The file must exist.
  • w - Create an empty file for writing.
  • a - Append to a file.The file is created if it does not exist.
  • r+ - Open a file for update both reading and writing. The file must exist.
  • w+ - Create an empty file for both reading and writing.
  • a+ - Open a file for reading and appending. The file is created if it does not exist.

In your case, 'w' is preferable.

OR you could have:

out_file = File.new("out.txt", "w")
#...
out_file.puts("write your stuff here")
#...
out_file.close

jQuery onclick event for <li> tags

Typing in $(this) will return the jQuery element instead of the HTML Element. Then it just depends on what you want to do in the click event.

alert($(this));

How do you convert a DataTable into a generic list?

If anyone want's to create custom function to convert datatable to list

class Program
{
    static void Main(string[] args)
    {
        DataTable table = GetDataTable();
        var sw = new Stopwatch();

        sw.Start();
        LinqMethod(table);
        sw.Stop();
        Console.WriteLine("Elapsed time for Linq Method={0}", sw.ElapsedMilliseconds);

        sw.Reset();

        sw.Start();
        ForEachMethod(table);
        sw.Stop();
        Console.WriteLine("Elapsed time for Foreach method={0}", sw.ElapsedMilliseconds);

        Console.ReadKey();
    }

    private static DataTable GetDataTable()
    {
        var table = new DataTable();
        table.Columns.Add("ID", typeof(double));
        table.Columns.Add("CategoryName", typeof(string));
        table.Columns.Add("Active", typeof(double));

        var rand = new Random();

        for (int i = 0; i < 100000; i++)
        {
            table.Rows.Add(i, "name" + i,  rand.Next(0, 2));
        }
        return table;
    }

    private static void LinqMethod(DataTable table)
    {
        var list = table.AsEnumerable()
            .Skip(1)
            .Select(dr =>
                new Category
                {
                    Id = Convert.ToInt32(dr.Field<double>("ID")),
                    CategoryName = dr.Field<string>("CategoryName"),                      
                    IsActive =
                            dr.Field<double>("Active") == 1 ? true : false
                }).ToList();
    }
    private static void ForEachMethod(DataTable table)
    {
        var categoryList = new List<Category>(table.Rows.Count);
        foreach (DataRow row in table.Rows)
        {
            var values = row.ItemArray;
            var category = new Category()
            {
                Id = Convert.ToInt32(values[0]),
                CategoryName = Convert.ToString(values[1]),                   
                IsActive = (double)values[2] == 1 ? true : false
            };
            categoryList.Add(category);
        }
    }

    private class Category
    {
        public int Id { get; set; }
        public string CategoryName { get; set; }
        public bool IsActive { get; set; }
    }
}

If we execute above code, Foreach method finishes in 56ms while linq one takes 101ms ( for 1000 records). So Foreach method is better to use. Source:Ways to Convert Datatable to List in C# (with performance test example)

How to clean node_modules folder of packages that are not in package.json?

Due to its folder nesting Windows can’t delete the folder as its name is too long. To solve this, install RimRaf:

npm install rimraf -g

rimraf node_modules

All ASP.NET Web API controllers return 404

Had this problem. Had to uncheck Precompile during publishing.

Composer update memory limit

On MAC OS High Siera I ran the below:

MacBook-Pro:asiu jack$ php --ini

Returned:

Configuration File (php.ini) Path: /usr/local/etc/php/7.4
Loaded Configuration File:         /usr/local/etc/php/7.4/php.ini
Scan for additional .ini files in: /usr/local/etc/php/7.4/conf.d
Additional .ini files parsed:      /usr/local/etc/php/7.4/conf.d/ext- 
opcache.ini,
/usr/local/etc/php/7.4/conf.d/php-memory-limits.ini

All answers above are setting the loaded config which does update, but notice additional .ini files parsed has php-memory-limits.ini as a separate file. You have to update this file memeory limit as well. same way open in text editor and change to somehting like 2G. The output on memory limit failure should tell you how much memory it needs to run, just set it to higher than that or -1 for unlimited.

What does ==$0 (double equals dollar zero) mean in Chrome Developer Tools?

$0 returns the most recently selected element or JavaScript object, $1 returns the second most recently selected one, and so on.

Refer : Command Line API Reference

What does [object Object] mean?

You have a javascript object

$1 and $2 are jquery objects, maybe use alert($1.text()); to get text or alert($1.attr('id'); etc...

you have to treat $1 and $2 like jQuery objects.

Concatenating bits in VHDL

You are not allowed to use the concatenation operator with the case statement. One possible solution is to use a variable within the process:

process(b0,b1,b2,b3)
   variable bcat : std_logic_vector(0 to 3);
begin
   bcat := b0 & b1 & b2 & b3;
   case bcat is
      when "0000" => x <= 1;
      when others => x <= 2;
   end case;
end process;

How to recursively download a folder via FTP on Linux

If lftp is installed on your machine, use mirror dir. And you are done. See the comment by Ciro below if you want to recursively download a directory.

How to set component default props on React component

If you're using a functional component, you can define defaults in the destructuring assignment, like so:

export default ({ children, id="menu", side="left", image={menu} }) => {
  ...
};

How do I convert Int/Decimal to float in C#?

You don't even need to cast, it is implicit.

int i = 3;

float f = i;

A full list/table of implicit numeric conversions can be seen here http://msdn.microsoft.com/en-us/library/y5b434w4.aspx

jQuery's .click - pass parameters to user function

I get the simple solution:

 <button id="btn1" onclick="sendData(20)">ClickMe</button>

<script>
   var id; // global variable
   function sendData(valueId){
     id = valueId;
   }
   $("#btn1").click(function(){
        alert(id);
     });
</script>

My mean is that pass the value onclick event to the javascript function sendData(), initialize to the variable and take it by the jquery event handler method.

This is possible since at first sendData(valueid) gets called and initialize the value. Then after jquery event get's executed and use that value.

This is the straight forward solution and For Detail solution go Here.

Currency formatting in Python

A lambda for calculating it inside a function, with help from @Nate's answer

converter = lambda amount, currency: "%s%s%s" %(
    "-" if amount < 0 else "", 
    currency, 
    ('{:%d,.2f}'%(len(str(amount))+3)).format(abs(amount)).lstrip())

and then,

>>> converter(123132132.13, "$")
'$123,132,132.13'

>>> converter(-123132132.13, "$")
'-$123,132,132.13'

How change List<T> data to IQueryable<T> data

var list = new List<string>();
var queryable = list.AsQueryable();

Add a reference to: System.Linq

What version of javac built my jar?

I as well wrote my own bash script to dump the Java version required by all the jars passed at the command line... Mine is a bit rough, but works for me ;-)

example usage

$ jar_dump_version_of_jvm_required.sh *.jar
JVM VERSION REQUIRED: 46.0, /private/tmp/jars/WEB-INF/lib/json-simple-1.1.jar
JVM VERSION REQUIRED: 49.0, /private/tmp/jars/WEB-INF/lib/json-smart-1.1.1.jar
JVM VERSION REQUIRED: 50.0, /private/tmp/jars/WEB-INF/lib/jsontoken-1.0.jar
JVM VERSION REQUIRED: 50.0, /private/tmp/jars/WEB-INF/lib/jsr166y-1.7.0.jar

jar_dump_version_of_jvm_required.sh

#!/bin/bash

DIR=$(PWD)
function show_help()
{
  ME=$(basename $0)
  IT=$(cat <<EOF

  Dumps the version of the JVM required to run the classes in a jar file

  usage: $ME JAR_FILE

  e.g. 

  $ME myFile.jar    ->  VERSION: 50.0     myFile.jar

  Java versions are:
  54 = Java 10
  53 = Java 9
  52 = Java 8
  51 = Java 7
  50 = Java 6
  49 = Java 5
  48 = Java 1.4
  47 = Java 1.3
  46 = Java 1.2
  45.3 = Java 1.1

EOF
  )
  echo "$IT"
  exit
}

if [ "$1" == "help" ]
then
  show_help
fi
if [ -z "$1" ]
then
  show_help
fi

function unzipJarToTmp()
{
  JAR=$1
  CLASS_FILE=$(jar -tf "$JAR" | grep \.class$ | grep -v '\$' | head -n1 | awk '{print $NF}')
  OUT_FILE="$CLASS_FILE"
  #echo "J=$JAR C=$CLASS_FILE O=$OUT_FILE"
  jar xf "$JAR" "$CLASS_FILE"

  MAJOR=$(javap -v "$OUT_FILE" 2>&1 | grep major | awk -F' ' '{print $3'})
  MINOR=$(javap -v "$OUT_FILE" 2>&1 | grep minor | awk -F' ' '{print $3'})
  if [ -z "$MAJOR" ]
  then
    echo "JVM VERSION REQUIRED: NA as no classes in $JAR"
  else
    echo "JVM VERSION REQUIRED: $MAJOR.$MINOR, $JAR"
  fi
}

# loop over cmd line args
for JAR in "$@"
do
  cd "$DIR"
  JAR_UID=$(basename "$JAR" | sed s/.jar//g)
  TMPDIR=/tmp/jar_dump/$JAR_UID/
  mkdir -p "$TMPDIR"
  JAR_ABS_PATH=$(realpath $JAR)

  cd "$TMPDIR"

  #echo "$JAR_ABS_PATH"
  unzipJarToTmp "$JAR_ABS_PATH"
  #sleep 2
done

Spring MVC: how to create a default controller for index page?

The solution I use in my SpringMVC webapps is to create a simple DefaultController class like the following: -

@Controller
public class DefaultController {

    private final String redirect;

    public DefaultController(String redirect) {
        this.redirect = redirect;
    }

    @RequestMapping(value = "/")
    public ModelAndView redirectToMainPage() {
        return new ModelAndView("redirect:/" + redirect);
    }

}

The redirect can be injected in using the following spring configuration: -

<bean class="com.adoreboard.farfisa.controller.DefaultController">
    <constructor-arg name="redirect" value="${default.redirect:loginController}"/>
</bean>

The ${default.redirect:loginController} will default to loginController but can be changed by inserting default.redirect=something_else into a spring properties file / setting an environment variable etc.

As @Mike has mentioned above I have also: -

  • Got rid of <welcome-file-list> ... </welcome-file-list> section in the web.xml file.
  • Don't have any files sitting in WebContent that would be considered default pages (index.html, index.jsp, default.html, etc)

This solution lets Spring worry more about redirects which may or may not be what you like.

How to set up Android emulator proxy settings

Now there is a setting in Android emulator enter image description here

Convert a CERT/PEM certificate to a PFX certificate

If you have a self-signed certificate generated by makecert.exe on a Windows machine, you will get two files: cert.pvk and cert.cer. These can be converted to a pfx using pvk2pfx

pvk2pfx is found in the same location as makecert (e.g. C:\Program Files (x86)\Windows Kits\10\bin\x86 or similar)

pvk2pfx -pvk cert.pvk -spc cert.cer -pfx cert.pfx

How to set div's height in css and html

To write inline styling use:

<div style="height: 100px;">
asdfashdjkfhaskjdf
</div>

Inline styling serves a purpose however, it is not recommended in most situations.

The more "proper" solution, would be to make a separate CSS sheet, include it in your HTML document, and then use either an ID or a class to reference your div.

if you have the file structure:

index.html
>>/css/
>>/css/styles.css

Then in your HTML document between <head> and </head> write:

<link href="css/styles.css" rel="stylesheet" />

Then, change your div structure to be:

<div id="someidname" class="someclassname">
    asdfashdjkfhaskjdf
</div>

In css, you can reference your div from the ID or the CLASS.

To do so write:

.someclassname { height: 100px; }

OR

#someidname { height: 100px; }

Note that if you do both, the one that comes further down the file structure will be the one that actually works.

For example... If you have:

.someclassname { height: 100px; }

.someclassname { height: 150px; }

Then in this situation the height will be 150px.

EDIT:

To answer your secondary question from your edit, probably need overflow: hidden; or overflow: visible; . You could also do this:

<div class="span12">
    <div style="height:100px;">
        asdfashdjkfhaskjdf
    </div>
</div>

Exiting out of a FOR loop in a batch file?

My answer
Use nested for loops to provide break points to the for /l loop.

for %%a in (0 1 2 3 4 5 6 7 8 9) do (
   for %%b in (0 1 2 3 4 5 6 7 8 9) do (
      for /l %%c in (1,1,10) do (
         if not exist %%a%%b%%c goto :continue
      )
   )
)
:continue

Explanation The code must be tweaked significantly to properly use the nested loops. For example, what is written will have leading zeros.
"Regular" for loops can be immediately broken out of with a simple goto command, where for /l loops cannot. This code's innermost for /l loop cannot be immediately broken, but an overall break point is present after every 10 iterations (as written). The innermost loop doesn't have to be 10 iterations -- you'll just have to account for the math properly if you choose to do 100 or 1000 or 2873 for that matter (if math even matters to the loop).

History I found this question while trying to figure out why a certain script was running slowly. It turns out I used multiple loops with a traditional loop structure:

set cnt=1
:loop
if "%somecriteria%"=="finished" goto :continue
rem do some things here
set /a cnt += 1
goto :loop

:continue
echo the loop ran %cnt% times

This script file had become somewhat long and it was being run from a network drive. This type of loop file was called maybe 20 times and each time it would loop 50-100 times. The script file was taking too long to run. I had the bright idea of attempting to convert it to a for /l loop. The number of needed iterations is unknown, but less than 10000. My first attempt was this:

setlocal enabledelayedexpansion
set cnt=1
for /l %%a in (1,1,10000) do (
   if "!somecriteria!"=="finished" goto :continue
   rem do some things here
   set /a cnt += 1
)

:continue
echo the loop ran %cnt% times

With echo on, I quickly found out that the for /l loop still did ... something ... without actually doing anything. It ran much faster, but still slower than I thought it could/should. Therefore I found this question and ended up with the nested loop idea presented above.

Side note It turns out that the for /l loop can be sped up quite a bit by simply making sure it doesn't have any output. I was able to do this for a noticeable speed increase:

setlocal enabledelayedexpansion
set cnt=1
@for /l %%a in (1,1,10000) do @(
   if "!somecriteria!"=="finished" goto :continue
   rem do some things here
   set /a cnt += 1
) > nul

:continue
echo the loop ran %cnt% times

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

Unique Key constraints for multiple columns in Entity Framework

In the accepted answer by @chuck, there is a comment saying it will not work in the case of FK.

it worked for me, case of EF6 .Net4.7.2

public class OnCallDay
{
     public int Id { get; set; }
    //[Key]
    [Index("IX_OnCallDateEmployee", 1, IsUnique = true)]
    public DateTime Date { get; set; }
    [ForeignKey("Employee")]
    [Index("IX_OnCallDateEmployee", 2, IsUnique = true)]
    public string EmployeeId { get; set; }
    public virtual ApplicationUser Employee{ get; set; }
}

Use FontAwesome or Glyphicons with css :before

Re: using icon in :before – recent Font Awesome builds include the .fa-icon() mixin for SASS and LESS. This will automatically include the font-family as well as some rendering tweaks (e.g. -webkit-font-smoothing). Thus you can do, e.g.:

// Add "?" icon to header.
h1:before {
    .fa-icon();
    content: "\f059";
}

How to catch exception correctly from http.request()?

The RxJS functions need to be specifically imported. An easy way to do this is to import all of its features with import * as Rx from "rxjs/Rx"

Then make sure to access the Observable class as Rx.Observable.

select and echo a single field from mysql db using PHP

And escape your values with mysql_real_escape_string since PHP6 won't do that for you anymore! :)

How do ACID and database transactions work?

Transaction can be defined as a collection of task that are considered as minimum processing unit. Each minimum processing unit can not be divided further.

All transaction must contain four properties that commonly known as ACID properties. i.e ACID are the group of properties of any transaction.

  • Atomicity :
  • Consistency
  • Isolation
  • Durability

Why can a function modify some arguments as perceived by the caller, but not others?

Some answers contain the word "copy" in a context of a function call. I find it confusing.

Python doesn't copy objects you pass during a function call ever.

Function parameters are names. When you call a function Python binds these parameters to whatever objects you pass (via names in a caller scope).

Objects can be mutable (like lists) or immutable (like integers, strings in Python). Mutable object you can change. You can't change a name, you just can bind it to another object.

Your example is not about scopes or namespaces, it is about naming and binding and mutability of an object in Python.

def f(n, x): # these `n`, `x` have nothing to do with `n` and `x` from main()
    n = 2    # put `n` label on `2` balloon
    x.append(4) # call `append` method of whatever object `x` is referring to.
    print('In f():', n, x)
    x = []   # put `x` label on `[]` ballon
    # x = [] has no effect on the original list that is passed into the function

Here are nice pictures on the difference between variables in other languages and names in Python.

How do I get the Date & Time (VBS)

There are also separate Time() and Date() functions.

PHP - Redirect and send data via POST

Use curl for this. Google for "curl php post" and you'll find this: http://www.askapache.com/htaccess/sending-post-form-data-with-php-curl.html.

Note that you could also use an array for the CURLOPT_POSTFIELDS option. From php.net docs:

The full data to post in a HTTP "POST" operation. To post a file, prepend a filename with @ and use the full path. This can either be passed as a urlencoded string like 'para1=val1&para2=val2&...' or as an array with the field name as key and field data as value. If value is an array, the Content-Type header will be set to multipart/form-data.

ggplot legends - change labels, order and title

You need to do two things:

  1. Rename and re-order the factor levels before the plot
  2. Rename the title of each legend to the same title

The code:

dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))

library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha = 0.35, linetype=0)+ 
  geom_line(aes(linetype=model), size = 1) +       
  geom_point(aes(shape=model), size=4)  +      
  theme(legend.position=c(.6,0.8)) +
  theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
  scale_linetype_discrete("Model 1") +
  scale_shape_discrete("Model 1") +
  scale_colour_discrete("Model 1")

enter image description here

However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:

ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
  geom_ribbon(alpha=0.2, colour=NA)+ 
  geom_line() +       
  geom_point()  +      
  facet_wrap(~model)

enter image description here

How to check compiler log in sql developer?

To see your log in SQL Developer then press:

CTRL+SHIFT + L (or CTRL + CMD + L on macOS)

or

View -> Log

or by using mysql query

show errors;

How to modify a CSS display property from JavaScript?

I found the solution.

As said in the EDIT of my answer, a <div> is misfunctioning in a <table>. So I wrote this code instead :

<tr id="hidden" style="display:none;">
    <td class="depot_table_left">
        <label for="sexe">Sexe</label>
    </td>
    <td>
        <select type="text" name="sexe">
            <option value="1">Sexe</option>
            <option value="2">Joueur</option>
            <option value="3">Joueuse</option>
        </select>
    </td>
</tr>

And this is working fine.

Thanks everybody ;)

How to use PHP OPCache?

With PHP 5.6 on Amazon Linux (should be the same on RedHat or CentOS):

yum install php56-opcache

and then restart apache.

Overflow Scroll css is not working in the div

For Angular2 + Material2 + Sidenav, you'll need to do the following:

 ngAfterViewInit() {
   this.element.nativeElement.getElementsByClassName('md-sidenav-content')[0].style.overflow = 'hidden'; 
  }

List the queries running on SQL Server

in 2005 you can right click on a database, go to reports and there's a whole list of reports on transitions and locks etc...

Simplest way to throw an error/exception with a custom message in Swift 2?

Check this cool version out. The idea is to implement both String and ErrorType protocols and use the error's rawValue.

enum UserValidationError: String, Error {
  case noFirstNameProvided = "Please insert your first name."
  case noLastNameProvided = "Please insert your last name."
  case noAgeProvided = "Please insert your age."
  case noEmailProvided = "Please insert your email."
}

Usage:

do {
  try User.define(firstName,
                  lastName: lastName,
                  age: age,
                  email: email,
                  gender: gender,
                  location: location,
                  phone: phone)
}
catch let error as User.UserValidationError {
  print(error.rawValue)
  return
}

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

I faced the same problem and did the filtering false like below working for me. You can try the same...

<testResources>
    <testResource>
        <directory>src/test/java</directory>
        <filtering>false</filtering>
    </testResource>
    <testResource>
        <directory>src/test/resources</directory>
        <filtering>false</filtering>
    </testResource>
</testResources>

'NoneType' object is not subscriptable?

Point A: Don't use list as a variable name Point B: You don't need the [0] just

print(list[x])

How to change the font and font size of an HTML input tag?

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

css

input[type="text"]
{
    font-size:24px;
}