Programs & Examples On #Update attribute

Skip rows during csv import pandas

You can try yourself:

>>> import pandas as pd
>>> from StringIO import StringIO
>>> s = """1, 2
... 3, 4
... 5, 6"""
>>> pd.read_csv(StringIO(s), skiprows=[1], header=None)
   0  1
0  1  2
1  5  6
>>> pd.read_csv(StringIO(s), skiprows=1, header=None)
   0  1
0  3  4
1  5  6

MVC 3: How to render a view without its layout page when loaded via ajax?

With ASP.NET 5 there is no Request variable available anymore. You can access it now with Context.Request

Also there is no IsAjaxRequest() Method anymore, you have to write it by yourself, for example in Extensions\HttpRequestExtensions.cs

using System;
using Microsoft.AspNetCore.Http;

namespace Microsoft.AspNetCore.Mvc
{
    public static class HttpRequestExtensions
    {
        public static bool IsAjaxRequest(this HttpRequest request)
        {
            if (request == null)
            {
                throw new ArgumentNullException(nameof(request));
            }

            return (request.Headers != null) && (request.Headers["X-Requested-With"] == "XMLHttpRequest");
        }
    }
}

I searched for a while now on this and hope that will help some others too ;)

Resource: https://github.com/aspnet/AspNetCore/issues/2729

Jinja2 template variable if None Object set a default value

Following this doc you can do this that way:

{{ p.User['first_name']|default('NONE') }}

Select all columns except one in MySQL?

I agree with the "simple" solution of listing all the columns, but this can be burdensome, and typos can cause lots of wasted time. I use a function "getTableColumns" to retrieve the names of my columns suitable for pasting into a query. Then all I need to do is to delete those I don't want.

CREATE FUNCTION `getTableColumns`(tablename varchar(100)) 
          RETURNS varchar(5000) CHARSET latin1
BEGIN
  DECLARE done INT DEFAULT 0;
  DECLARE res  VARCHAR(5000) DEFAULT "";

  DECLARE col  VARCHAR(200);
  DECLARE cur1 CURSOR FOR 
    select COLUMN_NAME from information_schema.columns 
    where TABLE_NAME=@table AND TABLE_SCHEMA="yourdatabase" ORDER BY ORDINAL_POSITION;
  DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
  OPEN cur1;
  REPEAT
       FETCH cur1 INTO col;
       IF NOT done THEN 
          set res = CONCAT(res,IF(LENGTH(res)>0,",",""),col);
       END IF;
    UNTIL done END REPEAT;
  CLOSE cur1;
  RETURN res;

Your result returns a comma delimited string, for example...

col1,col2,col3,col4,...col53

XMLHttpRequest cannot load XXX No 'Access-Control-Allow-Origin' header

This CORS issue wasn't further elaborated (for other causes).

I'm having this issue currently under different reason. My front end is returning 'Access-Control-Allow-Origin' header error as well.

Just that I've pointed the wrong URL so this header wasn't reflected properly (in which i kept presume it did). localhost (front end) -> call to non secured http (supposed to be https), make sure the API end point from front end is pointing to the correct protocol.

Difference between List, List<?>, List<T>, List<E>, and List<Object>

The reason you cannot cast List<String> to List<Object> is that it would allow you to violate the constraints of the List<String>.

Think about the following scenario: If I have a List<String>, it is supposed to only contain objects of type String. (Which is a final class)

If I can cast that to a List<Object>, then that allows me to add Object to that list, thus violating the original contract of List<String>.

Thus, in general, if class C inherits from class P, you cannot say that GenericType<C> also inherits from GenericType<P>.

N.B. I already commented on this in a previous answer but wanted to expand on it.

Printing with "\t" (tabs) does not result in aligned columns

In continuation of the comments by Péter and duncan, I normally use a quick padding method, something like -

public String rpad(String inStr, int finalLength)
{
    return (inStr + "                          " // typically a sufficient length spaces string.
        ).substring(0, finalLength);
}

similarly you can have a lpad() as well

Mail not sending with PHPMailer over SSL using SMTP

Don't use SSL on port 465, it's been deprecated since 1998 and is only used by Microsoft products that didn't get the memo; use TLS on port 587 instead: So, the code below should work very well for you.

mail->IsSMTP(); // telling the class to use SMTP
$mail->Host       = "smtp.gmail.com"; // SMTP server

$mail->SMTPAuth   = true;                  // enable SMTP authentication
$mail->SMTPSecure = "tls";                 // sets the prefix to the servier
$mail->Host       = "smtp.gmail.com";      // sets GMAIL as the SMTP server
$mail->Port       = 587;                   // set the SMTP port for the 

How to cast DATETIME as a DATE in mysql?

Use DATE() function:

select * from follow_queue group by DATE(follow_date)

What is the difference between git pull and git fetch + git rebase?

TLDR:

git pull is like running git fetch then git merge
git pull --rebase is like git fetch then git rebase

In reply to your first statement,

git pull is like a git fetch + git merge.

"In its default mode, git pull is shorthand for git fetch followed by git merge FETCH_HEAD" More precisely, git pull runs git fetch with the given parameters and then calls git merge to merge the retrieved branch heads into the current branch"

(Ref: https://git-scm.com/docs/git-pull)


For your second statement/question:

'But what is the difference between git pull VS git fetch + git rebase'

Again, from same source:
git pull --rebase

"With --rebase, it runs git rebase instead of git merge."


Now, if you wanted to ask

'the difference between merge and rebase'

that is answered here too:
https://git-scm.com/book/en/v2/Git-Branching-Rebasing
(the difference between altering the way version history is recorded)

Multi-line bash commands in makefile

What's wrong with just invoking the commands?

foo:
       echo line1
       echo line2
       ....

And for your second question, you need to escape the $ by using $$ instead, i.e. bash -c '... echo $$a ...'.

EDIT: Your example could be rewritten to a single line script like this:

gcc $(for i in `find`; do echo $i; done)

How to save a pandas DataFrame table as a png

There is actually a python library called dataframe_image Just do a

pip install dataframe_image

Do the imports

import pandas as pd
import numpy as np
import dataframe_image as dfi
df = pd.DataFrame(np.random.randn(6, 6), columns=list('ABCDEF'))

and style your table if you want by:

df_styled = df.style.background_gradient() #adding a gradient based on values in cell

and finally:

dfi.export(df_styled,"mytable.png")

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc2

I was running into a similar error in pywikipediabot. The .decode method is a step in the right direction but for me it didn't work without adding 'ignore':

ignore_encoding = lambda s: s.decode('utf8', 'ignore')

Ignoring encoding errors can lead to data loss or produce incorrect output. But if you just want to get it done and the details aren't very important this can be a good way to move faster.

How to save a bitmap on internal storage

Modify onClick() as follows:

@Override
public void onClick(View v) {
    if(v == btn) {
        canvas=sv.getHolder().lockCanvas();
        if(canvas!=null) {
            canvas.drawBitmap(bitmap, 100, 100, null);
            sv.getHolder().unlockCanvasAndPost(canvas);
        }
    } else if(v == btn1) {
        saveBitmapToInternalStorage(bitmap);
    }
}

There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.

I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:

if(v == btn) {
    ...
    btn1.setEnabled(true);
}

Creating a dynamic choice field

the problem is when you do

def __init__(self, user, *args, **kwargs):
    super(waypointForm, self).__init__(*args, **kwargs)
    self.fields['waypoints'] = forms.ChoiceField(choices=[ (o.id, str(o)) for o in Waypoint.objects.filter(user=user)])

in a update request, the previous value will lost!

How to scroll the window using JQuery $.scrollTo() function

If it's not working why don't you try using jQuery's scrollTop method?

$("#id").scrollTop($("#id").scrollTop() + 100);

If you're looking to scroll smoothly you could use basic javascript setTimeout/setInterval function to make it scroll in increments of 1px over a set length of time.

Default parameters with C++ constructors

This discussion apply both to constructors, but also methods and functions.

Using default parameters?

The good thing is that you won't need to overload constructors/methods/functions for each case:

// Header
void doSomething(int i = 25) ;

// Source
void doSomething(int i)
{
   // Do something with i
}

The bad thing is that you must declare your default in the header, so you have an hidden dependancy: Like when you change the code of an inlined function, if you change the default value in your header, you'll need to recompile all sources using this header to be sure they will use the new default.

If you don't, the sources will still use the old default value.

using overloaded constructors/methods/functions?

The good thing is that if your functions are not inlined, you then control the default value in the source by choosing how one function will behave. For example:

// Header
void doSomething() ;
void doSomething(int i) ;

// Source

void doSomething()
{
   doSomething(25) ;
}

void doSomething(int i)
{
   // Do something with i
}

The problem is that you have to maintain multiple constructors/methods/functions, and their forwardings.

Cannot connect to local SQL Server with Management Studio

Open Sql server 2014 Configuration Manager.

Click Sql server services and start the sql server service if it is stopped

Then click Check SQL server Network Configuration for TCP/IP Enabled

then restart the sql server management studio (SSMS) and connect your local database engine

Entity Framework - Code First - Can't Store List<String>

JSON.NET to the rescue.

You serialize it to JSON to persist in the Database and Deserialize it to reconstitute the .NET collection. This seems to perform better than I expected it to with Entity Framework 6 & SQLite. I know you asked for List<string> but here's an example of an even more complex collection that works just fine.

I tagged the persisted property with [Obsolete] so it would be very obvious to me that "this is not the property you are looking for" in the normal course of coding. The "real" property is tagged with [NotMapped] so Entity framework ignores it.

(unrelated tangent): You could do the same with more complex types but you need to ask yourself did you just make querying that object's properties too hard for yourself? (yes, in my case).

using Newtonsoft.Json;
....
[NotMapped]
public Dictionary<string, string> MetaData { get; set; } = new Dictionary<string, string>();

/// <summary> <see cref="MetaData"/> for database persistence. </summary>
[Obsolete("Only for Persistence by EntityFramework")]
public string MetaDataJsonForDb
{
    get
    {
        return MetaData == null || !MetaData.Any()
                   ? null
                   : JsonConvert.SerializeObject(MetaData);
    }

    set
    {
        if (string.IsNullOrWhiteSpace(value))
           MetaData.Clear();
        else
           MetaData = JsonConvert.DeserializeObject<Dictionary<string, string>>(value);
    }
}

Convert int to string?

int num = 10;
string str = Convert.ToString(num);

What does "where T : class, new()" mean?

new(): Specifying the new() constraint means type T must use a parameterless constructor, so an object can be instantiated from it - see Default constructors.

class: Means T must be a reference type so it can't be an int, float, double, DateTime or other struct (value type).

public void MakeCars()
{
    //This won't compile as researchEngine doesn't have a public constructor and so can't be instantiated.
    CarFactory<ResearchEngine> researchLine = new CarFactory<ResearchEngine>();
    var researchEngine = researchLine.MakeEngine();

    //Can instantiate new object of class with default public constructor
    CarFactory<ProductionEngine> productionLine = new CarFactory<ProductionEngine>();
    var productionEngine = productionLine.MakeEngine();
}

public class ProductionEngine { }
public class ResearchEngine
{
    private ResearchEngine() { }
}

public class CarFactory<TEngine> where TEngine : class, new()
{
    public TEngine MakeEngine()
    {
        return new TEngine();
    }
}

How to set session attribute in java?

Try this.

<%@page language="java" session="true" %>

MVC 4 - Return error message from Controller - Show in View

You can add this to your _Layout.cshtml:

@using MyProj.ViewModels;
...
    @if (TempData["UserMessage"] != null)
    {
        var message = (MessageViewModel)TempData["UserMessage"];
        <div class="alert @message.CssClassName" role="alert">
            <button type="button" class="close" data-dismiss="alert" aria-label="Close">
                <span aria-hidden="true">&times;</span>
            </button>
            <strong>@message.Title</strong>
            @message.Message
        </div>
    }

Then if you want to throw an error message in your controller:

    TempData["UserMessage"] = new MessageViewModel() { CssClassName = "alert-danger  alert-dismissible", Title = "Error", Message = "This is an error message" };

MessageViewModel.cs:

public class MessageViewModel
    {
        public string CssClassName { get; set; }
        public string Title { get; set; }
        public string Message { get; set; }
    }

Note: Using Bootstrap 4 classes.

What column type/length should I use for storing a Bcrypt hashed password in a Database?

A Bcrypt hash can be stored in a BINARY(40) column.

BINARY(60), as the other answers suggest, is the easiest and most natural choice, but if you want to maximize storage efficiency, you can save 20 bytes by losslessly deconstructing the hash. I've documented this more thoroughly on GitHub: https://github.com/ademarre/binary-mcf

Bcrypt hashes follow a structure referred to as modular crypt format (MCF). Binary MCF (BMCF) decodes these textual hash representations to a more compact binary structure. In the case of Bcrypt, the resulting binary hash is 40 bytes.

Gumbo did a nice job of explaining the four components of a Bcrypt MCF hash:

$<id>$<cost>$<salt><digest>

Decoding to BMCF goes like this:

  1. $<id>$ can be represented in 3 bits.
  2. <cost>$, 04-31, can be represented in 5 bits. Put these together for 1 byte.
  3. The 22-character salt is a (non-standard) base-64 representation of 128 bits. Base-64 decoding yields 16 bytes.
  4. The 31-character hash digest can be base-64 decoded to 23 bytes.
  5. Put it all together for 40 bytes: 1 + 16 + 23

You can read more at the link above, or examine my PHP implementation, also on GitHub.

How to filter an array of objects based on values in an inner array with jq?

Here is another solution which uses any/2

map(select(any(.Names[]; contains("data"))|not)|.Id)[]

with the sample data and the -r option it produces

cb94e7a42732b598ad18a8f27454a886c1aa8bbba6167646d8f064cd86191e2b
a4b7e6f5752d8dcb906a5901f7ab82e403b9dff4eaaeebea767a04bac4aada19

How to use pip with python 3.4 on windows?

From the same page

Note: To avoid conflicts between parallel Python 2 and Python 3 installations, only the versioned pip3 and pip3.4 commands are bootstrapped by default when ensurepip is invoked directly - the --default-pip option is needed to also request the unversioned pip command. pyvenv and the Windows installer ensure that the unqualified pip command is made available in those environments, and pip can always be invoked via the -m switch rather than directly to avoid ambiguity on systems with multiple Python installations.

So try pip3 or pip3.4 in Command Prompt.

Also, ensure that environment variable are set for pip command, if you missed to opt-in for automatic PATH configuration.

Inheritance and init method in Python

Since you don't call Num.__init__ , the field "n1" never gets created. Call it and then it will be there.

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

Another Option that has worked well for me is using the synchronize module . Then remove the original directory using the file module.

Here is an example from the docs:

- synchronize:
    src: /first/absolute/path
    dest: /second/absolute/path
    archive: yes
  delegate_to: "{{ inventory_hostname }}"

When to use window.opener / window.parent / window.top

I think you need to add some context to your question. However, basic information about these things can be found here:

window.opener https://developer.mozilla.org/en-US/docs/Web/API/Window.opener

I've used window.opener mostly when opening a new window that acted as a dialog which required user input, and needed to pass information back to the main window. However this is restricted by origin policy, so you need to ensure both the content from the dialog and the opener window are loaded from the same origin.

window.parent https://developer.mozilla.org/en-US/docs/Web/API/Window.parent

I've used this mostly when working with IFrames that need to communicate with the window object that contains them.

window.top https://developer.mozilla.org/en-US/docs/Web/API/Window.top

This is useful for ensuring you are interacting with the top level browser window. You can use it for preventing another site from iframing your website, among other things.

If you add some more detail to your question, I can supply other more relevant examples.

UPDATE: There are a few ways you can handle your situation.
You have the following structure:

  • Main Window
    • Dialog 1
      • Dialog 2 Opened By Dialog 1

When Dialog 1 runs the code to open Dialog 2, after creating Dialog 2, have dialog 1 set a property on Dialog 2 that references the Dialog1 opener.

So if "childwindow" is you variable for the dialog 2 window object, and "window" is the variable for the Dialog 1 window object. After opening dialog 2, but before closing dialog 1 make an assignment similar to this:

childwindow.appMainWindow = window.opener

After making the assignment above, close dialog 1. Then from the code running inside dialog2, you should be able to use window.appMainWindow to reference the main window, window object.

Hope this helps.

relative path to CSS file

You have to move the css folder into your web folder. It seems that your web folder on the hard drive equals the /ServletApp folder as seen from the www. Other content than inside your web folder cannot be accessed from the browsers.

The url of the CSS link is then

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

Storing WPF Image Resources

Full description how to use resources: WPF Application Resource, Content, and Data Files

And how to reference them, read "Pack URIs in WPF".

In short, there is even means to reference resources from referenced/referencing assemblies.

Regular expression for first and last name

So, with customer we create this crazy regex:

(^$)|(^([^\-!#\$%&\(\)\*,\./:;\?@\[\\\]_\{\|\}¨?“”€\+<=>§°\d\s¤®™©]| )+$)

Prepend line to beginning of a file

Different Idea:

(1) You save the original file as a variable.

(2) You overwrite the original file with new information.

(3) You append the original file in the data below the new information.

Code:

with open(<filename>,'r') as contents:
      save = contents.read()
with open(<filename>,'w') as contents:
      contents.write(< New Information >)
with open(<filename>,'a') as contents:
      contents.write(save)

How to find memory leak in a C++ code/project?

Visual Leak Detector (VLD) is a free, robust, open-source memory leak detection system for Visual C++.

When you run your program under the Visual Studio debugger, Visual Leak Detector will output a memory leak report at the end of your debugging session. The leak report includes the full call stack showing how any leaked memory blocks were allocated. Double-click on a line in the call stack to jump to that file and line in the editor window.

If you only have crash dumps, you can use the Windbg !heap -l command, it will detect leaked heap blocks. Better open the gflags option: “Create user mode stack trace database”, then you will see the memory allocation call stack.

Keras model.summary() result - Understanding the # of Parameters

For Dense Layers:

output_size * (input_size + 1) == number_parameters 

For Conv Layers:

output_channels * (input_channels * window_size + 1) == number_parameters

Consider following example,

model = Sequential([
Conv2D(32, (3, 3), activation='relu', input_shape=input_shape),
Conv2D(64, (3, 3), activation='relu'),
Conv2D(128, (3, 3), activation='relu'),
Dense(num_classes, activation='softmax')
])

model.summary()
_________________________________________________________________
Layer (type)                 Output Shape              Param #   
=================================================================
conv2d_1 (Conv2D)            (None, 222, 222, 32)      896       
_________________________________________________________________
conv2d_2 (Conv2D)            (None, 220, 220, 64)      18496     
_________________________________________________________________
conv2d_3 (Conv2D)            (None, 218, 218, 128)     73856     
_________________________________________________________________
dense_9 (Dense)              (None, 218, 218, 10)      1290      
=================================================================

Calculating params,

assert 32 * (3 * (3*3) + 1) == 896
assert 64 * (32 * (3*3) + 1) == 18496
assert 128 * (64 * (3*3) + 1) == 73856
assert num_classes * (128 + 1) == 1290

Add a row number to result set of a SQL query

So before MySQL 8.0 there is no ROW_NUMBER() function. Accpted answer rewritten to support older versions of MySQL:

SET @row_number = 0;
SELECT t.A, t.B, t.C, (@row_number:=@row_number + 1) AS number
FROM dbo.tableZ AS t ORDER BY t.A;

ValueError: math domain error

Your code is doing a log of a number that is less than or equal to zero. That's mathematically undefined, so Python's log function raises an exception. Here's an example:

>>> from math import log
>>> log(-1)
Traceback (most recent call last):
  File "<pyshell#59>", line 1, in <module>
    log(-1)
ValueError: math domain error

Without knowing what your newtonRaphson2 function does, I'm not sure I can guess where the invalid x[2] value is coming from, but hopefully this will lead you on the right track.

How do I get the opposite (negation) of a Boolean in Python?

You can just compare the boolean array. For example

X = [True, False, True]

then

Y = X == False

would give you

Y = [False, True, False]

What throws an IOException in Java?

Java documentation is helpful to know the root cause of a particular IOException.

Just have a look at the direct known sub-interfaces of IOException from the documentation page:

ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException

Most of these exceptions are self-explanatory.

A few IOExceptions with root causes:

EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.

SocketException: Thrown to indicate that there is an error creating or accessing a Socket.

RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.

UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).

MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.

How do I start/stop IIS Express Server?

Closing IIS Express

By default Visual Studio places the IISExpress icon in your system tray at the lower right hand side of your screen, by the clock. You can right click it and choose exit. If you don't see the icon, try clicking the small arrow to view the full list of icons in the system tray.

IIS Express icon

then right click and choose Exit:

enter image description here


Changing the Port

Another option is to change the port by modifying the project properties. You'll need to do this for each web project in your solution.

  1. Visual Studio > Solution Explorer
  2. Right click the web project and choose Properties
  3. Go to the Web tab
  4. In the 'Servers' section, change the port in the Project URL box
  5. Repeat for each web project in the solution

Changing the IIS Express port


If All Else Fails

If that doesn't work, you can try to bring up Task Manager and close the IIS Express System Tray (32 bit) process and IIS Express Worker Process (32 bit).

Terminating the IIS Express Worker Thread process

If it still doesn't work, as ni5ni6 pointed out, there is a 'Web Deployment Agent Service' running on the port 80. Use this article to track down which process uses it, and turn it off:

https://sites.google.com/site/anashkb/port-80-in-use

Java 8 stream map on entry set

Question might be a little dated, but you could simply use AbstractMap.SimpleEntry<> as follows:

private Map<String, AttributeType> mapConfig(
    Map<String, String> input, String prefix) {
       int subLength = prefix.length();
       return input.entrySet()
          .stream()
          .map(e -> new AbstractMap.SimpleEntry<>(
               e.getKey().substring(subLength),
               AttributeType.GetByName(e.getValue()))
          .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue));

any other Pair-like value object would work too (ie. ApacheCommons Pair tuple).

Google map V3 Set Center to specific Marker

Once you have markers on the map, you can retrieve the Lat/Long coordinates through the API and use this to set the map's center. You'll first just need to determine which marker you wish to center on - I'll leave that up to you.

// "marker" refers to the Marker object you wish to center on

var latLng = marker.getPosition(); // returns LatLng object
map.setCenter(latLng); // setCenter takes a LatLng object

Info windows are separate objects which are typically bound to a marker, so to open the info window you might do something like this (however it will depend on your code):

var infoWindow = marker.infoWindow; // retrieve the InfoWindow object
infoWindow.open(map); // Trigger the "open()" method

Hope this helps.

What does "Object reference not set to an instance of an object" mean?

what does this error mean? Object reference not set to an instance of an object.

exactly what it says, you are trying to use a null object as if it was a properly referenced object.

Python exit commands - why so many and when should each be used?

The functions* quit(), exit(), and sys.exit() function in the same way: they raise the SystemExit exception. So there is no real difference, except that sys.exit() is always available but exit() and quit() are only available if the site module is imported.

The os._exit() function is special, it exits immediately without calling any cleanup functions (it doesn't flush buffers, for example). This is designed for highly specialized use cases... basically, only in the child after an os.fork() call.

Conclusion

  • Use exit() or quit() in the REPL.

  • Use sys.exit() in scripts, or raise SystemExit() if you prefer.

  • Use os._exit() for child processes to exit after a call to os.fork().

All of these can be called without arguments, or you can specify the exit status, e.g., exit(1) or raise SystemExit(1) to exit with status 1. Note that portable programs are limited to exit status codes in the range 0-255, if you raise SystemExit(256) on many systems this will get truncated and your process will actually exit with status 0.

Footnotes

* Actually, quit() and exit() are callable instance objects, but I think it's okay to call them functions.

Python strftime - date without leading 0?

Old question, but %l (lower-case L) worked for me in strftime: this may not work for everyone, though, as it's not listed in the Python documentation I found

Command CompileSwift failed with a nonzero exit code in Xcode 10

For me, the error message said I had too many simulator files open to build Swift. When I quit the simulator and built again, everything worked.

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

using wildcards in LDAP search filters/queries

A filter argument with a trailing * can be evaluated almost instantaneously via an index lookup. A leading * implies a sequential search through the index, so it is O(N). It will take ages.

I suggest you reconsider the requirement.

Number of elements in a javascript object

Although JS implementations might keep track of such a value internally, there's no standard way to get it.

In the past, Mozilla's Javascript variant exposed the non-standard __count__, but it has been removed with version 1.8.5.

For cross-browser scripting you're stuck with explicitly iterating over the properties and checking hasOwnProperty():

function countProperties(obj) {
    var count = 0;

    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            ++count;
    }

    return count;
}

In case of ECMAScript 5 capable implementations, this can also be written as (Kudos to Avi Flax)

function countProperties(obj) {
    return Object.keys(obj).length;
}

Keep in mind that you'll also miss properties which aren't enumerable (eg an array's length).

If you're using a framework like jQuery, Prototype, Mootools, $whatever-the-newest-hype, check if they come with their own collections API, which might be a better solution to your problem than using native JS objects.

Why do python lists have pop() but not push()

Probably because the original version of Python (CPython) was written in C, not C++.

The idea that a list is formed by pushing things onto the back of something is probably not as well-known as the thought of appending them.

Using C++ filestreams (fstream), how can you determine the size of a file?

You can open the file using the ios::ate flag (and ios::binary flag), so the tellg() function will give you directly the file size:

ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();

Case insensitive regular expression without re.compile?

You can also define case insensitive during the pattern compile:

pattern = re.compile('FIle:/+(.*)', re.IGNORECASE)

How to store JSON object in SQLite database

https://github.com/app-z/Json-to-SQLite

At first generate Plain Old Java Objects from JSON http://www.jsonschema2pojo.org/

Main method

void createDb(String dbName, String tableName, List dataList, Field[] fields){ ...

Fields name will create dynamically

How do you delete an ActiveRecord object?

  1. User.destroy

User.destroy(1) will delete user with id == 1 and :before_destroy and :after_destroy callbacks occur. For example if you have associated records

has_many :addresses, :dependent => :destroy

After user is destroyed his addresses will be destroyed too. If you use delete action instead, callbacks will not occur.

  1. User.destroy, User.delete

  2. User.destroy_all(<conditions>) or User.delete_all(<conditions>)

Notice: User is a class and user is an instance object

JavaScript: undefined !== undefined?

From - JQuery_Core_Style_Guidelines

  • Global Variables:
    typeof variable === "undefined"

  • Local Variables:
    variable === undefined

  • Properties:
    object.prop === undefined

Naming Conventions: What to name a boolean variable?

A simple semantic name would be last. This would allow code always positive code like:

if (item.last)
    ...

do {
   ...
} until (item.last);

change cursor from block or rectangle to line?

If you happen to be using a mac keyboard on linux (ubuntu), Insert is actually fn + return. You can also click on the zero of the number pad to switch between the cursor types.

Took me a while to figure that out. :-P

Can't connect to docker from docker-compose

I solved the issue in Ubuntu 20.0.4 by

sudo chmod 666 /var/run/docker.sock

and then

sudo service docker start && docker-compose up -d

Ref.

Errno 10061 : No connection could be made because the target machine actively refused it ( client - server )

Hint: actively refused sounds like somewhat deeper technical trouble, but...

...actually, this response (and also specifically errno:10061) is also given, if one calls the bin/mongo executable and the mongodb service is simply not running on the target machine. This even applies to local machine instances (all happening on localhost).

? Always rule out for this trivial possibility first, i.e. simply by using the command line client to access your db.

See here.

How do I change the default application icon in Java?

You can simply go Netbeans, in the design view, go to JFrame property, choose icon image property, Choose Set Form's iconImage property using: "Custom code" and then in the Form.SetIconImage() function put the following code:

Toolkit.getDefaultToolkit().getImage(name_of_your_JFrame.class.getResource("image.png"))

Do not forget to import:

import java.awt.Toolkit;

in the source code!

How to Decrease Image Brightness in CSS

Like

.classname
{
 opacity: 0.5;
}

Change size of axes title and labels in ggplot2

You can change axis text and label size with arguments axis.text= and axis.title= in function theme(). If you need, for example, change only x axis title size, then use axis.title.x=.

g+theme(axis.text=element_text(size=12),
        axis.title=element_text(size=14,face="bold"))

There is good examples about setting of different theme() parameters in ggplot2 page.

What does "Content-type: application/json; charset=utf-8" really mean?

I exactly agree with @deceze but I want to develop this "I get an error from the service" part of the question,

We getting this kind of errors as http 415

Http 415 Unsupported Media type error

The HTTP 415 Unsupported Media Type client error response code indicates that the server refuses to accept the request because the payload format is in an unsupported format.

The format problem might be due to the request's indicated Content-Type or Content-Encoding, or as a result of inspecting the data directly.

In other words, such is seen in this example.

  • We have to set the correct content type and we have to accept the right content type as seen Add Content-Type: application/json and Accept: application/json. Otherwise, it will assume the default

javascript onclick increment number

<body>
    <input type="button" value="Increase" id="inc" onclick="incNumber()"/>
    <input type="button" value="Decrease" id="dec" onclick="decNumber()"/>

    <label id="display"></label>

    <script type="text/javascript">

    var i = 0;

    function incNumber() {
        if (i < 10) {
            i++;
        } else if (i = 10) {
            i = 0;
        }
        document.getElementById("display").innerHTML = i;
    }

    function decNumber() {
        if (i > 0) {
            --i;
        } else if (i = 0) {
            i = 10;
        }
        document.getElementById("display").innerHTML = i;
    }
    </script>
</body>

Chrome ignores autocomplete="off"

You can use below concept to implement AutoComplete='false' for chrome as well as others browser.

<input style="opacity: 0; position: absolute; z-index: -1;" name="email">
<input type="search" name="email" class="form-control" autocomplete="new-email" id="email">

LINQ - Full Outer Join

I think there are problems with most of these, including the accepted answer, because they don't work well with Linq over IQueryable either due to doing too many server round trips and too much data returns, or doing too much client execution.

For IEnumerable I don't like Sehe's answer or similar because it has excessive memory use (a simple 10000000 two list test ran Linqpad out of memory on my 32GB machine).

Also, most of the others don't actually implement a proper Full Outer Join because they are using a Union with a Right Join instead of Concat with a Right Anti Semi Join, which not only eliminates the duplicate inner join rows from the result, but any proper duplicates that existed originally in the left or right data.

So here are my extensions that handle all of these issues, generate SQL as well as implementing the join in LINQ to SQL directly, executing on the server, and is faster and with less memory than others on Enumerables:

public static class Ext {
    public static IEnumerable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return from left in leftItems
               join right in rightItems on leftKeySelector(left) equals rightKeySelector(right) into temp
               from right in temp.DefaultIfEmpty()
               select resultSelector(left, right);
    }

    public static IEnumerable<TResult> RightOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return from right in rightItems
               join left in leftItems on rightKeySelector(right) equals leftKeySelector(left) into temp
               from left in temp.DefaultIfEmpty()
               select resultSelector(left, right);
    }

    public static IEnumerable<TResult> FullOuterJoinDistinct<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Union(leftItems.RightOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    public static IEnumerable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector) {

        var hashLK = new HashSet<TKey>(from l in leftItems select leftKeySelector(l));
        return rightItems.Where(r => !hashLK.Contains(rightKeySelector(r))).Select(r => resultSelector(default(TLeft),r));
    }

    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> leftItems,
        IEnumerable<TRight> rightItems,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TResult> resultSelector)  where TLeft : class {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    private static Expression<Func<TP, TC, TResult>> CastSMBody<TP, TC, TResult>(LambdaExpression ex, TP unusedP, TC unusedC, TResult unusedRes) => (Expression<Func<TP, TC, TResult>>)ex;

    public static IQueryable<TResult> LeftOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLR = new { left = default(TLeft), rightg = default(IEnumerable<TRight>) };
        var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
        var parmC = Expression.Parameter(typeof(TRight), "c");
        var argLeft = Expression.PropertyOrField(parmP, "left");
        var newleftrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, parmC), parmP, parmC), sampleAnonLR, default(TRight), default(TResult));

        return leftItems.AsQueryable().GroupJoin(rightItems, leftKeySelector, rightKeySelector, (left, rightg) => new { left, rightg }).SelectMany(r => r.rightg.DefaultIfEmpty(), newleftrs);
    }

    public static IQueryable<TResult> RightOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLR = new { leftg = default(IEnumerable<TLeft>), right = default(TRight) };
        var parmP = Expression.Parameter(sampleAnonLR.GetType(), "p");
        var parmC = Expression.Parameter(typeof(TLeft), "c");
        var argRight = Expression.PropertyOrField(parmP, "right");
        var newrightrs = CastSMBody(Expression.Lambda(Expression.Invoke(resultSelector, parmC, argRight), parmP, parmC), sampleAnonLR, default(TLeft), default(TResult));

        return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).SelectMany(l => l.leftg.DefaultIfEmpty(), newrightrs);
    }

    public static IQueryable<TResult> FullOuterJoinDistinct<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Union(leftItems.RightOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }

    private static Expression<Func<TP, TResult>> CastSBody<TP, TResult>(LambdaExpression ex, TP unusedP, TResult unusedRes) => (Expression<Func<TP, TResult>>)ex;

    public static IQueryable<TResult> RightAntiSemiJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        var sampleAnonLgR = new { leftg = default(IEnumerable<TLeft>), right = default(TRight) };
        var parmLgR = Expression.Parameter(sampleAnonLgR.GetType(), "lgr");
        var argLeft = Expression.Constant(default(TLeft), typeof(TLeft));
        var argRight = Expression.PropertyOrField(parmLgR, "right");
        var newrightrs = CastSBody(Expression.Lambda(Expression.Invoke(resultSelector, argLeft, argRight), parmLgR), sampleAnonLgR, default(TResult));

        return rightItems.GroupJoin(leftItems, rightKeySelector, leftKeySelector, (right, leftg) => new { leftg, right }).Where(lgr => !lgr.leftg.Any()).Select(newrightrs);
    }

    public static IQueryable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IQueryable<TLeft> leftItems,
        IQueryable<TRight> rightItems,
        Expression<Func<TLeft, TKey>> leftKeySelector,
        Expression<Func<TRight, TKey>> rightKeySelector,
        Expression<Func<TLeft, TRight, TResult>> resultSelector) {

        return leftItems.LeftOuterJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector).Concat(leftItems.RightAntiSemiJoin(rightItems, leftKeySelector, rightKeySelector, resultSelector));
    }
}

The difference between a Right Anti-Semi-Join is mostly moot with Linq to Objects or in the source, but makes a difference on the server (SQL) side in the final answer, removing an unnecessary JOIN.

The hand coding of Expression to handle merging an Expression<Func<>> into a lambda could be improved with LinqKit, but it would be nice if the language/compiler had added some help for that. The FullOuterJoinDistinct and RightOuterJoin functions are included for completeness, but I did not re-implement FullOuterGroupJoin yet.

I wrote another version of a full outer join for IEnumerable for cases where the key is orderable, which is about 50% faster than combining the left outer join with the right anti semi join, at least on small collections. It goes through each collection after sorting just once.

I also added another answer for a version that works with EF by replacing the Invoke with a custom expansion.

Difference between map, applymap and apply methods in Pandas

Adding to the other answers, in a Series there are also map and apply.

Apply can make a DataFrame out of a series; however, map will just put a series in every cell of another series, which is probably not what you want.

In [40]: p=pd.Series([1,2,3])
In [41]: p
Out[31]:
0    1
1    2
2    3
dtype: int64

In [42]: p.apply(lambda x: pd.Series([x, x]))
Out[42]: 
   0  1
0  1  1
1  2  2
2  3  3

In [43]: p.map(lambda x: pd.Series([x, x]))
Out[43]: 
0    0    1
1    1
dtype: int64
1    0    2
1    2
dtype: int64
2    0    3
1    3
dtype: int64
dtype: object

Also if I had a function with side effects, such as "connect to a web server", I'd probably use apply just for the sake of clarity.

series.apply(download_file_for_every_element) 

Map can use not only a function, but also a dictionary or another series. Let's say you want to manipulate permutations.

Take

1 2 3 4 5
2 1 4 5 3

The square of this permutation is

1 2 3 4 5
1 2 5 3 4

You can compute it using map. Not sure if self-application is documented, but it works in 0.15.1.

In [39]: p=pd.Series([1,0,3,4,2])

In [40]: p.map(p)
Out[40]: 
0    0
1    1
2    4
3    2
4    3
dtype: int64

How to add bootstrap in angular 6 project?

npm install bootstrap --save

and add relevent files into angular.json file under the style property for css files and under scripts for JS files.

 "styles": [
  "../node_modules/bootstrap/dist/css/bootstrap.min.css",
   ....
]

Eclipse not recognizing JVM 1.8

OK, so I don't really know what the problem was, but I simply fixed it by navigating to here http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html and installing 8u74 instead of 8u73 which is what I was prompted to do when I would go to "download latest version" in Java. So changing the versions is what did it in the end. Eclipse launched fine, now. Thanks for everyone's help!

edit: Apr 2018- Now is 8u161 and 8u162 (Just need one, I used 8u162 and it worked.)

" app-release.apk" how to change this default generated apk name

I wrote more universal solution based on @Fer answer.

It also should work with flavor and build type based configuration of applicationId, versionName, versionCode.

In the build.gradle:

android {
    ...
    applicationVariants.all { variant ->
        variant.outputs.each { output ->
            def appId = variant.applicationId
            def versionName = variant.versionName
            def versionCode = variant.versionCode
            def flavorName = variant.flavorName // e. g. free
            def buildType = variant.buildType // e. g. debug
            def variantName = variant.name // e. g. freeDebug

            def apkName = appId + '_' + variantName + '_' + versionName + '_' + versionCode + '.apk';
            output.outputFile = new File(output.outputFile.parentFile, apkName)
        }
    }
}

Example apk name: com.example.app_freeDebug_1.0_1.apk

For more information about variant variable see ApkVariant and BaseVariant interfaces definition.

Encoding URL query parameters in Java

EDIT: URIUtil is no longer available in more recent versions, better answer at Java - encode URL or by Mr. Sindi in this thread.


URIUtil of Apache httpclient is really useful, although there are some alternatives

URIUtil.encodeQuery(url);

For example, it encodes space as "+" instead of "%20"

Both are perfectly valid in the right context. Although if you really preferred you could issue a string replace.

In DB2 Display a table's definition

db2look -d <db_name> -e -z <schema_name> -t <table_name> -i <user_name> -w <password> > <file_name>.sql

For more information, please refer below:

    db2look [-h]

    -d: Database Name: This must be specified

    -e: Extract DDL file needed to duplicate database
   -xs: Export XSR objects and generate a script containing DDL statements
 -xdir: Path name: the directory in which XSR objects will be placed
    -u: Creator ID: If -u and -a are both not specified then $USER will be used
    -z: Schema name: If -z and -a are both specified then -z will be ignored
    -t: Generate statistics for the specified tables
   -tw: Generate DDLs for tables whose names match the pattern criteria (wildcard characters) of the table name
   -ap: Generate AUDIT USING Statements
  -wlm: Generate WLM specific DDL Statements
  -mod: Generate DDL statements for Module
  -cor: Generate DDL with CREATE OR REPLACE clause
 -wrap: Generates obfuscated versions of DDL statements
    -h: More detailed help message
    -o: Redirects the output to the given file name
    -a: Generate statistics for all creators
    -m: Run the db2look utility in mimic mode
        -c: Do not generate COMMIT statements for mimic
        -r: Do not generate RUNSTATS statements for mimic
    -l: Generate Database Layout: Database partition groups, Bufferpools and Tablespaces
    -x: Generate Authorization statements DDL excluding the original definer of the object
   -xd: Generate Authorization statements DDL including the original definer of the object
    -f: Extract configuration parameters and environment variables
   -td: Specifies x to be statement delimiter (default is semicolon(;))
    -i: User ID to log on to the server where the database resides
    -w: Password to log on to the server where the database resides

add commas to a number in jQuery

Timothy Pirez answer was very correct but if you need to replace the numbers with commas Immediately as user types in textfield, u might want to use the Keyup function.

      $('#textfield').live('keyup', function (event) {
        var value=$('#textfield').val();

      if(event.which >= 37 && event.which <= 40){
          event.preventDefault();
      }
      var newvalue=value.replace(/,/g, '');   
      var valuewithcomma=Number(newvalue).toLocaleString('en');   
      $('#textfield').val(valuewithcomma); 

      });

    <form><input type="text" id="textfield" ></form>

Extend contigency table with proportions (percentages)

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

set.seed(1234)

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

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

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

cbind(my.table, my.prop)

Where is a log file with logs from a container?

To see how much space each container's log is taking up, use this:

docker ps -qa | xargs docker inspect --format='{{.LogPath}}' | xargs ls -hl

(you might need a sudo before ls).

How do I fix "for loop initial declaration used outside C99 mode" GCC error?

For anyone attempting to compile code from an external source that uses an automated build utility such as Make, to avoid having to track down the explicit gcc compilation calls you can set an environment variable. Enter on command prompt or put in .bashrc (or .bash_profile on Mac):

export CFLAGS="-std=c99"

Note that a similar solution applies if you run into a similar scenario with C++ compilation that requires C++ 11, you can use:

export CXXFLAGS="-std=c++11"

How to prompt for user input and read command-line arguments

In Python 2:

data = raw_input('Enter something: ')
print data

In Python 3:

data = input('Enter something: ')
print(data)

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

Update a dataframe in pandas while iterating row by row

Pandas DataFrame object should be thought of as a Series of Series. In other words, you should think of it in terms of columns. The reason why this is important is because when you use pd.DataFrame.iterrows you are iterating through rows as Series. But these are not the Series that the data frame is storing and so they are new Series that are created for you while you iterate. That implies that when you attempt to assign tho them, those edits won't end up reflected in the original data frame.

Ok, now that that is out of the way: What do we do?

Suggestions prior to this post include:

  1. pd.DataFrame.set_value is deprecated as of Pandas version 0.21
  2. pd.DataFrame.ix is deprecated
  3. pd.DataFrame.loc is fine but can work on array indexers and you can do better

My recommendation
Use pd.DataFrame.at

for i in df.index:
    if <something>:
        df.at[i, 'ifor'] = x
    else:
        df.at[i, 'ifor'] = y

You can even change this to:

for i in df.index:
    df.at[i, 'ifor'] = x if <something> else y

Response to comment

and what if I need to use the value of the previous row for the if condition?

for i in range(1, len(df) + 1):
    j = df.columns.get_loc('ifor')
    if <something>:
        df.iat[i - 1, j] = x
    else:
        df.iat[i - 1, j] = y

How can I save an image with PIL?

You should be able to simply let PIL get the filetype from extension, i.e. use:

j.save("C:/Users/User/Desktop/mesh_trans.bmp")

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

This can be caused when upstream rewrites history.

When this happens, I toss all affected repos, clone them fresh from upstream, and use 'git format-patch' / 'git am' to ferry any work in progress from old world to new.

Remove padding or margins from Google Charts

There is this possibility like Aman Virk mentioned:

var options = {
    chartArea:{left:10,top:20,width:"100%",height:"100%"}
};

But keep in mind that the padding and margin aren't there to bother you. If you have the possibility to switch between different types of charts like a ColumnChart and the one with vertical columns then you need some margin for displaying the labels of those lines.

If you take away that margin then you will end up showing only a part of the labels or no labels at all.

So if you just have one chart type then you can change the margin and padding like Arman said. But if it's possible to switch don't change them.

Grep only the first match and stop

My grep-a-like program ack has a -1 option that stops at the first match found anywhere. It supports the -m 1 that @mvp refers to as well. I put it in there because if I'm searching a big tree of source code to find something that I know exists in only one file, it's unnecessary to find it and have to hit Ctrl-C.

Installing MySQL-python

In python3 with virtualenv on a Ubuntu Bionic machine the following commands worked for me:

sudo apt install build-essential python-dev libmysqlclient-dev
sudo apt-get install libssl-dev
pip install mysqlclient

c# regex matches example

Regex regex = new Regex("%download#(\\d+?)%", RegexOptions.SingleLine);
Matches m = regex.Matches(input);

I think will do the trick (not tested).

Android LinearLayout : Add border with shadow around a LinearLayout

As an alternative, you might use a 9 patch image as the background for your layout, allowing for more "natural" shadows:

enter image description here

Result:

enter image description here

Put the image in your /res/drawable folder.
Make sure the file extension is .9.png, not .png

By the way, this is a modified (reduced to the minimum square size) of an existing resource found in the API 19 sdk resources folder.
I left the red markers, since they don't seem to be harmful, as shown in the draw9patch tool.

[EDIT]

About 9 patches, in case you never had anything to do with them.

Simply add it as the background of your View.

The black-marked areas (left and top) will stretch (vertically, horizontally).
The black-marked areas (right, bottom) define the "content area" (where it's possible to add text or Views - you can call the unmarked regions "padding", if you like to).

Tutorial: http://radleymarx.com/blog/simple-guide-to-9-patch/

How to initailize byte array of 100 bytes in java with all 0's

A new byte array will automatically be initialized with all zeroes. You don't have to do anything.

The more general approach to initializing with other values, is to use the Arrays class.

import java.util.Arrays;

byte[] bytes = new byte[100];
Arrays.fill( bytes, (byte) 1 );

How do you make a div follow as you scroll?

A better JQuery answer would be:

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()});
});

You can also add a number after scrollTop i.e .scrollTop() + 5 to give it buff.

A good suggestion would also to limit the duration to 100 and go from default swing to linear easing.

$('#ParentContainer').scroll(function() { 
    $('#FixedDiv').animate({top:$(this).scrollTop()},100,"linear");
})

Switch/toggle div (jQuery)

function toggling_fields_contact_bank(class_name) {
    jQuery("." + class_name).animate({
        height: 'toggle'
    });
}

How to fix Cannot find module 'typescript' in Angular 4?

If you have cloned your project from git or somewhere then first, you should type npm install.

Manually type in a value in a "Select" / Drop-down HTML list?

Telerik also has a combo box control. Essentially, it's a textbox with images that when you click on them reveal a panel with a list of predefined options.

http://demos.telerik.com/aspnet-ajax/combobox/examples/overview/defaultcs.aspx

But this is AJAX, so it may have a larger footprint than you want on your website (since you say it's "HTML").

How to ISO 8601 format a Date with Timezone Offset in JavaScript?

Here are the functions I used for this end:

function localToGMTStingTime(localTime = null) {
    var date = localTime ? new Date(localTime) : new Date();
    return new Date(date.getTime() + (date.getTimezoneOffset() * 60000)).toISOString();
};

function GMTToLocalStingTime(GMTTime = null) {
    var date = GMTTime ? new Date(GMTTime) : new Date();;
    return new Date(date.getTime() - (date.getTimezoneOffset() * 60000)).toISOString();
};

PHP array() to javascript array()

You should need to convert your PHP array to javascript array using PHP syntax json_encode. json_encode convert PHP array to JSON string

Single Dimension PHP array to javascript array

<?php
var $itemsarray= array("Apple", "Bear", "Cat", "Dog");
?>
<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[2]); // Output: Bear
// OR
alert(items[0]); // Output: Apple
</script>

Multi Dimension PHP array to javascript array

<?php
var $itemsarray= array( 
               array('name'='Apple', 'price'=>'12345'),
               array('name'='Bear', 'price'=>'13344'),
               array('name'='Potato', 'price'=>'00440')
             );
?>


<script>
var items= <?php echo json_encode($itemsarray); ?>;
console.log(items[1][name]); // Output: Bear
// OR
alert(items[0][price]); // Output: Apple
</script>

For more detail, you can also check php array to javascript array

How to replace blank (null ) values with 0 for all records?

I just had this same problem, and I ended up finding the simplest solution which works for my needs. In the table properties, I set the default value to 0 for the fields that I don't want to show nulls. Super easy.

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

I got this error when I was trying to write a javascript bookmarklet. I couldn't figure out what was causing it. But eventually I tried URL encoding the bookmarklet, via the following website: http://mrcoles.com/bookmarklet/ and then the error went away, so it must have been a problem with certain characters in the javascript code being interpreted as special URL control characters.

How to fix date format in ASP .NET BoundField (DataFormatString)?

very simple just add this to your bound field DataFormatString="{0: yyyy/MM/dd}"

Why should I use a container div in HTML?

The most common reasons for me are so that:

  1. The layout can have a fixed width (yes, I know, I do a lot of work for designers who love fixed widths), and
  2. So the layout can be centered by applying text-align: center to the body and then margin: auto to the left and right of the container div.

Add SUM of values of two LISTS into new LIST

Default behavior in numpy is add componentwise

import numpy as np
np.add(first, second)

which outputs

array([7,9,11,13,15])

Remove Blank option from Select Option with AngularJS

It is kind of a workaround but works like a charm. Just add <option value="" style="display: none"></option> as a filler. Like in:

<select size="4" ng-model="feed.config" ng-options="template.value as template.name for template in feed.configs">
       <option value="" style="display: none"></option>
</select>

The client and server cannot communicate, because they do not possess a common algorithm - ASP.NET C# IIS TLS 1.0 / 1.1 / 1.2 - Win32Exception

After messing with this for days, my final fix for our issues required two things;

1) We added this line of code to all of our .Net libraries that make out bound api calls to other vendors that had also disabled their SSL v3.

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls; // (.Net 4 and below)

2) This is the final and FULL registry changes you will need when you are running ASP.Net 4.0 sites and will need to be slightly changed after you upgrade to ASP.Net 4.5.

After we rebooted the servers - all problems went away after this.

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"DisabledByDefault"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Client]
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"DisabledByDefault"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 2.0\Server]
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"DisabledByDefault"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Client]
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"DisabledByDefault"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\SSL 3.0\Server]
"Enabled"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.0\Server]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.1\Server]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Client]
"DisabledByDefault"=dword:00000000

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"Enabled"=dword:00000001

[HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\SecurityProviders\SCHANNEL\Protocols\TLS 1.2\Server]
"DisabledByDefault"=dword:00000000

Reading/parsing Excel (xls) files with Python

    with open(csv_filename) as file:
        data = file.read()

    with open(xl_file_name, 'w') as file:
        file.write(data)

You can turn CSV to excel like above with inbuilt packages. CSV can be handled with an inbuilt package of dictreader and dictwriter which will work the same way as python dictionary works. which makes it a ton easy I am currently unaware of any inbuilt packages for excel but I had come across openpyxl. It was also pretty straight forward and simple You can see the code snippet below hope this helps

    import openpyxl
    book = openpyxl.load_workbook(filename)
    sheet = book.active 
    result =sheet['AP2']
    print(result.value)

how to make password textbox value visible when hover an icon

Complete example below. I just love the copy/paste :)

HTML

<div class="container">
    <div class="row">
        <div class="col-md-8 col-md-offset-2">
           <div class="panel panel-default">
              <div class="panel-body">
                  <form class="form-horizontal" method="" action="">

                     <div class="form-group">
                        <label class="col-md-4 control-label">Email</label>
                           <div class="col-md-6">
                               <input type="email" class="form-control" name="email" value="">
                           </div>
                     </div>
                     <div class="form-group">
                       <label class="col-md-4 control-label">Password</label>
                          <div class="col-md-6">
                              <input id="password-field" type="password" class="form-control" name="password" value="secret">
                              <span toggle="#password-field" class="fa fa-lg fa-eye field-icon toggle-password"></span>
                          </div>
                     </div>
                 </form>
              </div>
           </div>
      </div>
  </div>

CSS

.field-icon {
  float: right;
  margin-right: 8px;
  margin-top: -23px;
  position: relative;
  z-index: 2;
  cursor:pointer;
}

.container{
  padding-top:50px;
  margin: auto;
}

JS

$(".toggle-password").click(function() {
   $(this).toggleClass("fa-eye fa-eye-slash");
   var input = $($(this).attr("toggle"));
   if (input.attr("type") == "password") {
     input.attr("type", "text");
   } else {
     input.attr("type", "password");
   }
});

Try it here: https://codepen.io/anon/pen/ZoMQZP

How to check if an alert exists using WebDriver?

The following (C# implementation, but similar in Java) allows you to determine if there is an alert without exceptions and without creating the WebDriverWait object.

boolean isDialogPresent(WebDriver driver) {
    IAlert alert = ExpectedConditions.AlertIsPresent().Invoke(driver);
    return (alert != null);
}

htaccess redirect to https://www

To first force HTTPS, you must check the correct environment variable %{HTTPS} off, but your rule above then prepends the www. Since you have a second rule to enforce www., don't use it in the first rule.

RewriteEngine On
RewriteCond %{HTTPS} off
# First rewrite to HTTPS:
# Don't put www. here. If it is already there it will be included, if not
# the subsequent rule will catch it.
RewriteRule .* https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# Now, rewrite any request to the wrong domain to use www.
# [NC] is a case-insensitive match
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule .* https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]

About proxying

When behind some forms of proxying, whereby the client is connecting via HTTPS to a proxy, load balancer, Passenger application, etc., the %{HTTPS} variable may never be on and cause a rewrite loop. This is because your application is actually receiving plain HTTP traffic even though the client and the proxy/load balancer are using HTTPS. In these cases, check the X-Forwarded-Proto header instead of the %{HTTPS} variable. This answer shows the appropriate process

How can I get the "network" time, (from the "Automatic" setting called "Use network-provided values"), NOT the time on the phone?

Try this snippet of code:

String timeSettings = android.provider.Settings.System.getString(
                this.getContentResolver(),
                android.provider.Settings.System.AUTO_TIME);
        if (timeSettings.contentEquals("0")) {
            android.provider.Settings.System.putString(
                    this.getContentResolver(),
                    android.provider.Settings.System.AUTO_TIME, "1");
        }
        Date now = new Date(System.currentTimeMillis());
        Log.d("Date", now.toString());

Make sure to add permission in Manifest

<uses-permission android:name="android.permission.WRITE_SETTINGS"/>

Switch statement fall-through...should it be allowed?

I don't like my switch statements to fall through - it's far too error prone and hard to read. The only exception is when multiple case statements all do exactly the same thing.

If there is some common code that multiple branches of a switch statement want to use, I extract that into a separate common function that can be called in any branch.

How to reset the state of a Redux store?

UPDATE NGRX4

If you are migrating to NGRX 4, you may have noticed from the migration guide that the rootreducer method for combining your reducers has been replaced with ActionReducerMap method. At first, this new way of doing things might make resetting state a challenge. It is actually straight-forward, yet the way of doing this has changed.

This solution is inspired by the meta-reducers API section of the NGRX4 Github docs.

First, lets say your are combining your reducers like this using NGRX's new ActionReducerMap option:

//index.reducer.ts
export const reducers: ActionReducerMap<State> = {
    auth: fromAuth.reducer,
    layout: fromLayout.reducer,
    users: fromUsers.reducer,
    networks: fromNetworks.reducer,
    routingDisplay: fromRoutingDisplay.reducer,
    routing: fromRouting.reducer,
    routes: fromRoutes.reducer,
    routesFilter: fromRoutesFilter.reducer,
    params: fromParams.reducer
}

Now, lets say you want to reset state from within app.module `

//app.module.ts
import { IndexReducer } from './index.reducer';
import { StoreModule, ActionReducer, MetaReducer } from '@ngrx/store';
...
export function debug(reducer: ActionReducer<any>): ActionReducer<any> {
    return function(state, action) {

      switch (action.type) {
          case fromAuth.LOGOUT:
            console.log("logout action");
            state = undefined;
      }

      return reducer(state, action);
    }
  }

  export const metaReducers: MetaReducer<any>[] = [debug];

  @NgModule({
    imports: [
        ...
        StoreModule.forRoot(reducers, { metaReducers}),
        ...
    ]
})

export class AppModule { }

`

And that is basically one way to achieve the same affect with NGRX 4.

How do I detach objects in Entity Framework Code First?

If you want to detach existing object follow @Slauma's advice. If you want to load objects without tracking changes use:

var data = context.MyEntities.AsNoTracking().Where(...).ToList();

As mentioned in comment this will not completely detach entities. They are still attached and lazy loading works but entities are not tracked. This should be used for example if you want to load entity only to read data and you don't plan to modify them.

Opening PDF String in new window with javascript

Just for information, the below

window.open("data:application/pdf," + encodeURI(pdfString)); 

does not work anymore in Chrome. Yesterday, I came across with the same issue and tried this solution, but did not work (it is 'Not allowed to navigate top frame to data URL'). You cannot open the data URL directly in a new window anymore. But, you can wrap it in iframe and make it open in a new window like below. =)

let pdfWindow = window.open("")
pdfWindow.document.write(
    "<iframe width='100%' height='100%' src='data:application/pdf;base64, " +
    encodeURI(yourDocumentBase64VarHere) + "'></iframe>"
)

Handling a Menu Item Click Event - Android

in addition to the options shown in your question, there is the possibility of implementing the action directly in your xml file from the menu, for example:

<item
   android:id="@+id/OK_MENU_ITEM"
   android:onClick="showMsgDirectMenuXml" />

And for your Java (Activity) file, you need to implement a public method with a single parameter of type MenuItem, for example:

 private void showMsgDirectMenuXml(MenuItem item) {
    Toast toast = Toast.makeText(this, "OK", Toast.LENGTH_LONG);
    toast.show();
  }

NOTE: This method will have behavior similar to the onOptionsItemSelected (MenuItem item)

Rounding Bigdecimal values with 2 Decimal Places

You can call setScale(newScale, roundingMode) method three times with changing the newScale value from 4 to 3 to 2 like

First case

    BigDecimal a = new BigDecimal("10.12345");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1235
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.124
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.12

Second case

    BigDecimal a = new BigDecimal("10.12556");

    a = a.setScale(4, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.1256
    a = a.setScale(3, BigDecimal.ROUND_HALF_UP); 
    System.out.println("" + a); //10.126
    a = a.setScale(2, BigDecimal.ROUND_HALF_UP);
    System.out.println("" + a); //10.13

How to open specific tab of bootstrap nav tabs on click of a particuler link using jQuery?

I wrote this snippet, that I've been using for handling this exact case.

It's in plain javascript, making it also suitable in cases like with bootsrap5 without jQuery.

<script type='text/javascript'>
    window.onhashchange=hashTriggerTab;
    window.onload=hashTriggerTab;
    
    function hashTriggerTab(){
        var current_hash=window.location.hash;
        if(current_hash.substring(0,1)=='#')current_hash=current_hash.substring(1);
        if(current_hash!=''){
            var trigger=document.querySelector('.nav-tabs a[href="#'+current_hash+'"]');
            if(trigger)trigger.click();
        }
    }
</script>

With that in place, you could link both on the same page, like:

<a href='#tabId'>Link Any Tab</a>

Or from external page like:

<a href='newpage.php#tabId'>Link From External</a>

How to get user name using Windows authentication in asp.net?

You can get the user's WindowsIdentity object under Windows Authentication by:

WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;

and then you can get the information about the user like identity.Name.

Please note you need to have HttpContext for these code.

Check if one date is between two dates

Date.parse supports the format mm/dd/yyyy not dd/mm/yyyy. For the latter, either use a library like moment.js or do something as shown below

var dateFrom = "02/05/2013";
var dateTo = "02/09/2013";
var dateCheck = "02/07/2013";

var d1 = dateFrom.split("/");
var d2 = dateTo.split("/");
var c = dateCheck.split("/");

var from = new Date(d1[2], parseInt(d1[1])-1, d1[0]);  // -1 because months are from 0 to 11
var to   = new Date(d2[2], parseInt(d2[1])-1, d2[0]);
var check = new Date(c[2], parseInt(c[1])-1, c[0]);

console.log(check > from && check < to)

PHP mailer multiple address

You need to call the AddAddress method once for every recipient. Like so:

$mail->AddAddress('[email protected]', 'Person One');
$mail->AddAddress('[email protected]', 'Person Two');
// ..

Better yet, add them as Carbon Copy recipients.

$mail->AddCC('[email protected]', 'Person One');
$mail->AddCC('[email protected]', 'Person Two');
// ..

To make things easy, you should loop through an array to do this.

$recipients = array(
   '[email protected]' => 'Person One',
   '[email protected]' => 'Person Two',
   // ..
);
foreach($recipients as $email => $name)
{
   $mail->AddCC($email, $name);
}

Java - Search for files in a directory

This looks like a homework question, so I'll just give you a few pointers:

Try to give good distinctive variable names. Here you used "fileName" first for the directory, and then for the file. That is confusing, and won't help you solve the problem. Use different names for different things.

You're not using Scanner for anything, and it's not needed here, get rid of it.

Furthermore, the accept method should return a boolean value. Right now, you are trying to return a String. Boolean means that it should either return true or false. For example return a > 0; may return true or false, depending on the value of a. But return fileName; will just return the value of fileName, which is a String.

What is the quickest way to HTTP GET in Python?

It's simple enough with the powerful urllib3 library.

Import it like this:

import urllib3

http = urllib3.PoolManager()

And make a request like this:

response = http.request('GET', 'https://example.com')

print(response.data) # Raw data.
print(response.data.decode('utf-8')) # Text.
print(response.status) # Status code.
print(response.headers['Content-Type']) # Content type.

You can add headers too:

response = http.request('GET', 'https://example.com', headers={
    'key1': 'value1',
    'key2': 'value2'
})

More info can be found on the urllib3 documentation.

urllib3 is much safer and easier to use than the builtin urllib.request or http modules and is stable.

Global variables in AngularJS

It's actually pretty easy. (If you're using Angular 2+ anyway.)

Simply add

declare var myGlobalVarName;

Somewhere in the top of your component file (such as after the "import" statements), and you'll be able to access "myGlobalVarName" anywhere inside your component.

curl: (60) SSL certificate problem: unable to get local issuer certificate

Specifically for Windows users, using curl-7.57.0-win64-mingw or similar version.

This is a bit late, and the existing answers are correct. But I still had to struggle a bit to get it working on my Windows machine, though the process is actually pretty straight forward. So, sharing the step-by-step process.

This error basically means, curl is failing to verify the certificate of the target URI. If you trust the issuer of the certificate (CA), you can add that to the list of trusted certificates.

For that, browse the URI (e.g. on Chrome) and follow the steps

  1. Right click on the secure padlock icon
  2. Click on certificate, it'll open a window with the certificate details
  3. Go to 'Certification Path' tab
  4. Click the ROOT certificate
  5. Click View Certificate, it'll open another certificate window
  6. Go to Details tab
  7. Click Copy to File, it'll open the export wizard
  8. Click Next
  9. Select 'Base-64 encoded X.509 (.CER)'
  10. Click Next
  11. Give a friendly name e.g. 'MyDomainX.cer' (browse to desired directory)
  12. Click Next
  13. Click Finish, it'll save the certificate file
  14. Now open this .cer file and copy the contents (including -----BEGIN CERTIFICATE----- and -----END CERTIFICATE-----)
  15. Now go to the directory where curl.exe is saved e.g. C:\SomeFolder\curl-7.57.0-win64-mingw\bin
  16. Open the curl-ca-bundle.crt file with a text editor
  17. Append the copied certificate text to the end of the file. Save

Now your command should execute fine in curl.

How to find if element with specific id exists or not

 var myEle = document.getElementById("myElement");
    if(myEle){
        var myEleValue= myEle.value;
    }

the return of getElementById is null if an element is not actually present inside the dom, so your if statement will fail, because null is considered a false value

Get skin path in Magento?

First note that

Mage::getBaseDir('skin')

returns only path to skin directory of your Magento install (/your/magento/dir/skin).

You can access absolute path to currently used skin directory using:

Mage::getDesign()->getSkinBaseDir()

This method accepts an associative array as optional parameter to modify result.

Following keys are recognized:

  • _area frontend (default) or adminhtml
  • _package your package
  • _theme your theme
  • _relative when this is set (as an key) path relative to Mage::getBaseDir('skin') is returned.

So in your case correct answer would be:

require(Mage::getDesign()->getSkinBaseDir().DS.'myfunc.php');

Google Text-To-Speech API

#! /usr/bin/python2
# -*- coding: utf-8 -*-

def run(cmd):
    import os
    import sys
    from subprocess import Popen, PIPE
    print(cmd)
    proc=Popen(cmd, stdin=None, stdout=PIPE, stderr=None, shell=True)
    while True:
        data = proc.stdout.readline()   # Alternatively proc.stdout.read(1024)
        if len(data) == 0:
            print("Finished process")
            break
        sys.stdout.write(data)

import urllib

msg='Hello preety world'
msg=urllib.quote_plus(msg)
# -v verbosity
cmd='curl '+ \
    '--output tts_responsivevoice.mp2 '+ \
    "\""+'https://code.responsivevoice.org/develop/getvoice.php?t='+msg+'&tl=en-US&sv=g2&vn=&pitch=0.5&rate=0.5&vol=1'+"\""+ \
    ' -H '+"\""+'User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:44.0) Gecko/20100101 Firefox/44.0'+"\""+ \
    ' -H '+"\""+'Accept: audio/webm,audio/ogg,audio/wav,audio/*;q=0.9,application/ogg;q=0.7,video/*;q=0.6,*/*;q=0.5'+"\""+ \
    ' -H '+"\""+'Accept-Language: pl,en-US;q=0.7,en;q=0.3'+"\""+ \
    ' -H '+"\""+'Range: bytes=0-'+"\""+ \
    ' -H '+"\""+'Referer: http://code.responsivevoice.org/develop/examples/example2.html'+"\""+ \
    ' -H '+"\""+'Cookie: __cfduid=ac862i73b6a61bf50b66713fdb4d9f62c1454856476; _ga=GA1.2.2126195996.1454856480; _gat=1'+"\""+ \
    ' -H '+"\""+'Connection: keep-alive'+"\""+ \
    ''
print('***************************')
print(cmd)
print('***************************')
run(cmd)

Line:

/getvoice.php?t='+msg+'&tl=en-US&sv=g2&vn=&pitch=0.5&rate=0.5&vol=1'+"\""+ \

is responsible for language.

tl=en-US

There is another preety interesting site with tts engines that can be used in this manner.

substitute o for null iv0na.c0m

have a nice day

HTML5 Canvas Rotate Image

@Steve Farthing's answer is absolutely right.

But if you rotate more than 4 times then the image will get cropped from both the side. For that you need to do like this.

$("#clockwise").click(function(){ 
    angleInDegrees+=90 % 360;
    drawRotated(angleInDegrees);
    if(angleInDegrees == 360){  // add this lines
        angleInDegrees = 0
    }
});

Then you will get the desired result. Thanks. Hope this will help someone :)

How to unstage large number of files without deleting the content

git reset

If all you want is to undo an overzealous "git add" run:

git reset

Your changes will be unstaged and ready for you to re-add as you please.


DO NOT RUN git reset --hard.

It will not only unstage your added files, but will revert any changes you made in your working directory. If you created any new files in working directory, it will not delete them though.

How to add parameters to HttpURLConnection using POST using NameValuePair

There's a much easier approach using PrintWriter (see here)

Basically all you need is:

// set up URL connection
URL urlToRequest = new URL(urlStr);
HttpURLConnection urlConnection = (HttpURLConnection)urlToRequest.openConnection();
urlConnection.setDoOutput(true);
urlConnection.setRequestMethod("POST");
urlConnection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

// write out form parameters
String postParamaters = "param1=value1&param2=value2"
urlConnection.setFixedLengthStreamingMode(postParameters.getBytes().length);
PrintWriter out = new PrintWriter(urlConnection.getOutputStream());
out.print(postParameters);
out.close();

// connect
urlConnection.connect();

How to parse Excel (XLS) file in Javascript/HTML5

include the xslx.js , xlsx.full.min.js , jszip.js

add a onchange event handler to the file input

function showDataExcel(event)
{
            var file = event.target.files[0];
            var reader = new FileReader();
            var excelData = [];
            reader.onload = function (event) {
                var data = event.target.result;
                var workbook = XLSX.read(data, {
                    type: 'binary'
                });

                workbook.SheetNames.forEach(function (sheetName) {
                    // Here is your object
                    var XL_row_object = XLSX.utils.sheet_to_row_object_array(workbook.Sheets[sheetName]);

                    for (var i = 0; i < XL_row_object.length; i++)
                    {
                        excelData.push(XL_row_object[i]["your column name"]);

                    }

                    var json_object = JSON.stringify(XL_row_object);
                    console.log(json_object);
                    alert(excelData);
                })

            };

            reader.onerror = function (ex) {
                console.log(ex);
            };

            reader.readAsBinaryString(file);

}

How to show and update echo on same line

I use printf, is shorter as it doesn't need flags to do the work:

printf "\rMy static $myvars composed text"

How do I generate sourcemaps when using babel and webpack?

If optimizing for dev + production, you could try something like this in your config:

const dev = process.env.NODE_ENV !== 'production'

// in config

{
  devtool: dev ? 'eval-cheap-module-source-map' : 'source-map',
}

From the docs:

  • devtool: "eval-cheap-module-source-map" offers SourceMaps that only maps lines (no column mappings) and are much faster
  • devtool: "source-map" cannot cache SourceMaps for modules and need to regenerate complete SourceMap for the chunk. It’s something for production.

I am using webpack 2.1.0-beta.19

Chrome Dev Tools - Modify javascript and reload

The Resource Override extension allows you to do exactly that:

  • create a file rule for the url you want to replace
  • edit the js/css/etc in the extension
  • reload as often as you want :)

Can I write into the console in a unit test? If yes, why doesn't the console window open?

Someone commented about this apparently new functionality in Visual Studio 2013. I wasn't sure what he meant at first, but now that I do, I think it deserves its own answer.

We can use Console.WriteLine normally and the output is displayed, just not in the Output window, but in a new window after we click "Output" in the test details.

Enter image description here

Insert Picture into SQL Server 2005 Image Field using only SQL

For updating a record:

 UPDATE Employees SET [Photo] = (SELECT
 MyImage.* from Openrowset(Bulk
 'C:\photo.bmp', Single_Blob) MyImage)
 where Id = 10

Notes:

  • Make sure to add the 'BULKADMIN' Role Permissions for the login you are using.
  • Paths are not pointing to your computer when using SQL Server Management Studio. If you start SSMS on your local machine and connect to a SQL Server instance on server X, the file C:\photo.bmp will point to hard drive C: on server X, not your machine!

Div 100% height works on Firefox but not in IE

I don't think IE supports the use of auto for setting height / width, so you could try giving this a numeric value (like Jarett suggests).

Also, it doesn't look like you are clearing your floats properly. Try adding this to your CSS for #container:

#container {
    height:100%;
    width:100%;
    overflow:hidden;
    /* for IE */
    zoom:1;
}

How do I call a function twice or more times consecutively?

You can use itertools.repeat with operator.methodcaller to call the __call__ method of the function N times. Here is an example of a generator function doing it:

from itertools import repeat
from operator import methodcaller


def call_n_times(function, n):
    yield from map(methodcaller('__call__'), repeat(function, n))

Example of usage:

import random
from functools import partial

throw_dice = partial(random.randint, 1, 6)
result = call_n_times(throw_dice, 10)
print(list(result))
# [6, 3, 1, 2, 4, 6, 4, 1, 4, 6]

Getting session value in javascript

If you are using VB as code behind, you have to use bracket "()" instead of square bracket "[]".

Example for VB:

<script type="text/javascript">
var accesslevel = '<%= Session("accesslevel").ToString().ToLower() %>';
</script>  

Regular expression to match URLs in Java

I'll try a standard "Why are you doing it this way?" answer... Do you know about java.net.URL?

URL url = new URL(stringURL);

The above will throw a MalformedURLException if it can't parse the URL.

load scripts asynchronously

You can use LABJS or RequreJS

Script loaders like LABJS, RequireJS will improve the speed and quality of your code.

How can I detect when an Android application is running in the emulator?

I tried several techniques, but settled on a slightly revised version of checking the Build.PRODUCT as below. This seems to vary quite a bit from emulator to emulator, that's why I have the 3 checks I currently have. I guess I could have just checked if product.contains("sdk") but thought the check below was a bit safer.

public static boolean isAndroidEmulator() {
    String model = Build.MODEL;
    Log.d(TAG, "model=" + model);
    String product = Build.PRODUCT;
    Log.d(TAG, "product=" + product);
    boolean isEmulator = false;
    if (product != null) {
        isEmulator = product.equals("sdk") || product.contains("_sdk") || product.contains("sdk_");
    }
    Log.d(TAG, "isEmulator=" + isEmulator);
    return isEmulator;
}

FYI - I found that my Kindle Fire had Build.BRAND = "generic", and some of the emulators didn't have "Android" for the network operator.

How can I simulate a click to an anchor tag?

None of the above solutions address the generic intention of the original request. What if we don't know the id of the anchor? What if it doesn't have an id? What if it doesn't even have an href parameter (e.g. prev/next icon in a carousel)? What if we want to apply the action to multiple anchors with different models in an agnostic fashion? Here's an example that does something instead of a click, then later simulates the click (for any anchor or other tag):

var clicker = null;
$('a').click(function(e){ 
    clicker=$(this); // capture the clicked dom object
    /* ... do something ... */
    e.preventDefault(); // prevent original click action
});
clicker[0].click(); // this repeats the original click. [0] is necessary.

Dropping a connected user from an Oracle 10g database schema

just use SQL :

disconnect; 

conn tiger/scott as sysdba;

Twitter Bootstrap Button Text Word Wrap

Try this: add white-space: normal; to the style definition of the Bootstrap Button or you can replace the code you displayed with the one below

<div class="col-lg-3"> <!-- FIRST COL -->
  <div class="panel panel-default">
    <div class="panel-body"> 
    <h4>Posted on</h4>
    <p>22nd September 2013</p>
    <h4>Tags</h4>
    <a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
   <a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
   <a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
           </div>
  </div>
</div>

I have updated your fiddle here to show how it comes out.

How to obtain the number of CPUs/cores in Linux from the command line?

Crossplatform solution for Linux, MacOS, Windows:

CORES=$(grep -c ^processor /proc/cpuinfo 2>/dev/null || sysctl -n hw.ncpu || echo "$NUMBER_OF_PROCESSORS")

How do I close an Android alertdialog

final AlertDialog.Builder alert = new AlertDialog.Builder(mcontext);
alert.setTitle(title);
alert.setMessage(description);
alert.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
  @Override                                 
  public void onClick(DialogInterface dialog,int which) {
        cancelDialog(); //Implement method for canceling dialog
         }
   });
alert.show();
void cancelDialog()
{
   //Now you can either use  
   dialog.cancel();
    //or dialog.dismiss();
}

Python: How to pip install opencv2 with specific version 2.4.9?

python3.6 -m pip install opencv-python

will install cv2 in linux in branch python3.6

java.net.SocketException: Connection reset by peer: socket write error When serving a file

I face this problem but resolution is very simple. I am writing the 1 MB file in 1024 Byte Buffer causing this issue. To Understand refer code before and After Fix.

Code with Excepion

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[1024];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }
    

After Fixes:

DataOutputStream dos = new DataOutputStream(s.getOutputStream());
        FileInputStream fis = new FileInputStream(file);
        byte[] buffer = new byte[102400];
        
        while (fis.read(buffer) > 0) {
            dos.write(buffer);
        }

    

How to load external webpage in WebView

try this

webviewlayout.xml:

<?xml version="1.0" encoding="utf-8"?>
<WebView xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/help_webview"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:scrollbars="none"
/>

In your Activity:

WebView webView;
setContentView(R.layout.webviewlayout);
webView = (WebView)findViewById(R.id.help_webview);
webView.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://www.google.com");

Update

Add webView.setWebViewClient(new WebViewController()); to your Activity.

WebViewController class:

public class WebViewController extends WebViewClient {

    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        view.loadUrl(url);
        return true;
    }
}

python: after installing anaconda, how to import pandas

You can only import a library which has been installed in your environment.

If you have created a new environment, e.g. to run an older version of Python, maybe you lack 'pandas' package, which is in the 'base' environment of Anaconda by default.

Fix through GUI

To add it to your environment, from the GUI, select your environment, select "All" in the dropdown list, type pandas in the text field, select the pandas package and Apply.

Afterwards, select 'Installed' to verify that the package has been correctly installed.

CLEAR SCREEN - Oracle SQL Developer shortcut?

If you're using sqlplus in a shell, like bash you can run the shell's clear command from sqlplus:

SQL> host clear

you can abbreviate of course:

SQL> ho clear

.aspx vs .ashx MAIN difference

.aspx uses a full lifecycle (Init, Load, PreRender) and can respond to button clicks etc.
An .ashx has just a single ProcessRequest method.

removing html element styles via javascript

getElementById("id").removeAttribute("style");

if you are using jQuery then

$("#id").removeClass("classname");

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - process out of memory

Anyone getting this error with Azure build pipelines, try the below step to change environment variable of build agent

Add an Azure build pipeline task -> Azure powershell script:Inlinescript before Compile with below settings

- task: AzurePowerShell@3
  displayName: 'Azure PowerShell script: InlineScript'
  inputs:
    azureSubscription: 'NYCSCA Azure Dev/Test (ea91a274-55c6-461c-a11d-758ef02c2698)'
    ScriptType: InlineScript
    Inline: '[Environment]::SetEnvironmentVariable("NODE_OPTIONS", "--max_old_space_size=16384", "Machine")'
    FailOnStandardError: true
    azurePowerShellVersion: LatestVersion

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

You can use case in update and SWAP as many as you want

update Table SET column=(case when is_row_1 then value_2 else value_1 end) where rule_to_match_swap_columns

Cleaning `Inf` values from an R dataframe

Here is a dplyr/tidyverse solution using the na_if() function:

dat %>% mutate_if(is.numeric, list(~na_if(., Inf)))

Note that this only replaces positive infinity with NA. Need to repeat if negative infinity values also need to be replaced.

dat %>% mutate_if(is.numeric, list(~na_if(., Inf))) %>% 
  mutate_if(is.numeric, list(~na_if(., -Inf)))

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

If you do not have to sign the app, right click on your project

Project Properties -> Signing -> uncheck "Sign the ClickOnce Manifest"

Also as this MS article suggests,

If you are using Visual Studio 2008 and are targeting .NET 3.5 and using automatic updates, you can just change the certificate and deploy a new version,

find difference between two text files with one item per line

grep -Fxvf file1 file2

What the flags mean:

-F, --fixed-strings
              Interpret PATTERN as a list of fixed strings, separated by newlines, any of which is to be matched.    
-x, --line-regexp
              Select only those matches that exactly match the whole line.
-v, --invert-match
              Invert the sense of matching, to select non-matching lines.
-f FILE, --file=FILE
              Obtain patterns from FILE, one per line.  The empty file contains zero patterns, and therefore matches nothing.

how to move elasticsearch data from one server to another

The selected answer makes it sound slightly more complex than it is, the following is what you need (install npm first on your system).

npm install -g elasticdump
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=mapping
elasticdump --input=http://mysrc.com:9200/my_index --output=http://mydest.com:9200/my_index --type=data

You can skip the first elasticdump command for subsequent copies if the mappings remain constant.

I have just done a migration from AWS to Qbox.io with the above without any problems.

More details over at:

https://www.npmjs.com/package/elasticdump

Help page (as of Feb 2016) included for completeness:

elasticdump: Import and export tools for elasticsearch

Usage: elasticdump --input SOURCE --output DESTINATION [OPTIONS]

--input
                    Source location (required)
--input-index
                    Source index and type
                    (default: all, example: index/type)
--output
                    Destination location (required)
--output-index
                    Destination index and type
                    (default: all, example: index/type)
--limit
                    How many objects to move in bulk per operation
                    limit is approximate for file streams
                    (default: 100)
--debug
                    Display the elasticsearch commands being used
                    (default: false)
--type
                    What are we exporting?
                    (default: data, options: [data, mapping])
--delete
                    Delete documents one-by-one from the input as they are
                    moved.  Will not delete the source index
                    (default: false)
--searchBody
                    Preform a partial extract based on search results
                    (when ES is the input,
                    (default: '{"query": { "match_all": {} } }'))
--sourceOnly
                    Output only the json contained within the document _source
                    Normal: {"_index":"","_type":"","_id":"", "_source":{SOURCE}}
                    sourceOnly: {SOURCE}
                    (default: false)
--all
                    Load/store documents from ALL indexes
                    (default: false)
--bulk
                    Leverage elasticsearch Bulk API when writing documents
                    (default: false)
--ignore-errors
                    Will continue the read/write loop on write error
                    (default: false)
--scrollTime
                    Time the nodes will hold the requested search in order.
                    (default: 10m)
--maxSockets
                    How many simultaneous HTTP requests can we process make?
                    (default:
                      5 [node <= v0.10.x] /
                      Infinity [node >= v0.11.x] )
--bulk-mode
                    The mode can be index, delete or update.
                    'index': Add or replace documents on the destination index.
                    'delete': Delete documents on destination index.
                    'update': Use 'doc_as_upsert' option with bulk update API to do partial update.
                    (default: index)
--bulk-use-output-index-name
                    Force use of destination index name (the actual output URL)
                    as destination while bulk writing to ES. Allows
                    leveraging Bulk API copying data inside the same
                    elasticsearch instance.
                    (default: false)
--timeout
                    Integer containing the number of milliseconds to wait for
                    a request to respond before aborting the request. Passed
                    directly to the request library. If used in bulk writing,
                    it will result in the entire batch not being written.
                    Mostly used when you don't care too much if you lose some
                    data when importing but rather have speed.
--skip
                    Integer containing the number of rows you wish to skip
                    ahead from the input transport.  When importing a large
                    index, things can go wrong, be it connectivity, crashes,
                    someone forgetting to `screen`, etc.  This allows you
                    to start the dump again from the last known line written
                    (as logged by the `offset` in the output).  Please be
                    advised that since no sorting is specified when the
                    dump is initially created, there's no real way to
                    guarantee that the skipped rows have already been
                    written/parsed.  This is more of an option for when
                    you want to get most data as possible in the index
                    without concern for losing some rows in the process,
                    similar to the `timeout` option.
--inputTransport
                    Provide a custom js file to us as the input transport
--outputTransport
                    Provide a custom js file to us as the output transport
--toLog
                    When using a custom outputTransport, should log lines
                    be appended to the output stream?
                    (default: true, except for `$`)
--help
                    This page

Examples:

# Copy an index from production to staging with mappings:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=http://staging.es.com:9200/my_index \
  --type=data

# Backup index data to a file:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=/data/my_index_mapping.json \
  --type=mapping
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=/data/my_index.json \
  --type=data

# Backup and index to a gzip using stdout:
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=$ \
  | gzip > /data/my_index.json.gz

# Backup ALL indices, then use Bulk API to populate another ES cluster:
elasticdump \
  --all=true \
  --input=http://production-a.es.com:9200/ \
  --output=/data/production.json
elasticdump \
  --bulk=true \
  --input=/data/production.json \
  --output=http://production-b.es.com:9200/

# Backup the results of a query to a file
elasticdump \
  --input=http://production.es.com:9200/my_index \
  --output=query.json \
  --searchBody '{"query":{"term":{"username": "admin"}}}'

------------------------------------------------------------------------------
Learn more @ https://github.com/taskrabbit/elasticsearch-dump`enter code here`

Converting a year from 4 digit to 2 digit and back again in C#

The answer is quite simple:

DateTime Today = DateTime.Today;
string zeroBased = Today.ToString("yy-MM-dd");

How do I raise the same Exception with a custom message in Python?

Update: For Python 3, check Ben's answer


To attach a message to the current exception and re-raise it: (the outer try/except is just to show the effect)

For python 2.x where x>=6:

try:
    try:
      raise ValueError  # something bad...
    except ValueError as err:
      err.message=err.message+" hello"
      raise              # re-raise current exception
except ValueError as e:
    print(" got error of type "+ str(type(e))+" with message " +e.message)

This will also do the right thing if err is derived from ValueError. For example UnicodeDecodeError.

Note that you can add whatever you like to err. For example err.problematic_array=[1,2,3].


Edit: @Ducan points in a comment the above does not work with python 3 since .message is not a member of ValueError. Instead you could use this (valid python 2.6 or later or 3.x):

try:
    try:
      raise ValueError
    except ValueError as err:
       if not err.args: 
           err.args=('',)
       err.args = err.args + ("hello",)
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e.args))

Edit2:

Depending on what the purpose is, you can also opt for adding the extra information under your own variable name. For both python2 and python3:

try:
    try:
      raise ValueError
    except ValueError as err:
       err.extra_info = "hello"
       raise 
except ValueError as e:
    print(" error was "+ str(type(e))+str(e))
    if 'extra_info' in dir(e):
       print e.extra_info

Server certificate verification failed: issuer is not trusted

The other answers don't work for me. I'm trying to get the command line working in Jenkins. All you need are the following command line arguments:

--non-interactive

--trust-server-cert

How to modify the nodejs request default timeout time?

Try this:

var options = {
    url:  'http://url',
    timeout: 120000
}

request(options, function(err, resp, body) {});

Refer to request's documentation for other options.

How to access component methods from “outside” in ReactJS?

Alternatively, if the method on Child is truly static (not a product of current props, state) you can define it on statics and then access it as you would a static class method. For example:

var Child = React.createClass({
  statics: {
    someMethod: function() {
      return 'bar';
    }
  },
  // ...
});

console.log(Child.someMethod()) // bar

How to keep environment variables when using sudo

For individual variables you want to make available on a one off basis you can make it part of the command.

sudo http_proxy=$http_proxy wget "http://stackoverflow.com"

Error 1022 - Can't write; duplicate key in table

I had this problem when creating a new table. It turns out the Foreign Key name I gave was already in use. Renaming the key fixed it.

Is there any advantage of using map over unordered_map in case of trivial keys?

Reasons have been given in other answers; here is another.

std::map (balanced binary tree) operations are amortized O(log n) and worst case O(log n). std::unordered_map (hash table) operations are amortized O(1) and worst case O(n).

How this plays out in practice is that the hash table "hiccups" every once in a while with an O(n) operation, which may or may not be something your application can tolerate. If it can't tolerate it, you'd prefer std::map over std::unordered_map.

How can I pass a Bitmap object from one activity to another

Passsing bitmap as parceable in bundle between activity is not a good idea because of size limitation of Parceable(1mb). You can store the bitmap in a file in internal storage and retrieve the stored bitmap in several activities. Here's some sample code.

To store bitmap in a file myImage in internal storage:

public String createImageFromBitmap(Bitmap bitmap) {
    String fileName = "myImage";//no .png or .jpg needed
    try {
        ByteArrayOutputStream bytes = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
        FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
        fo.write(bytes.toByteArray());
        // remember close file output
        fo.close();
    } catch (Exception e) {
        e.printStackTrace();
        fileName = null;
    }
    return fileName;
}

Then in the next activity you can decode this file myImage to a bitmap using following code:

//here context can be anything like getActivity() for fragment, this or MainActivity.this
Bitmap bitmap = BitmapFactory.decodeStream(context.openFileInput("myImage"));

Note A lot of checking for null and scaling bitmap's is ommited.

Handling NULL values in Hive

To check for the NULL data for column1 and consider your datatype of it is String, you could use below command :

select * from tbl_name where column1 is null or column1 <> '';

Use table name in MySQL SELECT "AS"

To declare a string literal as an output column, leave the Table off and just use Test. It doesn't need to be associated with a table among your joins, since it will be accessed only by its column alias. When using a metadata function like getColumnMeta(), the table name will be an empty string because it isn't associated with a table.

SELECT
  `field1`, 
  `field2`, 
  'Test' AS `field3` 
FROM `Test`;

Note: I'm using single quotes above. MySQL is usually configured to honor double quotes for strings, but single quotes are more widely portable among RDBMS.

If you must have a table alias name with the literal value, you need to wrap it in a subquery with the same name as the table you want to use:

SELECT
  field1,
  field2,
  field3
FROM 
  /* subquery wraps all fields to put the literal inside a table */
  (SELECT field1, field2, 'Test' AS field3 FROM Test) AS Test

Now field3 will come in the output as Test.field3.

SSIS Convert Between Unicode and Non-Unicode Error

On the above example I kept losing the values, I think that delaying the Validation will allow the new data types to be saved as part of the meta data.

On the connection Manager for 'Excel Connection Manager' set the Delay Validation to False from the Properties.

Then on the data flow Destination task for Excel set the ValidationExternalMetaData to False, again from the properties.

This will now allow you to right click on the Excel Destination Task and go to Advanced Editor for Excel Destination --> far right tab - Input and Output Properties. In the External Columns folder section you will be able to now change the Data Types and Length values of the problematic columns and this can now be saved.

Good Luck!

resource error in android studio after update: No Resource Found

Attention, wrong answer coming! But anyone without apache libraries or so might find

compileSdkVersion 23
buildToolsVersion "23.0.0"



//...


dependencies {
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'com.android.support:design:23.0.0'    

}

helpful, it did the trick for me.

What is a regular expression which will match a valid domain name without a subdomain?

^[a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,7}$

[domain - lower case letters and 0-9 only] [can have a hyphen] + [TLD - lower case only, must be beween 2 and 7 letters long]
http://rubular.com/ is brilliant for testing regular expressions!
Edit: Updated TLD maximum to 7 characters for '.rentals' as Dan Caddigan pointed out.

How to use PrintWriter and File classes in Java?

Double click the file.txt, then save it, command + s, that worked in my case. Also, make sure the file.txt is saved in the project folder. If that does not work.

PrintWriter pw = new PrintWriter(new File("file.txt"));
pw.println("hello world"); // to test if it works.

How do I find numeric columns in Pandas?

You can use the undocumented function _get_numeric_data() to filter only numeric columns:

df._get_numeric_data()

Example:

In [32]: data
Out[32]:
   A  B
0  1  s
1  2  s
2  3  s
3  4  s

In [33]: data._get_numeric_data()
Out[33]:
   A
0  1
1  2
2  3
3  4

Note that this is a "private method" (i.e., an implementation detail) and is subject to change or total removal in the future. Use with caution.

How to request a random row in SQL?

In SQL Server you can combine TABLESAMPLE with NEWID() to get pretty good randomness and still have speed. This is especially useful if you really only want 1, or a small number, of rows.

SELECT TOP 1 * FROM [table] 
TABLESAMPLE (500 ROWS) 
ORDER BY NEWID()

Show DataFrame as table in iPython Notebook

In order to show the DataFrame in Jupyter Notebook just type:

   display(Name_of_the_DataFrame)

for example:

  display(df)

How to get detailed list of connections to database in sql server 2005?

sp_who2 will actually provide a list of connections for the database server, not a database. To view connections for a single database (YourDatabaseName in this example), you can use

DECLARE @AllConnections TABLE(
    SPID INT,
    Status VARCHAR(MAX),
    LOGIN VARCHAR(MAX),
    HostName VARCHAR(MAX),
    BlkBy VARCHAR(MAX),
    DBName VARCHAR(MAX),
    Command VARCHAR(MAX),
    CPUTime INT,
    DiskIO INT,
    LastBatch VARCHAR(MAX),
    ProgramName VARCHAR(MAX),
    SPID_1 INT,
    REQUESTID INT
)

INSERT INTO @AllConnections EXEC sp_who2

SELECT * FROM @AllConnections WHERE DBName = 'YourDatabaseName'

(Adapted from SQL Server: Filter output of sp_who2.)

Access Session attribute on jstl

You don't need the jsp:useBean to set the model if you already have a controller which prepared the model.

Just access it plain by EL:

<p>${Questions.questionPaperID}</p>
<p>${Questions.question}</p>

or by JSTL <c:out> tag if you'd like to HTML-escape the values or when you're still working on legacy Servlet 2.3 containers or older when EL wasn't supported in template text yet:

<p><c:out value="${Questions.questionPaperID}" /></p>
<p><c:out value="${Questions.question}" /></p>

See also:


Unrelated to the problem, the normal practice is by the way to start attribute name with a lowercase, like you do with normal variable names.

session.setAttribute("questions", questions);

and alter EL accordingly to use ${questions}.

Also note that you don't have any JSTL tag in your code. It's all plain JSP.

Properly close mongoose's connection once you're done

I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient to the options and putting it into a variable that you call close on seemed to work.

var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })

//do stuff

db.close()

bash: npm: command not found?

I also come here for the same problem, The solution I found is to install npm and then restart the Visual Studio Code

How to enable core dump in my Linux C++ program

You need to set ulimit -c. If you have 0 for this parameter a coredump file is not created. So do this: ulimit -c unlimited and check if everything is correct ulimit -a. The coredump file is created when an application has done for example something inappropriate. The name of the file on my system is core.<process-pid-here>.

How to include NA in ifelse?

@AnandaMahto has addressed why you're getting these results and provided the clearest way to get what you want. But another option would be to use identical instead of ==.

test$ID <- ifelse(is.na(test$time) | sapply(as.character(test$type), identical, "A"), NA, "1")

Or use isTRUE:

test$ID <- ifelse(is.na(test$time) | Vectorize(isTRUE)(test$type == "A"), NA, "1")

How do I find the maximum of 2 numbers?

You can use max(value, run)

The function max takes any number of arguments, or (alternatively) an iterable, and returns the maximum value.

Force IE9 to emulate IE8. Possible?

Yes. Recent versions of IE (IE8 or above) let you adjust that. Here's how:

  • Fire up Internet Explorer.
  • Click the 'Tools' menu, then click 'Developer Tools'. Alternatively, just press F12.

That should open the Developer Tools window. That window has two menu items that are of interest:

  • Browser Mode. This setting determines the value of the user-agent header sent for every request.
  • Document Mode. This setting determines how the rendering engine renders the page.

More at http://blogs.msdn.com/b/ie/archive/2010/06/16/ie-s-compatibility-features-for-site-developers.aspx

How do I add a newline to command output in PowerShell?

The option that I tend to use, mostly because it's simple and I don't have to think, is using Write-Output as below. Write-Output will put an EOL marker in the string for you and you can simply output the finished string.

Write-Output $stringThatNeedsEOLMarker | Out-File -FilePath PathToFile -Append

Alternatively, you could also just build the entire string using Write-Output and then push the finished string into Out-File.

Storing data into list with class

You need to add an instance of the class:

lstemail.Add(new EmailData { FirstName = "John", LastName = "Smith", Location = "Los Angeles"});

I would recommend adding a constructor to your class, however:

public class EmailData
{
    public EmailData(string firstName, string lastName, string location)
    {
        this.FirstName = firstName;
        this.LastName = lastName;
        this.Location = location;
    }
    public string FirstName{ set; get; }
    public string LastName { set; get; }
    public string Location{ set; get; }
}

This would allow you to write the addition to your list using the constructor:

lstemail.Add(new EmailData("John", "Smith", "Los Angeles"));

How can I add a space in between two outputs?

Like this?

 System.out.println(Name + " " + Income);

Where to find "Microsoft.VisualStudio.TestTools.UnitTesting" missing dll?

You have to add reference to

Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll 

It can be found at C:\Program Files\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies\ directory (for VS2010 professional or above; .NET Framework 4.0).

or right click on your project and select: Add Reference... > .NET: or click Add Reference... > .NET:

Difference between exit() and sys.exit() in Python

If I use exit() in a code and run it in the shell, it shows a message asking whether I want to kill the program or not. It's really disturbing. See here

But sys.exit() is better in this case. It closes the program and doesn't create any dialogue box.

CMake unable to determine linker language with C++

In my case, it was just because there were no source file in the target. All of my library was template with source code in the header. Adding an empty file.cpp solved the problem.

How can I find out what FOREIGN KEY constraint references a table in SQL Server?

You could use this query to display Foreign key constaraints:

SELECT
K_Table = FK.TABLE_NAME,
FK_Column = CU.COLUMN_NAME,
PK_Table = PK.TABLE_NAME,
PK_Column = PT.COLUMN_NAME,
Constraint_Name = C.CONSTRAINT_NAME
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS C
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS FK ON C.CONSTRAINT_NAME = FK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.TABLE_CONSTRAINTS PK ON C.UNIQUE_CONSTRAINT_NAME = PK.CONSTRAINT_NAME
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE CU ON C.CONSTRAINT_NAME = CU.CONSTRAINT_NAME
INNER JOIN (
SELECT i1.TABLE_NAME, i2.COLUMN_NAME
FROM INFORMATION_SCHEMA.TABLE_CONSTRAINTS i1
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE i2 ON i1.CONSTRAINT_NAME = i2.CONSTRAINT_NAME
WHERE i1.CONSTRAINT_TYPE = 'PRIMARY KEY'
) PT ON PT.TABLE_NAME = PK.TABLE_NAME
---- optional:
ORDER BY
1,2,3,4
WHERE PK.TABLE_NAME='YourTable'

Taken from http://blog.sqlauthority.com/2006/11/01/sql-server-query-to-display-foreign-key-relationships-and-name-of-the-constraint-for-each-table-in-database/

How much RAM is SQL Server actually using?

  1. Start -> Run -> perfmon
  2. Look at the zillions of counters that SQL Server installs

Which is a better way to check if an array has more than one element?

The first method if (isset($arr['1'])) will not work on an associative array.

For example, the following code displays "Nope, not more than one."

$arr = array(
    'a' => 'apple',
    'b' => 'banana',
);

if (isset($arr['1'])) {
    echo "Yup, more than one.";
} else {
    echo "Nope, not more than one.";
}

Editing the git commit message in GitHub

No, because the commit message is related with the commit SHA / hash, and if we change it the commit SHA is also changed. The way I used is to create a comment on that commit. I can't think the other way.

How to justify a single flexbox item (override justify-content)

If you aren't actually restricted to keeping all of these elements as sibling nodes you can wrap the ones that go together in another default flex box, and have the container of both use space-between.

_x000D_
_x000D_
.space-between {_x000D_
  border: 1px solid red;_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
}_x000D_
.default-flex {_x000D_
  border: 1px solid blue;_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  border: 1px solid;_x000D_
}
_x000D_
<div class="space-between">_x000D_
  <div class="child">1</div>_x000D_
  <div class="default-flex">_x000D_
    <div class="child">2</div>_x000D_
    <div class="child">3</div>_x000D_
    <div class="child">4</div>_x000D_
    <div class="child">5</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or if you were doing the same thing with flex-start and flex-end reversed you just swap the order of the default-flex container and lone child.

Printing tuple with string formatting in Python

This doesn't use string formatting, but you should be able to do:

print 'this is a tuple ', (1, 2, 3)

If you really want to use string formatting:

print 'this is a tuple %s' % str((1, 2, 3))
# or
print 'this is a tuple %s' % ((1, 2, 3),)

Note, this assumes you are using a Python version earlier than 3.0.

How to disable mouse right click on a web page?

window.oncontextmenu = function () {
return false;
}

might help you.

Extract column values of Dataframe as List in Apache Spark

I know the answer given and asked for is assumed for Scala, so I am just providing a little snippet of Python code in case a PySpark user is curious. The syntax is similar to the given answer, but to properly pop the list out I actually have to reference the column name a second time in the mapping function and I do not need the select statement.

i.e. A DataFrame, containing a column named "Raw"

To get each row value in "Raw" combined as a list where each entry is a row value from "Raw" I simply use:

MyDataFrame.rdd.map(lambda x: x.Raw).collect()

How to stop a setTimeout loop?

As this is tagged with the extjs tag it may be worth looking at the extjs method: http://docs.sencha.com/extjs/6.2.0/classic/Ext.Function.html#method-interval

This works much like setInterval, but also takes care of the scope, and allows arguments to be passed too:

function setBgPosition() {
    var c = 0;
    var numbers = [0, -120, -240, -360, -480, -600, -720];
    function run() {
       Ext.get('common-spinner').setStyle('background-position', numbers[c++] + 'px 0px');
        if (c<numbers.length){
            c=0;
        }
    }
    return Ext.Function.interval(run,200);
}

var bgPositionTimer = setBgPosition();

when you want to stop you can use clearInterval to stop it

clearInterval(bgPositionTimer);

An example use case would be:

Ext.Ajax.request({
    url: 'example.json',

    success: function(response, opts) {
        clearInterval(bgPositionTimer);
    },

    failure: function(response, opts) {
        console.log('server-side failure with status code ' + response.status);
        clearInterval(bgPositionTimer);
    }
});

In HTML5, can the <header> and <footer> tags appear outside of the <body> tag?

If you really want it to look more semantic like having the <body> in the middle you can use the <main> element. With all the recent advances the <body>element is not as semantic as it once was but you just have to think of it as a wrapper in which the view port sees.

<html>
    <head>
    </head>
    <body>
        <header>
        </header>
        <main>
            <section></section>
            <article></article>
        </main>
        <footer>
        </footer>
    <body>
</html>

'git status' shows changed files, but 'git diff' doesn't

I added the file to the index:

git add file_name

and then ran:

git diff --cached file_name

You can see the description of git diff here.

If you need to undo your git add, then please see here: How to undo 'git add' before commit?