Programs & Examples On #Createinstance

How to Pass Parameters to Activator.CreateInstance<T>()

Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.

There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.

Details about the issue on this article.

Graph is taken from the article and represents time taken in ms per 1000 calls.

Performance comparison

How can I decrypt MySQL passwords

If a proper encryption method was used, it's not going to be possible to easily retrieve them.

Just reset them with new passwords.

Edit: The string looks like it is using PASSWORD():

UPDATE user SET password = PASSWORD("newpassword");

how to download file in react js

React gives a security issue when using a tag with target="_blank".

I managed to get it working like that:

<a href={uploadedFileLink} target="_blank" rel="noopener noreferrer" download>
   <Button>
      <i className="fas fa-download"/>
      Download File
   </Button>
</a>

Grant all on a specific schema in the db to a group role in PostgreSQL

You found the shorthand to set privileges for all existing tables in the given schema. The manual clarifies:

(but note that ALL TABLES is considered to include views and foreign tables).

Bold emphasis mine. serial columns are implemented with nextval() on a sequence as column default and, quoting the manual:

For sequences, this privilege allows the use of the currval and nextval functions.

So if there are serial columns, you'll also want to grant USAGE (or ALL PRIVILEGES) on sequences

GRANT USAGE ON ALL SEQUENCES IN SCHEMA foo TO mygrp;

Note: identity columns in Postgres 10 or later use implicit sequences that don't require additional privileges. (Consider upgrading serial columns.)

What about new objects?

You'll also be interested in DEFAULT PRIVILEGES for users or schemas:

ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT ALL PRIVILEGES ON TABLES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo GRANT USAGE          ON SEQUENCES TO staff;
ALTER DEFAULT PRIVILEGES IN SCHEMA foo REVOKE ...;

This sets privileges for objects created in the future automatically - but not for pre-existing objects.

Default privileges are only applied to objects created by the targeted user (FOR ROLE my_creating_role). If that clause is omitted, it defaults to the current user executing ALTER DEFAULT PRIVILEGES. To be explicit:

ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo GRANT ...;
ALTER DEFAULT PRIVILEGES FOR ROLE my_creating_role IN SCHEMA foo REVOKE ...;

Note also that all versions of pgAdmin III have a subtle bug and display default privileges in the SQL pane, even if they do not apply to the current role. Be sure to adjust the FOR ROLE clause manually when copying the SQL script.

Converting a string to an integer on Android

Use regular expression:

int i=Integer.parseInt("hello123".replaceAll("[\\D]",""));
int j=Integer.parseInt("123hello".replaceAll("[\\D]",""));
int k=Integer.parseInt("1h2el3lo".replaceAll("[\\D]",""));

output:

i=123;
j=123;
k=123;

click() event is calling twice in jquery

A rather common solution to the two click problem is putting

e.stopPropagation()

at the end of your function (assuming you use function(e) that is). This prevents the event from bubbling up which could lead to a second execution of the function.

How can you create pop up messages in a batch script?

msg * "Enter Your Message"

Does this help ?

Retrieve the position (X,Y) of an HTML element relative to the browser window

You can add two properties to Element.prototype to get the top/left of any element.

Object.defineProperty( Element.prototype, 'documentOffsetTop', {
    get: function () { 
        return this.offsetTop + ( this.offsetParent ? this.offsetParent.documentOffsetTop : 0 );
    }
} );

Object.defineProperty( Element.prototype, 'documentOffsetLeft', {
    get: function () { 
        return this.offsetLeft + ( this.offsetParent ? this.offsetParent.documentOffsetLeft : 0 );
    }
} );

This is called like this:

var x = document.getElementById( 'myDiv' ).documentOffsetLeft;

Here's a demo comparing the results to jQuery's offset().top and .left: http://jsfiddle.net/ThinkingStiff/3G7EZ/

How to host material icons offline?

Method 2. Self hosting Developer Guide

Download the latest release from github (assets: zip file), unzip, and copy the font folder, containing the material design icons files, into your local project -- https://github.com/google/material-design-icons/releases

You only need to use the font folder from the archive: it contains the icons fonts in the different formats (for multiple browser support) and boilerplate css.

  • Replace the source in the url attribute of @font-face, with the relative path to the iconfont folder in your local project, (where the font files are located) eg. url("iconfont/MaterialIcons-Regular.ttf")
@font-face {
   font-family: 'Material Icons';
   font-style: normal;
   font-weight: 400;
   src: url(iconfont/MaterialIcons-Regular.eot); /* For IE6-8 */
   src: local('Material Icons'),
        local('MaterialIcons-Regular'),
        url(iconfont/MaterialIcons-Regular.woff2) format('woff2'),
        url(iconfont/MaterialIcons-Regular.woff) format('woff'),
        url(iconfont/MaterialIcons-Regular.ttf) format('truetype');
}

.material-icons {
  font-family: 'Material Icons';
  font-weight: normal;
  font-style: normal;
  font-size: 24px;  /* Preferred icon size */
  display: inline-block;
  line-height: 1;
  text-transform: none;
  letter-spacing: normal;
  word-wrap: normal;
  white-space: nowrap;
  direction: ltr;

  /* Support for all WebKit browsers. */
  -webkit-font-smoothing: antialiased;
  /* Support for Safari and Chrome. */
  text-rendering: optimizeLegibility;

  /* Support for Firefox. */
  -moz-osx-font-smoothing: grayscale;

  /* Support for IE. */
  font-feature-settings: 'liga';
}

<i class="material-icons">face</i>

NPM / Bower Packages

Google officially has a Bower and NPM dependency option -- follow Material Icons Guide 1

Using bower : bower install material-design-icons --save

Using NPM : npm install material-design-icons --save

Material Icons : Alternatively look into Material design icon font and CSS framework for self hosting the icons, from @marella's https://marella.me/material-icons/


Note

It seems google has the project on low maintenance mode. The last release was, at time of writing, 3 years ago!

There are several issues on GitHub regarding this, but I'd like to refer to @cyberalien comment on the issue Is this project actively maintained? #951 where it refers several community projects that forked and continue maintaining material icons.


Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

What are all the user accounts for IIS/ASP.NET and how do they differ?

This is a very good question and sadly many developers don't ask enough questions about IIS/ASP.NET security in the context of being a web developer and setting up IIS. So here goes....

To cover the identities listed:

IIS_IUSRS:

This is analogous to the old IIS6 IIS_WPG group. It's a built-in group with it's security configured such that any member of this group can act as an application pool identity.

IUSR:

This account is analogous to the old IUSR_<MACHINE_NAME> local account that was the default anonymous user for IIS5 and IIS6 websites (i.e. the one configured via the Directory Security tab of a site's properties).

For more information about IIS_IUSRS and IUSR see:

Understanding Built-In User and Group Accounts in IIS 7

DefaultAppPool:

If an application pool is configured to run using the Application Pool Identity feature then a "synthesised" account called IIS AppPool\<pool name> will be created on the fly to used as the pool identity. In this case there will be a synthesised account called IIS AppPool\DefaultAppPool created for the life time of the pool. If you delete the pool then this account will no longer exist. When applying permissions to files and folders these must be added using IIS AppPool\<pool name>. You also won't see these pool accounts in your computers User Manager. See the following for more information:

Application Pool Identities

ASP.NET v4.0: -

This will be the Application Pool Identity for the ASP.NET v4.0 Application Pool. See DefaultAppPool above.

NETWORK SERVICE: -

The NETWORK SERVICE account is a built-in identity introduced on Windows 2003. NETWORK SERVICE is a low privileged account under which you can run your application pools and websites. A website running in a Windows 2003 pool can still impersonate the site's anonymous account (IUSR_ or whatever you configured as the anonymous identity).

In ASP.NET prior to Windows 2008 you could have ASP.NET execute requests under the Application Pool account (usually NETWORK SERVICE). Alternatively you could configure ASP.NET to impersonate the site's anonymous account via the <identity impersonate="true" /> setting in web.config file locally (if that setting is locked then it would need to be done by an admin in the machine.config file).

Setting <identity impersonate="true"> is common in shared hosting environments where shared application pools are used (in conjunction with partial trust settings to prevent unwinding of the impersonated account).

In IIS7.x/ASP.NET impersonation control is now configured via the Authentication configuration feature of a site. So you can configure to run as the pool identity, IUSR or a specific custom anonymous account.

LOCAL SERVICE:

The LOCAL SERVICE account is a built-in account used by the service control manager. It has a minimum set of privileges on the local computer. It has a fairly limited scope of use:

LocalService Account

LOCAL SYSTEM:

You didn't ask about this one but I'm adding for completeness. This is a local built-in account. It has fairly extensive privileges and trust. You should never configure a website or application pool to run under this identity.

LocalSystem Account

In Practice:

In practice the preferred approach to securing a website (if the site gets its own application pool - which is the default for a new site in IIS7's MMC) is to run under Application Pool Identity. This means setting the site's Identity in its Application Pool's Advanced Settings to Application Pool Identity:

enter image description here

In the website you should then configure the Authentication feature:

enter image description here

Right click and edit the Anonymous Authentication entry:

enter image description here

Ensure that "Application pool identity" is selected:

enter image description here

When you come to apply file and folder permissions you grant the Application Pool identity whatever rights are required. For example if you are granting the application pool identity for the ASP.NET v4.0 pool permissions then you can either do this via Explorer:

enter image description here

Click the "Check Names" button:

enter image description here

Or you can do this using the ICACLS.EXE utility:

icacls c:\wwwroot\mysite /grant "IIS AppPool\ASP.NET v4.0":(CI)(OI)(M)

...or...if you site's application pool is called BobsCatPicBlogthen:

icacls c:\wwwroot\mysite /grant "IIS AppPool\BobsCatPicBlog":(CI)(OI)(M)

I hope this helps clear things up.

Update:

I just bumped into this excellent answer from 2009 which contains a bunch of useful information, well worth a read:

The difference between the 'Local System' account and the 'Network Service' account?

WSDL validator?

If you're using Eclipse, just have your WSDL in a .wsdl file, eclipse will validate it automatically.

From the Doc

The WSDL validator handles validation according to the 4 step process defined above. Steps 1 and 2 are both delegated to Apache Xerces (and XML parser). Step 3 is handled by the WSDL validator and any extension namespace validators (more on extensions below). Step 4 is handled by any declared custom validators (more on this below as well). Each step must pass in order for the next step to run.

Using JSON POST Request

Modern browsers do not currently implement JSONRequest (as far as I know) since it is only a draft right now. I have found someone who has implemented it as a library that you can include in your page: http://devpro.it/JSON/files/JSONRequest-js.html (please note that it has a few dependencies).

Otherwise, you might want to go with another JS library like jQuery or Mootools.

Index was out of range. Must be non-negative and less than the size of the collection parameter name:index

what this means ? is there any problem in my code

It means that you are accessing a location or index which is not present in collection.

To find this, Make sure your Gridview has 5 columns as you are using it's 5th column by this line

dataGridView1.Columns[4].Name = "Amount";

Here is the image which shows the elements of an array. So if your gridview has less column then the (index + 1) by which you are accessing it, then this exception arises.

enter image description here

How to get index in Handlebars each helper?

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


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

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

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

For object iteration, use @key instead:

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

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?

If you use Java and spring MVC you just need to add the following annotation to your method returning your page :

@CrossOrigin(origins = "*")

"*" is to allow your page to be accessible from anywhere. See https://developer.mozilla.org/fr/docs/Web/HTTP/Headers/Access-Control-Allow-Origin for more details about that.

No server in windows>preferences

In Eclipse Kepler,

  1. go to Help, select ‘Install New Software’
  2. Choose “Kepler- http://download.eclipse.org/releases/kepler” site or add it in if it’s missing.
  3. Expand “Web, XML, and Java EE Development” section Check JST Server Adapters and JST Server Adapters Extensions and install it

After Eclipse restart, go to Window / Preferences / Server / Runtime Environments

VBA - how to conditionally skip a for loop iteration

Hi I am also facing this issue and I solve this using below example code

For j = 1 To MyTemplte.Sheets.Count

       If MyTemplte.Sheets(j).Visible = 0 Then
           GoTo DoNothing        
       End If 


'process for this for loop
DoNothing:

Next j 

Can I create links with 'target="_blank"' in Markdown?

With Markdown-2.5.2, you can use this:

[link](url){:target="_blank"}

Error Code: 1062. Duplicate entry '1' for key 'PRIMARY'

The main reason why the error has been generated is because there is already an existing value of 1 for the column ID in which you define it as PRIMARY KEY (values are unique) in the table you are inserting.

Why not set the column ID as AUTO_INCREMENT?

CREATE  TABLE IF NOT EXISTS `PROGETTO`.`UFFICIO-INFORMAZIONI` (
  `ID` INT(11) NOT NULL AUTO_INCREMENT,
  `viale` VARCHAR(45) NULL ,
   .....

and when you are inserting record, you can now skip the column ID

INSERT INTO `PROGETTO`.`UFFICIO-INFORMAZIONI` (`viale`, `num_civico`, ...) 
VALUES ('Viale Cogel ', '120', ...)

Convert NSNumber to int in Objective-C

A tested one-liner:

int number = ((NSNumber*)[dict objectForKey:@"integer"]).intValue;

Appending an element to the end of a list in Scala

That's because you shouldn't do it (at least with an immutable list). If you really really need to append an element to the end of a data structure and this data structure really really needs to be a list and this list really really has to be immutable then do eiher this:

(4 :: List(1,2,3).reverse).reverse

or that:

List(1,2,3) ::: List(4)

How to keep a git branch in sync with master

Yeah I agree with your approach. To merge mobiledevicesupport into master you can use

git checkout master
git pull origin master //Get all latest commits of master branch
git merge mobiledevicesupport

Similarly you can also merge master in mobiledevicesupport.

Q. If cross merging is an issue or not.

A. Well it depends upon the commits made in mobile* branch and master branch from the last time they were synced. Take this example: After last sync, following commits happen to these branches

Master branch: A -> B -> C [where A,B,C are commits]
Mobile branch: D -> E

Now, suppose commit B made some changes to file a.txt and commit D also made some changes to a.txt. Let us have a look at the impact of each operation of merging now,

git checkout master //Switches to master branch
git pull // Get the commits you don't have. May be your fellow workers have made them.
git merge mobiledevicesupport // It will try to add D and E in master branch.

Now, there are two types of merging possible

  1. Fast forward merge
  2. True merge (Requires manual effort)

Git will first try to make FF merge and if it finds any conflicts are not resolvable by git. It fails the merge and asks you to merge. In this case, a new commit will occur which is responsible for resolving conflicts in a.txt.

So Bottom line is Cross merging is not an issue and ultimately you have to do it and that is what syncing means. Make sure you dirty your hands in merging branches before doing anything in production.

Most common C# bitwise operations on enums

@Drew

Note that except in the simplest of cases, the Enum.HasFlag carries a heavy performance penalty in comparison to writing out the code manually. Consider the following code:

[Flags]
public enum TestFlags
{
    One = 1,
    Two = 2,
    Three = 4,
    Four = 8,
    Five = 16,
    Six = 32,
    Seven = 64,
    Eight = 128,
    Nine = 256,
    Ten = 512
}


class Program
{
    static void Main(string[] args)
    {
        TestFlags f = TestFlags.Five; /* or any other enum */
        bool result = false;

        Stopwatch s = Stopwatch.StartNew();
        for (int i = 0; i < 10000000; i++)
        {
            result |= f.HasFlag(TestFlags.Three);
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *4793 ms*

        s.Restart();
        for (int i = 0; i < 10000000; i++)
        {
            result |= (f & TestFlags.Three) != 0;
        }
        s.Stop();
        Console.WriteLine(s.ElapsedMilliseconds); // *27 ms*        

        Console.ReadLine();
    }
}

Over 10 million iterations, the HasFlags extension method takes a whopping 4793 ms, compared to the 27 ms for the standard bitwise implementation.

How do you create optional arguments in php?

The default value of the argument must be a constant expression. It can't be a variable or a function call.

If you need this functionality however:

function foo($foo, $bar = false)
{
    if(!$bar)
    {
        $bar = $foo;
    }
}

Assuming $bar isn't expected to be a boolean of course.

Two Radio Buttons ASP.NET C#

In order to make it work, you have to set property GroupName of both radio buttons to the same value:

<asp:RadioButton id="rbMetric" runat="server" GroupName="measurementSystem"></asp:RadioButton>
<asp:RadioButton id="rbUS" runat="server" GroupName="measurementSystem"></asp:RadioButton>

Personally, I prefer to use a RadioButtonList:

<asp:RadioButtonList ID="rblMeasurementSystem" runat="server">
    <asp:ListItem Text="Metric" Value="metric" />
    <asp:ListItem Text="US" Value="us" />
</asp:RadioButtonList>

Deleting a file in VBA

An alternative way to code Brettski's answer, with which I otherwise agree entirely, might be

With New FileSystemObject
    If .FileExists(yourFilePath) Then
        .DeleteFile yourFilepath
    End If
End With

Same effect but fewer (well, none at all) variable declarations.

The FileSystemObject is a really useful tool and well worth getting friendly with. Apart from anything else, for text file writing it can actually sometimes be faster than the legacy alternative, which may surprise a few people. (In my experience at least, YMMV).

How to add a "confirm delete" option in ASP.Net Gridview?

I like this way of adding a confirmation prompt before deleting a record from a gridview. This is the CommandField definition nested within a GridView web control in the aspx page. There's nothing fancy here--just a straightforward Commandfield.

_x000D_
_x000D_
<asp:CommandField ShowEditButton="true" UpdateText="Save" ShowDeleteButton="True">_x000D_
  <ControlStyle CssClass="modMarketAdjust" />_x000D_
</asp:CommandField>
_x000D_
_x000D_
_x000D_

Then, all I had to do was add some code to the RowDeleting event of the GridView control. This event fires before the row is actually deleted, which allows you to get the user's confirmation, and to cancel the event if he doesn't want to cancel after all. Here is the code that I put in the RowDeleting event handler:

Private Sub grdMarketAdjustment_RowDeleting(sender As Object, e As GridViewDeleteEventArgs) Handles grdMarketAdjustment.RowDeleting
  Dim confirmed As Integer = MsgBox("Are you sure that you want to delete this market adjustment?", MsgBoxStyle.YesNo + MsgBoxStyle.MsgBoxSetForeground, "Confirm Delete")
  If Not confirmed = MsgBoxResult.Yes Then
    e.Cancel = True 'Cancel the delete.
  End If
End Sub

And that seems to work fine.

What is the best way to know if all the variables in a Class are null?

The best way in my opinion is Reflection as others have recommended. Here's a sample that evaluates each local field for null. If it finds one that is not null, method will return false.

public class User {

    String id = null;
    String name = null;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public boolean isNull() {
        Field fields[] = this.getClass().getDeclaredFields();
        for (Field f : fields) {
            try {
                Object value = f.get(this);
                if (value != null) {
                    return false;
                }
            }
            catch (IllegalArgumentException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            catch (IllegalAccessException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }


        }
        return true;

    }

    public static void main(String args[]) {
        System.out.println(new User().isNull());
    }
}

How do I set the timeout for a JAX-WS webservice client?

Here is my working solution :

// --------------------------
// SOAP Message creation
// --------------------------
SOAPMessage sm = MessageFactory.newInstance().createMessage();
sm.setProperty(SOAPMessage.WRITE_XML_DECLARATION, "true");
sm.setProperty(SOAPMessage.CHARACTER_SET_ENCODING, "UTF-8");

SOAPPart sp = sm.getSOAPPart();
SOAPEnvelope se = sp.getEnvelope();
se.setEncodingStyle("http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:SOAP-ENC", "http://schemas.xmlsoap.org/soap/encoding/");
se.setAttribute("xmlns:xsd", "http://www.w3.org/2001/XMLSchema");
se.setAttribute("xmlns:xsi", "http://www.w3.org/2001/XMLSchema-instance");

SOAPBody sb = sm.getSOAPBody();
// 
// Add all input fields here ...
// 

SOAPConnection connection = SOAPConnectionFactory.newInstance().createConnection();
// -----------------------------------
// URL creation with TimeOut connexion
// -----------------------------------
URL endpoint = new URL(null,
                      "http://myDomain/myWebService.php",
                    new URLStreamHandler() { // Anonymous (inline) class
                    @Override
                    protected URLConnection openConnection(URL url) throws IOException {
                    URL clone_url = new URL(url.toString());
                    HttpURLConnection clone_urlconnection = (HttpURLConnection) clone_url.openConnection();
                    // TimeOut settings
                    clone_urlconnection.setConnectTimeout(10000);
                    clone_urlconnection.setReadTimeout(10000);
                    return(clone_urlconnection);
                    }
                });


try {
    // -----------------
    // Send SOAP message
    // -----------------
    SOAPMessage retour = connection.call(sm, endpoint);
}
catch(Exception e) {
    if ((e instanceof com.sun.xml.internal.messaging.saaj.SOAPExceptionImpl) && (e.getCause()!=null) && (e.getCause().getCause()!=null) && (e.getCause().getCause().getCause()!=null)) {
        System.err.println("[" + e + "] Error sending SOAP message. Initial error cause = " + e.getCause().getCause().getCause());
    }
    else {
        System.err.println("[" + e + "] Error sending SOAP message.");

    }
}

DateTimePicker time picker in 24 hour but displaying in 12hr?

this will display current ate & time. Working on my side perfectly

$("#datePicker").datetimepicker({
    format: 'DD-MM-YYYY HH:mm A',
    defaultDate: new Date(),
});

Setting dropdownlist selecteditem programmatically

Just Use this oneliner:

divisions.Items.FindByText("Some Text").Selected = true;
divisions.Items.FindByValue("some value").Selected = true;

where divisions is a dropdownlist control.

Hope it helps someone.

Linker command failed with exit code 1 - duplicate symbol __TMRbBp

I had removed files from Compile Sources in Build Phases in Targets. I added main.m and it worked.

Check whether a request is GET or POST

Better use $_SERVER['REQUEST_METHOD']:

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    // …
}

R Language: How to print the first or last rows of a data set?

If you want to print the last 10 lines, use

tail(dataset, 10)

for the first 10, you could also do

head(dataset, 10)

How do I correct "Commit Failed. File xxx is out of date. xxx path not found."

I think I've seen something similar when folders were moved on the server but the working copies were still bound to the older SVN folder structure. Not sure if anyone moved things around in your trunk before you had the chance to merge the branch.

Is that a possibility?

ViewBag, ViewData and TempData

Also the scope is different between viewbag and temptdata. viewbag is based on first view (not shared between action methods) but temptdata can be shared between an action method and just one another.

How do you remove a specific revision in the git history?

Here is a way to remove non-interactively a specific <commit-id>, knowing only the <commit-id> you would like to remove:

git rebase --onto <commit-id>^ <commit-id> HEAD

The shortest possible output from git log containing author and date

git --no-pager log --pretty=tformat:"%C(yellow)%h %C(cyan)%ad %Cblue%an%C(auto)%d %Creset%s" --graph --date=format:"%Y-%m-%d %H:%M" -25 

I use alias

alias gitlog='git --no-pager log --pretty=tformat:"%C(yellow)%h %C(cyan)%ad %Cblue%an%C(auto)%d %Creset%s" --graph --date=format:"%Y-%m-%d %H:%M" -25'

Differences: I use tformat and isodate without seconds and time zones , with --no-pager you will see colors

How to use enums as flags in C++?

If your compiler doesn't support strongly typed enums yet, you can give a look to the following article from the c++ source:

From the abstract:

This article presents a solution to the problem of constraining bit operations to
allow only safe and legitimate ones, and turn all invalid bit manipulations into compile-time errors. Best of all, the syntax of bit operations remains unchanged, and the code working with bits does not need to be modified, except possibly to fix errors that had as yet remained undetected.

How to get client IP address in Laravel 5+

If you are still getting 127.0.0.1 as the IP, you need to add your "proxy", but be aware that you have to change it before going into production!

Read "Configuring Trusted Proxies".

And add this:

class TrustProxies extends Middleware
{
    /**
     * The trusted proxies for this application.
     *
     * @var array
     */
    protected $proxies = '*';

Now request()->ip() gives you the correct IP.

How do I create a sequence in MySQL?

SEQUENCES like it works on firebird:

-- =======================================================

CREATE TABLE SEQUENCES  
(  
  NM_SEQUENCE VARCHAR(32) NOT NULL UNIQUE,  
  VR_SEQUENCE BIGINT      NOT NULL  
);  

-- =======================================================
-- Creates a sequence sSeqName and set its initial value.
-- =======================================================

DROP PROCEDURE IF EXISTS CreateSequence;  

DELIMITER :)  
CREATE PROCEDURE CreateSequence( sSeqName VARCHAR(32), iSeqValue BIGINT )  
BEGIN  
  IF NOT EXISTS ( SELECT * FROM SEQUENCES WHERE (NM_SEQUENCE = sSeqName) ) THEN  
    INSERT INTO SEQUENCES (NM_SEQUENCE, VR_SEQUENCE)  
    VALUES (sSeqName   , iSeqValue  );  
  END IF;  
END :)  
DELIMITER ;  

-- CALL CreateSequence( 'MySequence', 0 );  

-- =======================================================================
-- Increments the sequence value of sSeqName by iIncrement and returns it.
-- If iIncrement is zero, returns the current value of sSeqName.
-- =======================================================================

DROP FUNCTION IF EXISTS GetSequenceVal;  

DELIMITER :)  
CREATE FUNCTION GetSequenceVal( sSeqName VARCHAR(32), iIncrement INTEGER )  
RETURNS BIGINT  -- iIncrement can be negative  
BEGIN  
  DECLARE iSeqValue BIGINT;  

  SELECT VR_SEQUENCE FROM SEQUENCES  
  WHERE  ( NM_SEQUENCE = sSeqName )  
  INTO   @iSeqValue;  

  IF ( iIncrement <> 0 ) THEN  
    SET @iSeqValue = @iSeqValue + iIncrement;  

    UPDATE SEQUENCES SET VR_SEQUENCE = @iSeqValue  
    WHERE  ( NM_SEQUENCE = sSeqName );  
  END IF;

  RETURN @iSeqValue;
END :)  
DELIMITER ;  

-- SELECT GetSequenceVal('MySequence', 1);  -- Adds 1 to MySequence value and returns it.

-- ===================================================================

How to scroll page in flutter

Use LayoutBuilder and Get the output you want

Wrap the SingleChildScrollView with LayoutBuilder and implement the Builder function.

we can use a LayoutBuilder to get the box contains or the amount of space available.

LayoutBuilder(
    builder: (BuildContext context, BoxConstraints constraints){
      return SingleChildScrollView(
        child: Stack(
          children: <Widget>[
            Container(
              height: constraints.maxHeight,
            ),
            topTitle(context),
            middleView(context),
            bottomView(context),
          ],
        ),
      );
    }
)

What does "javascript:void(0)" mean?

You should always have an href on your a tags. Calling a JavaScript function that returns 'undefined' will do just fine. So will linking to '#'.

Anchor tags in Internet Explorer 6 without an href do not get the a:hover style applied.

Yes, it is terrible and a minor crime against humanity, but then again so is Internet Explorer 6 in general.

I hope this helps.

Internet Explorer 6 is actually a major crime against humanity.

What is the best open XML parser for C++?

TiCPP is a "more c++" version of TinyXML.

'TiCPP' is short for the official name TinyXML++. It is a completely new interface to TinyXML (http://www.grinninglizard.com/tinyxml/) that uses MANY of the C++ strengths. Templates, exceptions, and much better error handling. It is also fully documented in doxygen. It is really cool because this version let's you interface tiny the exact same way as before or you can choose to use the new 'ticpp' classes. All you need to do is define TIXML_USE_TICPP. It has been tested in VC 6.0, VC 7.0, VC 7.1, VC 8.0, MinGW gcc 3.4.5, and in Linux GNU gcc 3+

Position absolute and overflow hidden

Make outer <div> to position: relative and inner <div> to position: absolute. It should work for you.

Android; Check if file exists without creating a new one

When you use this code, you are not creating a new File, it's just creating an object reference for that file and testing if it exists or not.

File file = new File(filePath);
if(file.exists()) 
    //do something

How to print out a variable in makefile

No need to modify the Makefile.

$ cat printvars.mak
print-%:
        @echo '$*=$($*)'

$ cd /to/Makefile/dir
$ make -f ~/printvars.mak -f Makefile print-VARIABLE

How to delete the contents of a folder?

the easiest way to delete all files in a folder/remove all files

import os
files = os.listdir(yourFilePath)
for f in files:
    os.remove(yourFilePath + f)

Ignoring directories in Git repositories on Windows

I had similar issues. I work on a Windows tool chain with a shared repository with Linux guys, and they happily create files with the same (except for case) names in a given folder.

The effect is that I can clone the repository and immediately have dozens of 'modified' files that, if I checked in, would create havoc.

I have Windows set to case sensitive and Git to not ignore case, but it still fails (in the Win32 API calls apparently).

If I gitignore the files then I have to remember to not track the .gitignore file.

But I found a good answer here:

http://archive.robwilkerson.org/2010/03/02/git-tip-ignore-changes-to-tracked-files/index.html

How to solve : SQL Error: ORA-00604: error occurred at recursive SQL level 1

I noticed following line from error.

exact fetch returns more than requested number of rows

That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.

Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.

So, I truncated dual table and inserted only row which X value. And, everything working fine.

Python 'If not' syntax

Yes, if bar is not None is more explicit, and thus better, assuming it is indeed what you want. That's not always the case, there are subtle differences: if not bar: will execute if bar is any kind of zero or empty container, or False. Many people do use not bar where they really do mean bar is not None.

Append text to input field

_x000D_
_x000D_
    $('#input-field-id').val($('#input-field-id').val() + 'more text');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<input id="input-field-id" />
_x000D_
_x000D_
_x000D_

How to make a DIV not wrap?

overflow: hidden should give you the correct behavior. My guess is that RTL is messed up because you have float: left on the encapsulated divs.

Beside that bug, you got the right behavior.

Project with path ':mypath' could not be found in root project 'myproject'

I got similar error after deleting a subproject, removed

"*compile project(path: ':MySubProject', configuration: 'android-endpoints')*"

in build.gradle (dependencies) under Gradle Scripts

What is RSS and VSZ in Linux memory management

RSS is Resident Set Size (physically resident memory - this is currently occupying space in the machine's physical memory), and VSZ is Virtual Memory Size (address space allocated - this has addresses allocated in the process's memory map, but there isn't necessarily any actual memory behind it all right now).

Note that in these days of commonplace virtual machines, physical memory from the machine's view point may not really be actual physical memory.

process.waitFor() never returns

As others have mentioned you have to consume stderr and stdout.

Compared to the other answers, since Java 1.7 it is even more easy. You do not have to create threads yourself anymore to read stderr and stdout.

Just use the ProcessBuilder and use the methods redirectOutput in combination with either redirectError or redirectErrorStream.

String directory = "/working/dir";
File out = new File(...); // File to write stdout to
File err = new File(...); // File to write stderr to
ProcessBuilder builder = new ProcessBuilder();
builder.directory(new File(directory));
builder.command(command);
builder.redirectOutput(out); // Redirect stdout to file
if(out == err) { 
  builder.redirectErrorStream(true); // Combine stderr into stdout
} else { 
  builder.redirectError(err); // Redirect stderr to file
}
Process process = builder.start();

Posting JSON Data to ASP.NET MVC

Take a look at Phil Haack's post on model binding JSON data. The problem is that the default model binder doesn't serialize JSON properly. You need some sort of ValueProvider OR you could write a custom model binder:

using System.IO;
using System.Web.Script.Serialization;

public class JsonModelBinder : DefaultModelBinder {
        public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext) {
            if(!IsJSONRequest(controllerContext)) {
                return base.BindModel(controllerContext, bindingContext);
            }

            // Get the JSON data that's been posted
            var request = controllerContext.HttpContext.Request;
            //in some setups there is something that already reads the input stream if content type = 'application/json', so seek to the begining
            request.InputStream.Seek(0, SeekOrigin.Begin);
            var jsonStringData = new StreamReader(request.InputStream).ReadToEnd();

            // Use the built-in serializer to do the work for us
            return new JavaScriptSerializer()
                .Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);

            // -- REQUIRES .NET4
            // If you want to use the .NET4 version of this, change the target framework and uncomment the line below
            // and comment out the above return statement
            //return new JavaScriptSerializer().Deserialize(jsonStringData, bindingContext.ModelMetadata.ModelType);
        }

        private static bool IsJSONRequest(ControllerContext controllerContext) {
            var contentType = controllerContext.HttpContext.Request.ContentType;
            return contentType.Contains("application/json");
        }
    }

public static class JavaScriptSerializerExt {
        public static object Deserialize(this JavaScriptSerializer serializer, string input, Type objType) {
            var deserializerMethod = serializer.GetType().GetMethod("Deserialize", BindingFlags.NonPublic | BindingFlags.Static);

            // internal static method to do the work for us
            //Deserialize(this, input, null, this.RecursionLimit);

            return deserializerMethod.Invoke(serializer,
                new object[] { serializer, input, objType, serializer.RecursionLimit });
        }
    }

And tell MVC to use it in your Global.asax file:

ModelBinders.Binders.DefaultBinder = new JsonModelBinder();

Also, this code makes use of the content type = 'application/json' so make sure you set that in jquery like so:

$.ajax({
    dataType: "json",
    contentType: "application/json",            
    type: 'POST',
    url: '/Controller/Action',
    data: { 'items': JSON.stringify(lineItems), 'id': documentId }
});

How to define a Sql Server connection string to use in VB.NET?

             if (reader.HasRows)
            {
                while (reader.Read())
                {
                    comboBox1.Items.Add(reader.GetString(0));
                }
            }
            reader.Close();

            MySqlDataReader reader1 = cmd1.ExecuteReader();
            if (reader1.HasRows)
            {
                while (reader1.Read())
                {
                    listBox1.Items.Add(reader1.GetString(0));
                }
            }
            reader1.Close();

How to find all duplicate from a List<string>?

Using LINQ, ofcourse. The below code would give you dictionary of item as string, and the count of each item in your sourc list.

var item2ItemCount = list.GroupBy(item => item).ToDictionary(x=>x.Key,x=>x.Count());

Inner Joining three tables

try the following code

select * from TableA A 
inner join TableB B on A.Column=B.Column 
inner join TableC C on A.Column=C.Column

Java multiline string

With JDK/12 early access build # 12, one can now use multiline strings in Java as follows :

String multiLine = `First line
    Second line with indentation
Third line
and so on...`; // the formatting as desired
System.out.println(multiLine);

and this results in the following output:

First line
    Second line with indentation
Third line
and so on...

Edit: Postponed to java 13

R error "sum not meaningful for factors"

The error comes when you try to call sum(x) and x is a factor.

What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)

simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:

family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))

For a detailed explanation of why the intermediate as.character step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?

Check if Python Package is installed

As an extension of this answer:

For Python 2.*, pip show <package_name> will perform the same task.

For example pip show numpy will return the following or alike:

Name: numpy
Version: 1.11.1
Summary: NumPy: array processing for numbers, strings, records, and objects.
Home-page: http://www.numpy.org
Author: NumPy Developers
Author-email: [email protected]
License: BSD
Location: /home/***/anaconda2/lib/python2.7/site-packages
Requires: 
Required-by: smop, pandas, tables, spectrum, seaborn, patsy, odo, numpy-stl, numba, nfft, netCDF4, MDAnalysis, matplotlib, h5py, GridDataFormats, dynd, datashape, Bottleneck, blaze, astropy

How to filter array when object key value is in array

In case you have key value pairs in your input array, I used:

.filter(
          this.multi_items[0] != null && store.state.isSearchBox === false
            ? item =>
                _.map(this.multi_items, "value").includes(item["wijknaam"])
            : item => item["wijknaam"].includes("")
        );

where the input array is multi_items as: [{"text": "bla1", "value": "green"}, {"text": etc. etc.}]

_.map is a lodash function.

\r\n, \r and \n what is the difference between them?

They are normal symbols as 'a' or '?' or any other. Just (invisible) entries in a string. \r moves cursor to the beginning of the line. \n goes one line down.

As for your replacement, you haven't specified what language you're using, so here's the sketch:

someString.replace("\r\n", "\n").replace("\r", "\n")

Easiest way to make lua script wait/pause/sleep/block for a few seconds?

I would implement a simple function to wrap the host system's sleep function in C.

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

I had modified my answer tons of times and realized i don't have to say anything, python had explained itself already.

a = 'string'
a.replace('t', '_')
print(a)
>>> 'string'

a = a.replace('t', '_')
print(a)
>>> 's_ring'

b = 100
b + 1
print(b)
>>> 100

b = b + 1
print(b)
>>> 101

def test_id(arg):
    c = id(arg)
    arg = 123
    d = id(arg)
    return

a = 'test ids'
b = id(a)
test_id(a)
e = id(a)

# b = c  = e != d
# this function do change original value
del change_like_mutable(arg):
    arg.append(1)
    arg.insert(0, 9)
    arg.remove(2)
    return

test_1 = [1, 2, 3]
change_like_mutable(test_1)



# this function doesn't 
def wont_change_like_str(arg):
     arg = [1, 2, 3]
     return


test_2 = [1, 1, 1]
wont_change_like_str(test_2)
print("Doesn't change like a imutable", test_2)

This devil is not the reference / value / mutable or not / instance, name space or variable / list or str, IT IS THE SYNTAX, EQUAL SIGN.

How to ignore files/directories in TFS for avoiding them to go to central source repository?

It does seem a little cumbersome to ignore files (and folders) in Team Foundation Server. I've found a couple ways to do this (using TFS / Team Explorer / Visual Studio 2008). These methods work with the web site ASP project type, too.

One way is to add a new or existing item to a project (e.g. right click on project, Add Existing Item or drag and drop from Windows explorer into the solution explorer), let TFS process the file(s) or folder, then undo pending changes on the item(s). TFS will unmark them as having a pending add change, and the files will sit quietly in the project and stay out of TFS.

Another way is with the Add Items to Folder command of Source Control Explorer. This launches a small wizard, and on one of the steps you can select items to exclude (although, I think you have to add at least one item to TFS with this method for the wizard to let you continue).

You can even add a forbidden patterns check-in policy (under Team -> Team Project Settings -> Source Control... -> Check-in Policy) to disallow other people on the team from mistakenly checking in certain assets.

Initialize class fields in constructor or at declaration?

Being consistent is important, but this is the question to ask yourself: "Do I have a constructor for anything else?"

Typically, I am creating models for data transfers that the class itself does nothing except work as housing for variables.

In these scenarios, I usually don't have any methods or constructors. It would feel silly to me to create a constructor for the exclusive purpose of initializing my lists, especially since I can initialize them in-line with the declaration.

So as many others have said, it depends on your usage. Keep it simple, and don't make anything extra that you don't have to.

Different CURRENT_TIMESTAMP and SYSDATE in oracle

SYSDATE, SYSTIMESTAMP returns the Database's date and timestamp, whereas current_date, current_timestamp returns the date and timestamp of the location from where you work.

For eg. working from India, I access a database located in Paris. at 4:00PM IST:

select sysdate,systimestamp from dual;

This returns me the date and Time of Paris:

RESULT

12-MAY-14   12-MAY-14 12.30.03.283502000 PM +02:00

select current_date,current_timestamp from dual;

This returns me the date and Time of India:

RESULT

12-MAY-14   12-MAY-14 04.00.03.283520000 PM ASIA/CALCUTTA

Please note the 3:30 time difference.

Resolve conflicts using remote changes when pulling from Git remote

You can either use the answer from the duplicate link pointed by nvm.

Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):

git pull -s recursive -X theirs

Error: Uncaught SyntaxError: Unexpected token <

I too got this error, when developing a Backbone application using HTML5 push state in conjunction with an .htaccess which redirects any unknown files to index.html.

It turns out that when visiting a URL such as /something/5, my /index.html was effectively being served at /something/index.html (thanks to my .htaccess). This had the effect of breaking all the relative URLs to my JavaScript files (from inside the index.html ), which meant that they should have 404'd on me.

However, again due to my htaccess, instead of 404'ing when attempting to retrieve the JS files, they instead returned my index.html. Thus the browser was given an index.html for every JavaScript file it tried to pull in, and when it evaluated the HTML as if it were JavaScript, it returned a JS error due to the leading < (from my tag in index.html).

The fix in my case (as I was serving the site from inside a subdirectory) was to add a base tag in my html head.

<base href="/my-app/">

Remove HTML tags from string including &nbsp in C#

I took @Ravi Thapliyal's code and made a method: It is simple and might not clean everything, but so far it is doing what I need it to do.

public static string ScrubHtml(string value) {
    var step1 = Regex.Replace(value, @"<[^>]+>|&nbsp;", "").Trim();
    var step2 = Regex.Replace(step1, @"\s{2,}", " ");
    return step2;
}

mcrypt is deprecated, what is the alternative?

I was able to translate my Crypto object

  • Get a copy of php with mcrypt to decrypt the old data. I went to http://php.net/get/php-7.1.12.tar.gz/from/a/mirror, compiled it, then added the ext/mcrypt extension (configure;make;make install). I think I had to add the extenstion=mcrypt.so line to the php.ini as well. A series of scripts to build intermediate versions of the data with all data unencrypted.

  • Build a public and private key for openssl

    openssl genrsa -des3 -out pkey.pem 2048
    (set a password)
    openssl rsa -in pkey.pem -out pkey-pub.pem -outform PEM -pubout
    
  • To Encrypt (using public key) use openssl_seal. From what I've read, openssl_encrypt using an RSA key is limited to 11 bytes less than the key length (See http://php.net/manual/en/function.openssl-public-encrypt.php comment by Thomas Horsten)

    $pubKey = openssl_get_publickey(file_get_contents('./pkey-pub.pem'));
    openssl_seal($pwd, $sealed, $ekeys, [ $pubKey ]);
    $encryptedPassword = base64_encode($sealed);
    $key = base64_encode($ekeys[0]);
    

You could probably store the raw binary.

  • To Decrypt (using private key)

    $passphrase="passphrase here";
    $privKey = openssl_get_privatekey(file_get_contents('./pkey.pem'), $passphrase);
    // I base64_decode() from my db columns
    openssl_open($encryptedPassword, $plain, $key, $privKey);
    echo "<h3>Password=$plain</h3>";
    

P.S. You can't encrypt the empty string ("")

P.P.S. This is for a password database not for user validation.

How to round to 2 decimals with Python?

Here is an example that I used:

def volume(self):
    return round(pi * self.radius ** 2 * self.height, 2)

def surface_area(self):
    return round((2 * pi * self.radius * self.height) + (2 * pi * self.radius ** 2), 2)

Flutter.io Android License Status Unknown

Try downgrading your java version, this will happen when your systems java version isn't compatible with the one from android. Once you changed you the java version just run flutter doctor it will automatically accepts the licenses.

How can I check if a command exists in a shell script?

In general, that depends on your shell, but if you use bash, zsh, ksh or sh (as provided by dash), the following should work:

if ! type "$foobar_command_name" > /dev/null; then
  # install foobar here
fi

For a real installation script, you'd probably want to be sure that type doesn't return successfully in the case when there is an alias foobar. In bash you could do something like this:

if ! foobar_loc="$(type -p "$foobar_command_name")" || [[ -z $foobar_loc ]]; then
  # install foobar here
fi

Why AVD Manager options are not showing in Android Studio

Usually this implies some Android setup issue with the project. Go to the "Resource Manager" tab where you will be able to click on "Add Android Module" and click on import gradle files. If the import fails, you will get error messages that you can work with enter image description here

Global keyboard capture in C# application

Stephen Toub wrote a great article on implementing global keyboard hooks in C#:

using System;
using System.Diagnostics;
using System.Windows.Forms;
using System.Runtime.InteropServices;

class InterceptKeys
{
    private const int WH_KEYBOARD_LL = 13;
    private const int WM_KEYDOWN = 0x0100;
    private static LowLevelKeyboardProc _proc = HookCallback;
    private static IntPtr _hookID = IntPtr.Zero;

    public static void Main()
    {
        _hookID = SetHook(_proc);
        Application.Run();
        UnhookWindowsHookEx(_hookID);
    }

    private static IntPtr SetHook(LowLevelKeyboardProc proc)
    {
        using (Process curProcess = Process.GetCurrentProcess())
        using (ProcessModule curModule = curProcess.MainModule)
        {
            return SetWindowsHookEx(WH_KEYBOARD_LL, proc,
                GetModuleHandle(curModule.ModuleName), 0);
        }
    }

    private delegate IntPtr LowLevelKeyboardProc(
        int nCode, IntPtr wParam, IntPtr lParam);

    private static IntPtr HookCallback(
        int nCode, IntPtr wParam, IntPtr lParam)
    {
        if (nCode >= 0 && wParam == (IntPtr)WM_KEYDOWN)
        {
            int vkCode = Marshal.ReadInt32(lParam);
            Console.WriteLine((Keys)vkCode);
        }
        return CallNextHookEx(_hookID, nCode, wParam, lParam);
    }

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr SetWindowsHookEx(int idHook,
        LowLevelKeyboardProc lpfn, IntPtr hMod, uint dwThreadId);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    [return: MarshalAs(UnmanagedType.Bool)]
    private static extern bool UnhookWindowsHookEx(IntPtr hhk);

    [DllImport("user32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr CallNextHookEx(IntPtr hhk, int nCode,
        IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern IntPtr GetModuleHandle(string lpModuleName);
}

How can I check if a background image is loaded?

I've located a solution that worked better for me, and which has the advantage of being usable with several images (case not illustrated in this example).

From @adeneo's answer on this question :

If you have an element with a background image, like this

<div id="test" style="background-image: url(link/to/image.png)"><div>

You can wait for the background to load by getting the image URL and using it for an image object in javascript with an onload handler

var src = $('#test').css('background-image');
var url = src.match(/\((.*?)\)/)[1].replace(/('|")/g,'');

var img = new Image();
img.onload = function() {
    alert('image loaded');
}
img.src = url;
if (img.complete) img.onload();

create a trusted self-signed SSL cert for localhost (for use with Express/Node)

There are more aspects to this.

You can achieve TLS (some keep saying SSL) with a certificate, self-signed or not.

To have a green bar for a self-signed certificate, you also need to become the Certificate Authority (CA). This aspect is missing in most resources I found on my journey to achieve the green bar in my local development setup. Becoming a CA is as easy as creating a certificate.

This resource covers the creation of both the CA certificate and a Server certificate and resulted my setup in showing a green bar on localhost Chrome, Firefox and Edge: https://ram.k0a1a.net/self-signed_https_cert_after_chrome_58

Please note: in Chrome you need to add the CA Certificate to your trusted authorities.

iOS 7 status bar overlapping UI

If your developing for iOS 7 I wouldn't recommend wrapping the status bar in a black rectangle old iOS style. Just integrate it to the design for a more iOS 7 "fullscreen" look.

You can use this plugin to adjust the ink colour of the status bar, or hide it or show it in any instance of your app.

https://github.com/jota-v/cordova-ios-statusbar

The js methods are:

window.plugins.statusBar.hide();
window.plugins.statusBar.show();
window.plugins.statusBar.blackTint();
window.plugins.statusBar.whiteTint();

IMPORTANT: Also in your app plist file set UIViewControllerBasedStatusBarAppearance to NO.

What is the best way to implement "remember me" for a website?

I would store a user ID and a token. When the user comes back to the site, compare those two pieces of information against something persistent like a database entry.

As for security, just don't put anything in there that will allow someone to modify the cookie to gain extra benefits. For example, don't store their user groups or their password. Anything that can be modified that would circumvent your security should not be stored in the cookie.

How to extract a substring using regex

Since Java 9

As of this version, you can use a new method Matcher::results with no args that is able to comfortably return Stream<MatchResult> where MatchResult represents the result of a match operation and offers to read matched groups and more (this class is known since Java 1.5).

String string = "Some string with 'the data I want' inside and 'another data I want'.";

Pattern pattern = Pattern.compile("'(.*?)'");
pattern.matcher(string)
       .results()                       // Stream<MatchResult>
       .map(mr -> mr.group(1))          // Stream<String> - the 1st group of each result
       .forEach(System.out::println);   // print them out (or process in other way...)

The code snippet above results in:

the data I want
another data I want

The biggest advantage is in the ease of usage when one or more results is available compared to the procedural if (matcher.find()) and while (matcher.find()) checks and processing.

How do you format an unsigned long long int using printf?

Well, one way is to compile it as x64 with VS2008

This runs as you would expect:

int normalInt = 5; 
unsigned long long int num=285212672;
printf(
    "My number is %d bytes wide and its value is %ul. 
    A normal number is %d \n", 
    sizeof(num), 
    num, 
    normalInt);

For 32 bit code, we need to use the correct __int64 format specifier %I64u. So it becomes.

int normalInt = 5; 
unsigned __int64 num=285212672;
printf(
    "My number is %d bytes wide and its value is %I64u. 
    A normal number is %d", 
    sizeof(num),
    num, normalInt);

This code works for both 32 and 64 bit VS compiler.

How do I get the currently-logged username from a Windows service in .NET?

ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem") solution worked fine for me. BUT it does not work if the service is started over a Remote Desktop Connection. To work around this, we can ask for the username of the owner of an interactive process that always is running on a PC: explorer.exe. This way, we always get the currently Windows logged-in username from our Windows service:

foreach (System.Management.ManagementObject Process in Processes.Get())
{
    if (Process["ExecutablePath"] != null && 
        System.IO.Path.GetFileName(Process["ExecutablePath"].ToString()).ToLower() == "explorer.exe" )
    {
        string[] OwnerInfo = new string[2];
        Process.InvokeMethod("GetOwner", (object[])OwnerInfo);

        Console.WriteLine(string.Format("Windows Logged-in Interactive UserName={0}", OwnerInfo[0]));

        break;
    }
}

Android: How do I prevent the soft keyboard from pushing my view up?

You can simply switch your Activity's windowSoftInputModeflag to adjustPan in your AndroidMainfest.xml file inside your activity tag.

Check the official documentation for more info.

<activity
   ...
   android:windowSoftInputMode="adjustPan"> 
</activity>

If your container is not changing size, then you likely have the height set to "match parent". If possible, set the parent to "Wrap Content", or a constraint layout with constraingts to top and bottom of parent.

The parent container will shrink to fit the available space, so it is likely that your content should be inside of a scolling view to prevent (depending on the phone manufacturer and the layout choosen...)

  1. Content being smashed together
  2. Content hanging off the screen
  3. Content being inacccessable due to it being underneath the keyboard

even if the layout it is in is a relative or constraint layout, the content could exhibit problems 1-3.

jQuery Validate Plugin - How to create a simple custom rule?

// add a method. calls one built-in method, too.
jQuery.validator.addMethod("optdate", function(value, element) {
        return jQuery.validator.methods['date'].call(
            this,value,element
        )||value==("0000/00/00");
    }, "Please enter a valid date."
);

// connect it to a css class
jQuery.validator.addClassRules({
    optdate : { optdate : true }    
});

Table header to stay fixed at the top when user scrolls it out of view with jQuery

Well, I was trying to obtain the same effect without resorting to fixed size columns or having a fixed height for the entire table.

The solution I came up with is a hack. It consists of duplicating the entire table then hiding everything but the header, and making that have a fixed position.

HTML

<div id="table-container">
<table id="maintable">
    <thead>
        <tr>
            <th>Col1</th>
            <th>Col2</th>
            <th>Col3</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>some really long line here instead</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
                <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
                <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
        <tr>
            <td>info</td>
            <td>info</td>
            <td>info</td>
        </tr>
    </tbody>
</table>
<div id="bottom_anchor"></div>
</div>

CSS

body { height: 1000px; }
thead{
    background-color:white;
}

javascript

function moveScroll(){
    var scroll = $(window).scrollTop();
    var anchor_top = $("#maintable").offset().top;
    var anchor_bottom = $("#bottom_anchor").offset().top;
    if (scroll>anchor_top && scroll<anchor_bottom) {
    clone_table = $("#clone");
    if(clone_table.length == 0){
        clone_table = $("#maintable").clone();
        clone_table.attr('id', 'clone');
        clone_table.css({position:'fixed',
                 'pointer-events': 'none',
                 top:0});
        clone_table.width($("#maintable").width());
        $("#table-container").append(clone_table);
        $("#clone").css({visibility:'hidden'});
        $("#clone thead").css({'visibility':'visible','pointer-events':'auto'});
    }
    } else {
    $("#clone").remove();
    }
}
$(window).scroll(moveScroll); 

See here: http://jsfiddle.net/QHQGF/7/

Edit: updated the code so that the thead can receive pointer events(so buttons and links in the header still work). This fixes the problem reported by luhfluh and Joe M.

New jsfiddle here: http://jsfiddle.net/cjKEx/

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

From the documentation:

NOTE: Every corner must (initially) be provided a corner radius greater than 1, or else no corners are rounded. If you want specific corners to not be rounded, a work-around is to use android:radius to set a default corner radius greater than 1, but then override each and every corner with the values you really want, providing zero ("0dp") where you don't want rounded corners.

E.g. you have to set an android:radius="<bigger than 1dp>" to be able to do what you want:

<corners 
    android:radius="2dp"
    android:bottomRightRadius="0dp" 
    android:topRightRadius="0dp"/> 

How to submit a form using Enter key in react.js?

It's been quite a few years since this question was last answered. React introduced "Hooks" back in 2017, and "keyCode" has been deprecated.

Now we can write this:

  useEffect(() => {
    const listener = event => {
      if (event.code === "Enter" || event.code === "NumpadEnter") {
        console.log("Enter key was pressed. Run your function.");
        // callMyFunction();
      }
    };
    document.addEventListener("keydown", listener);
    return () => {
      document.removeEventListener("keydown", listener);
    };
  }, []);

This registers a listener on the keydown event, when the component is loaded for the first time. It removes the event listener when the component is destroyed.

How to comment and uncomment blocks of code in the Office VBA Editor

There is a built-in Edit toolbar in the VBA editor that has the Comment Block and Uncomment Block buttons by default, and other useful tools.

If you right-click any toolbar or menu (or go to the View menu > Toolbars), you will see a list of available toolbars (above the "Customize..." option). The Standard toolbar is selected by default. Select the Edit toolbar and the new toolbar will appear, with the Comment Block buttons in the middle.

enter image description here

*This is a simpler option to the ones mentioned.

C++, What does the colon after a constructor mean?

It's called an initialization list. An initializer list is how you pass arguments to your member variables' constructors and for passing arguments to the parent class's constructor.

If you use = to assign in the constructor body, first the default constructor is called, then the assignment operator is called. This is a bit wasteful, and sometimes there's no equivalent assignment operator.

Can someone explain the dollar sign in Javascript?

The $ sign is an identifier for variables and functions.

https://web.archive.org/web/20160529121559/http://www.authenticsociety.com/blog/javascript_dollarsign

That has a clear explanation of what the dollar sign is for.

Here's an alternative explanation: http://www.vcarrer.com/2010/10/about-dollar-sign-in-javascript.html

Force browser to clear cache

I had a case where I would take photos of clients online and would need to update the div if a photo is changed. Browser was still showing the old photo. So I used the hack of calling a random GET variable, which would be unique every time. Here it is if it could help anybody

<img src="/photos/userid_73.jpg?random=<?php echo rand() ?>" ...

EDIT As pointed out by others, following is much more efficient solution since it will reload images only when they are changed, identifying this change by the file size:

<img src="/photos/userid_73.jpg?modified=<? filemtime("/photos/userid_73.jpg")?>"

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code and start over.

For a slightly easier approach, you can use ast.parse module to parse the expression, and then the ast.NodeVisitor or ast.NodeTransformer to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile and eval to get the result.

The code is a bit different from literal_eval in that this code actually uses eval, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__ is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num (float and integer), list and dictionary literals.

Also, works the same on 2.7 and 3.3

import ast
import decimal

source = "(Decimal('11.66985'), Decimal('1e-8'),"\
    "(1,), (1,2,3), 1.2, [1,2,3], {1:2})"

tree = ast.parse(source, mode='eval')

# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
    ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
    ALLOWED_NODE_TYPES = set([
        'Expression', # a top node for an expression
        'Tuple',      # makes a tuple
        'Call',       # a function call (hint, Decimal())
        'Name',       # an identifier...
        'Load',       # loads a value of a variable with given identifier
        'Str',        # a string literal

        'Num',        # allow numbers too
        'List',       # and list literals
        'Dict',       # and dicts...
    ])

    def visit_Name(self, node):
        if not node.id in self.ALLOWED_NAMES:
            raise RuntimeError("Name access to %s is not allowed" % node.id)

        # traverse to child nodes
        return self.generic_visit(node)

    def generic_visit(self, node):
        nodetype = type(node).__name__
        if nodetype not in self.ALLOWED_NODE_TYPES:
            raise RuntimeError("Invalid expression: %s not allowed" % nodetype)

        return ast.NodeTransformer.generic_visit(self, node)


transformer = Transformer()

# raises RuntimeError on invalid code
transformer.visit(tree)

# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')

# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))

print(result)

List all files in one directory PHP

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

Why is 1/1/1970 the "epoch time"?

Short answer: Why not?

Longer answer: The time itself doesn't really matter, as long as everyone who uses it agrees on its value. As 1/1/70 has been in use for so long, using it will make you code as understandable as possible for as many people as possible.

There's no great merit in choosing an arbitrary epoch just to be different.

How to implement the factory method pattern in C++ correctly

Simple Factory Example:

// Factory returns object and ownership
// Caller responsible for deletion.
#include <memory>
class FactoryReleaseOwnership{
  public:
    std::unique_ptr<Foo> createFooInSomeWay(){
      return std::unique_ptr<Foo>(new Foo(some, args));
    }
};

// Factory retains object ownership
// Thus returning a reference.
#include <boost/ptr_container/ptr_vector.hpp>
class FactoryRetainOwnership{
  boost::ptr_vector<Foo>  myFoo;
  public:
    Foo& createFooInSomeWay(){
      // Must take care that factory last longer than all references.
      // Could make myFoo static so it last as long as the application.
      myFoo.push_back(new Foo(some, args));
      return myFoo.back();
    }
};

Access elements in json object like an array

The your seems a multi-array, not a JSON object.

If you want access the object like an array, you have to use some sort of key/value, such as:

var JSONObject = {
  "city": ["Blankaholm, "Gamleby"],
  "date": ["2012-10-23", "2012-10-22"],
  "description": ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
  "lat": ["57.586174","16.521841"], 
  "long": ["57.893162","16.406090"]
}

and access it with:

JSONObject.city[0] // => Blankaholm
JSONObject.date[1] // => 2012-10-22

and so on...

or

JSONObject['city'][0] // => Blankaholm
JSONObject['date'][1] // => 2012-10-22

and so on...

or, in last resort, if you don't want change your structure, you can do something like that:

var JSONObject = {
  "data": [
    ["Blankaholm, "Gamleby"],
    ["2012-10-23", "2012-10-22"],
    ["Blankaholm. Under natten har det varit inbrott", "E22 i med Gamleby. Singelolycka. En bilist har.],
    ["57.586174","16.521841"], 
    ["57.893162","16.406090"]
  ]
}

JSONObject.data[0][1] // => Gambleby

How to check if a symlink exists

If you are testing for file existence you want -e not -L. -L tests for a symlink.

RegEx match open tags except XHTML self-contained tags

RegEx match open tags except XHTML self-contained tags
All other tags (and content) are skipped.


This regex does that. If you need to match only specific Open tags, make a list
in an alternation (?:p|br|<whatever tags you want>) and replace the [\w:]+ construct
in the appropriate place below.

<(?:(?:(?:(script|style|object|embed|applet|noframes|noscript|noembed)(?:\s+(?>"[\S\s]*?"|'[\S\s]*?'|(?:(?!/>)[^>])?)+)?\s*>)[\S\s]*?</\1\s*(?=>)(*SKIP)(*FAIL))|(?:[\w:]+\b(?=((?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)*)>)\2(?<!/))|(?:(?:/?[\w:]+\s*/?)|(?:[\w:]+\s+(?:"[\S\s]*?"|'[\S\s]*?'|[^>]?)+\s*/?)|\?[\S\s]*?\?|(?:!(?:(?:DOCTYPE[\S\s]*?)|(?:\[CDATA\[[\S\s]*?\]\])|(?:--[\S\s]*?--)|(?:ATTLIST[\S\s]*?)|(?:ENTITY[\S\s]*?)|(?:ELEMENT[\S\s]*?))))(*SKIP)(*FAIL))>

https://regex101.com/r/uMvJn0/1

 # Mix html/xml     
 # https://regex101.com/r/uMvJn0/1     
 
 <
 (?:
    
    # Invisible content gets failed
    
    (?:
       (?:
                               # Invisible content; end tag req'd
          (                    # (1 start)
             script
           | style
           | object
           | embed
           | applet
           | noframes
           | noscript
           | noembed 
          )                    # (1 end)
          (?:
             \s+ 
             (?>
                " [\S\s]*? "
              | ' [\S\s]*? '
              | (?:
                   (?! /> )
                   [^>] 
                )?
             )+
          )?
          \s* >
       )
       
       [\S\s]*? </ \1 \s* 
       (?= > )
       (*SKIP)(*FAIL)
    )
    
  | 
    
    # This is any open html tag we will match
    
    (?:
       [\w:]+ \b 
       (?=
          (                    # (2 start)
             (?:
                " [\S\s]*? " 
              | ' [\S\s]*? ' 
              | [^>]? 
             )*
          )                    # (2 end)
          >
       )
       \2 
       (?<! / )
    )
    
  | 
    # All other tags get failed
    
    (?:
       (?: /? [\w:]+ \s* /? )
     | (?:
          [\w:]+ 
          \s+ 
          (?:
             " [\S\s]*? " 
           | ' [\S\s]*? ' 
           | [^>]? 
          )+
          \s* /?
       )
     | \? [\S\s]*? \?
     | (?:
          !
          (?:
             (?: DOCTYPE [\S\s]*? )
           | (?: \[CDATA\[ [\S\s]*? \]\] )
           | (?: -- [\S\s]*? -- )
           | (?: ATTLIST [\S\s]*? )
           | (?: ENTITY [\S\s]*? )
           | (?: ELEMENT [\S\s]*? )
          )
       )
    )
    (*SKIP)(*FAIL)
 )
 >

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

This example might help you. by using simple casting you can get code behind urdu character.

string str = "?????";
        char ch = ' ';
        int number = 0;
        for (int i = 0; i < str.Length; i++)
        {
            ch = str[i];
            number = (int)ch;
            Console.WriteLine(number);
        }

How do I correctly detect orientation change using Phonegap on iOS?

I believe that the correct answer has already been posted and accepted, yet there is an issue that I have experienced myself and that some others have mentioned here.

On certain platforms, various properties such as window dimensions (window.innerWidth, window.innerHeight) and the window.orientation property will not be updated by the time that the event "orientationchange" has fired. Many times, the property window.orientation is undefined for a few milliseconds after the firing of "orientationchange" (at least it is in Chrome on iOS).

The best way that I found to handle this issue was:

var handleOrientationChange = (function() {
    var struct = function(){
        struct.parse();
    };
    struct.showPortraitView = function(){
        alert("Portrait Orientation: " + window.orientation);
    };
    struct.showLandscapeView = function(){
        alert("Landscape Orientation: " + window.orientation);
    };
    struct.parse = function(){
        switch(window.orientation){
            case 0:
                    //Portrait Orientation
                    this.showPortraitView();
                break;
            default:
                    //Landscape Orientation
                    if(!parseInt(window.orientation) 
                    || window.orientation === this.lastOrientation)
                        setTimeout(this, 10);
                    else
                    {
                        this.lastOrientation = window.orientation;
                        this.showLandscapeView();
                    }
                break;
        }
    };
    struct.lastOrientation = window.orientation;
    return struct;
})();
window.addEventListener("orientationchange", handleOrientationChange, false);

I am checking to see if the orientation is either undefined or if the orientation is equal to the last orientation detected. If either is true, I wait ten milliseconds and then parse the orientation again. If the orientation is a proper value, I call the showXOrientation functions. If the orientation is invalid, I continue to loop my checking function, waiting ten milliseconds each time, until it is valid.

Now, I would make a JSFiddle for this, as I usually did, but JSFiddle has not been working for me and my support bug for it was closed as no one else is reporting the same problem. If anyone else wants to turn this into a JSFiddle, please go ahead.

Thanks! I hope this helps!

Remove Null Value from String array in java

Using Google's guava library

String[] firstArray = {"test1","","test2","test4","",null};

Iterable<String> st=Iterables.filter(Arrays.asList(firstArray),new Predicate<String>() {
    @Override
    public boolean apply(String arg0) {
        if(arg0==null) //avoid null strings 
            return false;
        if(arg0.length()==0) //avoid empty strings 
            return false;
        return true; // else true
    }
});

What is Common Gateway Interface (CGI)?

CGI is an interface specification between a web server (HTTP server) and an executable program of some type that is to handle a particular request.

It describes how certain properties of that request should be communicated to the environment of that program and how the program should communicate the response back to the server and how the server should 'complete' the response to form a valid reply to the original HTTP request.

For a while CGI was an IETF Internet Draft and as such had an expiry date. It expired with no update so there was no CGI 'standard'. It is now an informational RFC, but as such documents common practice and isn't a standard itself. rfc3875.txt, rfc3875.html

Programs implementing a CGI interface can be written in any language runnable on the target machine. They must be able to access environment variables and usually standard input and they generate their output on standard output.

Compiled languages such as C were commonly used as were scripting languages such as perl, often using libraries to make accessing the CGI environment easier.

One of the big disadvantages of CGI is that a new program is spawned for each request so maintaining state between requests could be a major performance issue. The state might be handled in cookies or encoded in a URL, but if it gets to large it must be stored elsewhere and keyed from encoded url information or a cookie. Each CGI invocation would then have to reload the stored state from a store somewhere.

For this reason, and for a greatly simple interface to requests and sessions, better integrated environments between web servers and applications are much more popular. Environments like a modern php implementation with apache integrate the target language much better with web server and provide access to request and sessions objects that are needed to efficiently serve http requests. They offer a much easier and richer way to write 'programs' to handle HTTP requests.

Whether you wrote a CGI script rather depends on interpretation. It certainly did the job of one but it is much more usual to run php as a module where the interface between the script and the server isn't strictly a CGI interface.

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

You are facing a double-encoding issue.

¦ and &#8226; are absolutely equivalent to each other. Both refer to the Unicode character 'BULLET' (U+2022) and can exist side-by-side in HTML source code.

However, if that source-code is HTML-encoded again at some point, it will contain ¦ and &amp;#8226;. The former is rendered unchanged, the latter will come out as "&#8226;" on the screen.

This is correct behavior under these circumstances. You need to find the point where the superfluous second HTML-encoding occurs and get rid of it.

Permissions error when connecting to EC2 via SSH on Mac OSx

Are you sure you have used the right instance? I ran into this problem and realized that something like 4 of the ubuntu instances i tried did not have SSH servers installed on them.

For a list of good servers see "Getting the images" about half way down. Sounds like you may be using something else... the default username is ubuntu on these images.

https://help.ubuntu.com/community/EC2StartersGuide

Set the maximum character length of a UITextField in Swift

Just in case, don't forget to guard range size before applying it to the string. Otherwise, you will get crash if the user will do this:

Type maximum length text Insert something (Nothing will be inserted due to length limitation, but iOS doesn't know about it) Undo insertion (You get crash, cause range will be greater than actual string size)

Also, using iOS 13 users can accidentally trigger this by gestures

I suggest you add to your project this

extension String {
    func replace(with text: String, in range: NSRange) -> String? {
        guard range.location + range.length <= self.count else { return nil }
        return (self as NSString).replacingCharacters(in: range, with: text)
    }
}

And use it like this:

func textView(_ textView: UITextView, shouldChangeTextIn range: NSRange, replacementText text: String) -> Bool {
    guard let newText = textView.text.replace(with: text, in: range) else { return false }
    return newText.count < maxNumberOfCharacters
}

Otherwise, you will constantly be getting crashed in your app

Switch on ranges of integers in JavaScript

function sequentialSizes(val) {
 var answer = "";

 switch (val){
case 1:
case 2:
case 3:
case 4:
  answer="Less than five";
  break;
case 5:
case 6:
case 7:
case 8:
  answer="less than 9";
  break;
case 8:
case 10:
case 11:
  answer="More than 10";
  break;
 }

return answer;  
}

// Change this value to test you code to confirm ;)
sequentialSizes(1);

How to convert entire dataframe to numeric while preserving decimals?

You might need to do some checking. You cannot safely convert factors directly to numeric. as.character must be applied first. Otherwise, the factors will be converted to their numeric storage values. I would check each column with is.factor then coerce to numeric as necessary.

df1[] <- lapply(df1, function(x) {
    if(is.factor(x)) as.numeric(as.character(x)) else x
})
sapply(df1, class)
#         a         b 
# "numeric" "numeric" 

Python pandas insert list into a cell

Since set_value has been deprecated since version 0.21.0, you should now use at. It can insert a list into a cell without raising a ValueError as loc does. I think this is because at always refers to a single value, while loc can refer to values as well as rows and columns.

df = pd.DataFrame(data={'A': [1, 2, 3], 'B': ['x', 'y', 'z']})

df.at[1, 'B'] = ['m', 'n']

df =
    A   B
0   1   x
1   2   [m, n]
2   3   z

You also need to make sure the column you are inserting into has dtype=object. For example

>>> df = pd.DataFrame(data={'A': [1, 2, 3], 'B': [1,2,3]})
>>> df.dtypes
A    int64
B    int64
dtype: object

>>> df.at[1, 'B'] = [1, 2, 3]
ValueError: setting an array element with a sequence

>>> df['B'] = df['B'].astype('object')
>>> df.at[1, 'B'] = [1, 2, 3]
>>> df
   A          B
0  1          1
1  2  [1, 2, 3]
2  3          3

Convert date yyyyMMdd to system.datetime format

string time = "19851231";
DateTime theTime= DateTime.ParseExact(time,
                                        "yyyyMMdd",
                                        CultureInfo.InvariantCulture,
                                        DateTimeStyles.None);

Google Play on Android 4.0 emulator

I do this in a more permanent way - instead of installing the APKs each time with adb, permanently add them to the system image that the emulator uses. You will need Yaffey on Windows, or a similar utility on other systems, to modify YAFFS2 images. Copy GoogleLoginService.apk, GoogleServicesFramework.apk, and Phonesky.apk (or Vending.apk in older versions of Android) to the /system/app folder of the system.img file of the emulator. Afterwards I can start the emulator normally, without messing with adb, and Play Store is always there.

Obtaining the Google Play app from your device

Downloading Google Apps from some Internet site may not be quite legal, but if you have a phone or tablet with a corresponding Android version, just pull them out of your device:

adb -d root
adb -d pull /system/app/GoogleLoginService.apk
adb -d pull /system/app/GoogleServicesFramework.apk
adb -d pull /system/app/Phonesky.apk

You must have root-level access (run adb root) to the device in order to pull these files from it.

Adding it to the image

Now start yaffey on Windows or a similar utility on Linux or Mac, and open system.img for the emulator image you want to modify. I modify most often the one in [...]\android-sdk\system-images\android-17\x86.

Rename the original system.img to system-original.img. Under yaffey, copy the APK files you pulled from your device to /app folder. Save your modified image as system.img in the original folder. Then start your emulator (in my case it would be Android 4.2 emulator with Intel Atom processor running under Intel HAX, super-fast on Windows machines) and you'll have Play Store there. I did not find it necessary to delete SdkSetup.apk and SdkSetup.odex - the Play Store and other services still work fine for me with these files present.

When finished with your testing, to alleviate your conscience guilty of temporarily pirating the Google Apps from your device, you may delete the modified system.img and restore the original from system-original.img.

Windows XP or later Windows: How can I run a batch file in the background with no window displayed?

Convert the batch file to an exe. Try Bat To Exe Converter or Online Bat To Exe Converter, and choose the option to run it as a ghost application, i.e. no window.

How to create a new figure in MATLAB?

The other thing to be careful about, is to use the clf (clear figure) command when you are starting a fresh plot. Otherwise you may be plotting on a pre-existing figure (not possible with the figure command by itself, but if you do figure(2) there may already be a figure #2), with more than one axis, or an axis that is placed kinda funny. Use clf to ensure that you're starting from scratch:

figure(N);
clf;
plot(something);
...

How do I iterate and modify Java Sets?

You can safely remove from a set during iteration with an Iterator object; attempting to modify a set through its API while iterating will break the iterator. the Set class provides an iterator through getIterator().

however, Integer objects are immutable; my strategy would be to iterate through the set and for each Integer i, add i+1 to some new temporary set. When you are finished iterating, remove all the elements from the original set and add all the elements of the new temporary set.

Set<Integer> s; //contains your Integers
...
Set<Integer> temp = new Set<Integer>();
for(Integer i : s)
    temp.add(i+1);
s.clear();
s.addAll(temp);

Execute and get the output of a shell command in node.js

If you're using node later than 7.6 and you don't like the callback style, you can also use node-util's promisify function with async / await to get shell commands which read cleanly. Here's an example of the accepted answer, using this technique:

const { promisify } = require('util');
const exec = promisify(require('child_process').exec)

module.exports.getGitUser = async function getGitUser () {
  const name = await exec('git config --global user.name')
  const email = await exec('git config --global user.email')
  return { name, email }
};

This also has the added benefit of returning a rejected promise on failed commands, which can be handled with try / catch inside the async code.

Error when trying to access XAMPP from a network

This answer is for XAMPP on Ubuntu.

The manual for installation and download is on (site official)

http://www.apachefriends.org/it/xampp-linux.html

After to start XAMPP simply call this command:

sudo /opt/lampp/lampp start

You should now see something like this on your screen:

Starting XAMPP 1.8.1...
LAMPP: Starting Apache...
LAMPP: Starting MySQL...
LAMPP started.

If you have this

Starting XAMPP for Linux 1.8.1...                                                             
XAMPP: Another web server daemon is already running.                                          
XAMPP: Another MySQL daemon is already running.                                               
XAMPP: Starting ProFTPD...                                                                    
XAMPP for Linux started

. The solution is

sudo /etc/init.d/apache2 stop
sudo /etc/init.d/mysql stop

And the restast with sudo //opt/lampp/lampp restart

You to fix most of the security weaknesses simply call the following command:

/opt/lampp/lampp security

After the change this file

sudo kate //opt/lampp/etc/extra/httpd-xampp.conf

Find and replace on

    #
# New XAMPP security concept
#
<LocationMatch "^/(?i:(?:xampp|security|licenses|phpmyadmin|webalizer|server-status|server-info))">
    Order deny,allow
    Deny from all
    Allow from ::1 127.0.0.0/8 
    Allow from all
    #\
    #   fc00::/7 10.0.0.0/8 172.16.0.0/12 192.168.0.0/16 \
    #   fe80::/10 169.254.0.0/16

    ErrorDocument 403 /error/XAMPP_FORBIDDEN.html.var
</LocationMatch>

How To fix white screen on app Start up?

You should read this great post by Cyril Mottier: Android App launching made gorgeous

You need to customise your Theme in style.xml and avoid to customise in your onCreate as ActionBar.setIcon/setTitle/etc.

See also the Documentation on Performance Tips by Google.

Use Trace View and Hierarchy Viewer to see the time to display your Views: Android Performance Optimization / Performance Tuning On Android

Use AsyncTask to display some views.

How to sort an STL vector?

this is my approach to solve this generally. It extends the answer from Steve Jessop by removing the requirement to set template arguments explicitly and adding the option to also use functoins and pointers to methods (getters)

#include <vector>
#include <iostream>
#include <algorithm>
#include <string>
#include <functional>

using namespace std;

template <typename T, typename U>
struct CompareByGetter {
    U (T::*getter)() const;
    CompareByGetter(U (T::*getter)() const) : getter(getter) {};
    bool operator()(const T &lhs, const T &rhs) {
        (lhs.*getter)() < (rhs.*getter)();
    }
};

template <typename T, typename U>
CompareByGetter<T,U> by(U (T::*getter)() const) {
    return CompareByGetter<T,U>(getter);
}

//// sort_by
template <typename T, typename U>
struct CompareByMember {
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

template <typename T, typename U>
CompareByMember<T,U> by(U T::*f) {
    return CompareByMember<T,U>(f);
}

template <typename T, typename U>
struct CompareByFunction {
    function<U(T)> f;
    CompareByFunction(function<U(T)> f) : f(f) {}
    bool operator()(const T& a, const T& b) const {
        return f(a) < f(b);
    }
};

template <typename T, typename U>
CompareByFunction<T,U> by(function<U(T)> f) {
    CompareByFunction<T,U> cmp{f};
    return cmp;
}

struct mystruct {
    double x,y,z;
    string name;
    double length() const {
        return sqrt( x*x + y*y + z*z );
    }
};

ostream& operator<< (ostream& os, const mystruct& ms) {
    return os << "{ " << ms.x << ", " << ms.y << ", " << ms.z << ", " << ms.name << " len: " << ms.length() << "}";
}

template <class T>
ostream& operator<< (ostream& os, std::vector<T> v) {
    os << "[";
    for (auto it = begin(v); it != end(v); ++it) {
        if ( it != begin(v) ) {
            os << " ";
        }
        os << *it;
    }
    os << "]";
    return os;
}

void sorting() {
    vector<mystruct> vec1 = { {1,1,0,"a"}, {0,1,2,"b"}, {-1,-5,0,"c"}, {0,0,0,"d"} };

    function<string(const mystruct&)> f = [](const mystruct& v){return v.name;};

    cout << "unsorted  " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::x) );
    cout << "sort_by x " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(&mystruct::length));
    cout << "sort_by len " << vec1 << endl;
    sort(begin(vec1), end(vec1), by(f) );
    cout << "sort_by name " << vec1 << endl;
}

Mongodb service won't start

I can't upvote/comment yet, but +1 for manually removing the lock file haha.

My C9 workspace crashed on me and triggered an unexpected shutdown. The API advises: https://docs.mongodb.com/manual/tutorial/recover-data-following-unexpected-shutdown/

.. but removing data/mongo.lock worked for me :).

Also, just in case you're getting a connection refusal (which happened to me), running the repair command before removing the lock file could solve your problem (it did mine).

sudo -u mongodb mongod --repair --dbpath /var/lib/mongodb/

Using a dictionary to select function to execute

def p1( ):
    print("in p1")

def p2():
    print("in p2")

myDict={
    "P1": p1,
    "P2": p2

}

name=input("enter P1 or P2")

myDictname

Delete the first three rows of a dataframe in pandas

df.drop(df.index[[0,2]])

Pandas uses zero based numbering, so 0 is the first row, 1 is the second row and 2 is the third row.

Setting initial values on load with Select2 with Ajax

The function which you are specifying as initSelection is called with the initial value as argument. So if value is empty, the function is not called.
When you specifiy value='[{"id":"IN","name":"India"}]' instead of data-initvalue the function gets called and the selection can get initialized.

ClassNotFoundException com.mysql.jdbc.Driver

see to it that the argument of Class. forName method is exactly "com. mysql. jdbc. Driver". If yes then see to it that mysql connector is present in lib folder of the project. if yes then see to it that the same mysql connector . jar file is in the ClassPath variable (system variable)..

Show Curl POST Request Headers? Is there a way to do this?

I had exactly the same problem lately, and I installed Wireshark (it is a network monitoring tool). You can see everything with this, except encrypted traffic (HTTPS).

Parse String date in (yyyy-MM-dd) format

tl;dr

LocalDate.parse( "2013-09-18" )

… and …

myLocalDate.toString()  // Example: 2013-09-18

java.time

The Question and other Answers are out-of-date. The troublesome old legacy date-time classes are now supplanted by the java.time classes.

ISO 8601

Your input string happens to comply with standard ISO 8601 format, YYYY-MM-DD. The java.time classes use ISO 8601 formats by default when parsing and generating string representations of date-time values. So no need to specify a formatting pattern.

LocalDate

The LocalDate class represents a date-only value without time-of-day and without time zone.

LocalDate ld = LocalDate.parse( "2013-09-18" );

About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval, YearWeek, YearQuarter, and more.

Floating divs in Bootstrap layout

From all I have read you cannot do exactly what you want without javascript. If you float left before text

<div style="float:left;">widget</div> here is some CONTENT, etc.

Your content wraps as expected. But your widget is in the top left. If you instead put the float after the content

here is some CONTENT, etc. <div style="float:left;">widget</div>

Then your content will wrap the last line to the right of the widget if the last line of content can fit to the right of the widget, otherwise no wrapping is done. To make borders and backgrounds actually include the floated area in the previous example, most people add:

here is some CONTENT, etc. <div style="float:left;">widget</div><div style="clear:both;"></div>

In your question you are using bootstrap which just adds row-fluid::after { content: ""} which resolves the border/background issue.

Moving your content up will give you the one line wrap : http://jsfiddle.net/jJNPY/34/

  <div class="container-fluid">
  <div class="row-fluid">
    <div class="offset1 span8 pull-right">
    ... Widget 1...
    </div>
    .... a lot of content ....
    <div class="span8" style="margin-left: 0;">
    ... Widget 2...
    </div>


  </div>

</div><!--/.fluid-container-->

Running javascript in Selenium using Python

Try browser.execute_script instead of selenium.GetEval.

See this answer for example.

How to adjust text font size to fit textview

If a tranformation like allCaps is set, speedplane's approach is buggy. I fixed it, resulting in the following code (sorry, my reputation does not allow me to add this as a comment to speedplane's solution):

import android.content.Context;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;

public class FontFitTextView extends TextView {

    public FontFitTextView(Context context) {
        super(context);
        initialise();
    }

    public FontFitTextView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initialise();
    }

    private void initialise() {
        mTestPaint = new Paint();
        mTestPaint.set(this.getPaint());
        //max size defaults to the initially specified text size unless it is too small
    }

    /* Re size the font so the specified text fits in the text box
     * assuming the text box is the specified width.
     */
    private void refitText(String text, int textWidth) 
    { 
        if (getTransformationMethod() != null) {
            text = getTransformationMethod().getTransformation(text, this).toString();
        }

        if (textWidth <= 0)
            return;
        int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
        float hi = 100;
        float lo = 2;
        final float threshold = 0.5f; // How close we have to be

        mTestPaint.set(this.getPaint());

        while((hi - lo) > threshold) {
            float size = (hi+lo)/2;
            if(mTestPaint.measureText(text) >= targetWidth) 
                hi = size; // too big
            else
                lo = size; // too small
        }
        // Use lo so that we undershoot rather than overshoot
        this.setTextSize(TypedValue.COMPLEX_UNIT_PX, lo);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
    {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
        int height = getMeasuredHeight();
        refitText(this.getText().toString(), parentWidth);
        this.setMeasuredDimension(parentWidth, height);
    }

    @Override
    protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
        refitText(text.toString(), this.getWidth());
    }

    @Override
    protected void onSizeChanged (int w, int h, int oldw, int oldh) {
        if (w != oldw) {
            refitText(this.getText().toString(), w);
      }
    }

    //Attributes
    private Paint mTestPaint;
}

Returning http status code from Web Api controller

I did not know the answer so asked the ASP.NET team here.

So the trick is to change the signature to HttpResponseMessage and use Request.CreateResponse.

[ResponseType(typeof(User))]
public HttpResponseMessage GetUser(HttpRequestMessage request, int userId, DateTime lastModifiedAtClient)
{
    var user = new DataEntities().Users.First(p => p.Id == userId);
    if (user.LastModified <= lastModifiedAtClient)
    {
         return new HttpResponseMessage(HttpStatusCode.NotModified);
    }
    return request.CreateResponse(HttpStatusCode.OK, user);
}

How to select distinct rows in a datatable and store into an array

DataTable dtbs = new DataTable(); 
DataView dvbs = new DataView(dt); 
dvbs.RowFilter = "ColumnName='Filtervalue'"; 
dtbs = dvbs.ToTable();

How to avoid annoying error "declared and not used"

In case others have a hard time making sense of this, I think it might help to explain it in very straightforward terms. If you have a variable that you don't use, for example a function for which you've commented out the invocation (a common use-case):

myFn := func () { }
// myFn()

You can assign a useless/blank variable to the function so that it's no longer unused:

myFn := func () { }
_ = myFn
// myFn()

Eclipse CDT: no rule to make target all

I just solved this exact issue for myself; even referenced this question.

I'm assuming you haven't written the "all" rule that Eclipse is complaining about. If this is the case, take these steps:

  1. Go to Project Properties > C/C++ Build > Behaviour Tab.
  2. Leave Build (Incremental Build) Checked.
  3. Remove "all" from the text box next to Build (Incremental Build).
  4. Compile away!

This lets Eclipse know you aren't trying to use a make target called "all". For some reason, that is the default.

Submitting form and pass data to controller method of type FileStreamResult

When in doubt, follow MVC conventions.

Create a viewModel if you haven't already that contains a property for JobID

public class Model
{
     public string JobId {get; set;}
     public IEnumerable<MyCurrentModel> myCurrentModel { get; set; }
     //...any other properties you may need
}

Strongly type your view

@model Fully.Qualified.Path.To.Model

Add a hidden field for JobId to the form

using (@Html.BeginForm("myMethod", "Home", FormMethod.Post))
{   
    //...    
    @Html.HiddenFor(m => m.JobId)
}

And accept the model as the parameter in your controller action:

[HttpPost]
public FileStreamResult myMethod(Model model)
{
    sting str = model.JobId;
}

Array to Collection: Optimized code

You can use:

list.addAll(Arrays.asList(array));

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Your code is correct. Kindly mark small correction.

#rightcolumn {
     width: 750px;
     background-color: #777;
     display: block;
     **float: left;(wrong)**
     **float: right; (corrected)**
     border: 1px solid white;
}

Insert text with single quotes in PostgreSQL

In postgresql if you want to insert values with ' in it then for this you have to give extra '

 insert into test values (1,'user''s log');
 insert into test values (2,'''my users''');
 insert into test values (3,'customer''s');

Git error: "Please make sure you have the correct access rights and the repository exists"

Strangely I only received this error in 1 of my many repos.

My issue was after installing the new GitHub Desktop for Windows where the previous old GitHub for Win kept keys in ~/.ssh/github_rsa and ~/.ssh/github_rsa.pub where as the new GitHub for Win expects it in ~/.ssh/id_rsa so the solution was just renaming the existing private and public keys:

~/.ssh/github_rsa -> ~/.ssh/id_rsa
~/.ssh/github_rsa.pub -> ~/.ssh/id_rsa.pub

After which let me access the repo again without issue.

Check if a given key already exists in a dictionary

Using ternary operator:

message = "blah" if 'key1' in dict else "booh"
print(message)

Find CRLF in Notepad++

If you need to do a complex regexp replacement including \r\n, you can workaround the limitation by a three-step approach:

  1. Replace all \r\n by a tag, let's say #GO# ? Check 'Extended', replace \r\n by #GO#
  2. Perform your regexp, example removing multiline ICON="*" from an html bookmarks ? Check regexp, replace ICON=.[^"]+.> by >
  3. Put back \r\n ? Check 'Extended', replace #GO# by \r\n

ERROR 1064 (42000) in MySQL

If the line before your error contains COMMENT '' either populate the comment in the script or remove the empty comment definition. I've found this in scripts generated by MySQL Workbench.

PHP Fatal error: Call to undefined function mssql_connect()

I have just tried to install that extension on my dev server.

First, make sure that the extension is correctly enabled. Your phpinfo() output doesn't seem complete.

If it is indeed installed properly, your phpinfo() should have a section that looks like this: enter image description here

If you do not get that section in your phpinfo(). Make sure that you are using the right version. There are both non-thread-safe and thread-safe versions of the extension.

Finally, check your extension_dir setting. By default it's this: extension_dir = "ext", for most of the time it works fine, but if it doesn't try: extension_dir = "C:\PHP\ext".

===========================================================================

EDIT given new info:

You are using the wrong function. mssql_connect() is part of the Mssql extension. You are using microsoft's extension, so use sqlsrv_connect(), for the API for the microsoft driver, look at SQLSRV_Help.chm which should be extracted to your ext directory when you extracted the extension.

Android button onClickListener

Use OnClicklistener or you can use android:onClick="myMethod" in your button's xml code from which you going to open a new layout. So when that button is clicked your myMethod function will be called automatically. Your myMethod function in class look like this.

public void myMethod(View v) {
Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
}

And in that SecondActivity.class set new layout in contentview.

Remove file extension from a file name string

The Path.GetFileNameWithoutExtension method gives you the filename you pass as an argument without the extension, as should be obvious from the name.

How to select rows that have current day's timestamp?

Or you could use the CURRENT_DATE alternative, with the same result:

SELECT * FROM yourtable WHERE created >= CURRENT_DATE

Examples from database.guide

Laravel Migration Error: Syntax error or access violation: 1071 Specified key was too long; max key length is 767 bytes

As outlined in the Migrations guide to fix this, all you have to do is edit your app/Providers/AppServiceProvider.php file and inside the boot method set a default string length:

use Illuminate\Support\Facades\Schema;

public function boot()
{
    Schema::defaultStringLength(191);
}

Note: first you have to delete (if you have) users table, password_resets table from the database and delete users and password_resets entries from migrations table.

To run all of your outstanding migrations, execute the migrate Artisan command:

php artisan migrate

After that everything should work as normal.

jQuery load more data on scroll

Improving on @deepakssn answer. There is a possibility that you want the data to load a bit before we actually scroll to the bottom.

var scrollLoad = true;
$(window).scroll(function(){
 if (scrollLoad && ($(document).height() - $(window).height())-$(window).scrollTop()<=800){
    // fetch data when we are 800px above the document end
    scrollLoad = false;
   }
  });

[var scrollLoad] is used to block the call until one new data is appended.

Hope this helps.

How can I use "e" (Euler's number) and power operation in python 2.7

math.e or from math import e (= 2.718281…)

The two expressions math.exp(x) and e**x are equivalent however:
Return e raised to the power x, where e = 2.718281… is the base of natural logarithms. This is usually more accurate than math.e ** x or pow(math.e, x). docs.python

for power use ** (3**2 = 9), not " ^ "
" ^ " is a bitwise XOR operator (& and, | or), it works logicaly with bits. So for example 10^4=14 (maybe unexpectedly) ? consider the bitwise depiction:

(0000 1010 ^ 0000 0100 = 0000 1110) programiz

View array in Visual Studio debugger?

If you have a large array and only want to see a subsection of the array you can type this into the watch window;

ptr+100,10

to show a list of the 10 elements starting at ptr[100]. Beware that the displayed array subscripts will start at [0], so you will have to remember that ptr[0] is really ptr[100] and ptr[1] is ptr[101] etc.

Javascript get object key name

This might be better understood if you modified the wording up a bit:

var buttons = {
  foo: 'bar',
  fiz: 'buz'
};

for ( var property in buttons ) {
  console.log( property ); // Outputs: foo, fiz or fiz, foo
}

Note here that you're iterating over the properties of the object, using property as a reference to each during each subsequent cycle.

MSDN says of for ( variable in [object | array ] ) the following:

Before each iteration of a loop, variable is assigned the next property name of object or the next element index of array. You can then use it in any of the statements inside the loop to reference the property of object or the element of array.

Note also that the property order of an object is not constant, and can change, unlike the index order of an array. That might come in handy.

Uploading both data and files in one form using Ajax?

The problem I had was using the wrong jQuery identifier.

You can upload data and files with one form using ajax.

PHP + HTML

<?php

print_r($_POST);
print_r($_FILES);
?>

<form id="data" method="post" enctype="multipart/form-data">
    <input type="text" name="first" value="Bob" />
    <input type="text" name="middle" value="James" />
    <input type="text" name="last" value="Smith" />
    <input name="image" type="file" />
    <button>Submit</button>
</form>

jQuery + Ajax

$("form#data").submit(function(e) {
    e.preventDefault();    
    var formData = new FormData(this);

    $.ajax({
        url: window.location.pathname,
        type: 'POST',
        data: formData,
        success: function (data) {
            alert(data)
        },
        cache: false,
        contentType: false,
        processData: false
    });
});

Short Version

$("form#data").submit(function(e) {
    e.preventDefault();
    var formData = new FormData(this);    

    $.post($(this).attr("action"), formData, function(data) {
        alert(data);
    });
});

Android: ListView elements with multiple clickable buttons

I Know it's late but this may help, this is an example how I write custom adapter class for different click actions

 public class CustomAdapter extends BaseAdapter {

    TextView title;
  Button button1,button2;

    public long getItemId(int position) {
        return position;
    }

    public int getCount() {
        return mAlBasicItemsnav.size();  // size of your list array
    }

    public Object getItem(int position) {
        return position;
    }

    public View getView(int position, View convertView, ViewGroup parent) {

        if (convertView == null) {
            convertView = getLayoutInflater().inflate(R.layout.listnavsub_layout, null, false); // use sublayout which you want to inflate in your each list item
        }

        title = (TextView) convertView.findViewById(R.id.textViewnav); // see you have to find id by using convertView.findViewById 
        title.setText(mAlBasicItemsnav.get(position));
      button1=(Button) convertView.findViewById(R.id.button1);
      button1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

           // if you have different click action at different positions then
            if(position==0)
              {
                       //click action of 1st list item on button click
        }
           if(position==1)
              {
                       //click action of 2st list item on button click
        }
    });

 // similarly for button 2

   button2=(Button) convertView.findViewById(R.id.button2);
      button2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            //your click action 

    });



        return convertView;
    }
}

java.sql.SQLException: Access denied for user 'root'@'localhost' (using password: YES)

If you are connecting a remote mysql server from your local machine using java see the below steps. Error : "java.sql.SQLException: Access denied for user 'xxxxx'@'101.123.163.141' (using password: YES) "

for remote access may be cpanel or others grant the remote access for your local ip address.

In the above error message: "101.123.163.141" is my local machine ip. So First we have to give remote access in the Cpanel-> Remote MySQL®. Then run your application to connect.

Class.forName("com.mysql.jdbc.Driver");  
Connection con=DriverManager.getConnection(  
    "jdbc:mysql://www.xyz.com/abc","def","ghi");  
//here abc is database name, def is username and ghi        
Statement stmt=con.createStatement();  
ResultSet rs=stmt.executeQuery("select * from employee");  
    while(rs.next())  
        System.out.println(rs.getInt(1)+" "+rs.getString(2)+"  
                          "+rs.getString(3));  
con.close();    

Hope it will resolve your issue.

Thanks

Why can templates only be implemented in the header file?

Plenty correct answers here, but I wanted to add this (for completeness):

If you, at the bottom of the implementation cpp file, do explicit instantiation of all the types the template will be used with, the linker will be able to find them as usual.

Edit: Adding example of explicit template instantiation. Used after the template has been defined, and all member functions has been defined.

template class vector<int>;

This will instantiate (and thus make available to the linker) the class and all its member functions (only). Similar syntax works for template functions, so if you have non-member operator overloads you may need to do the same for those.

The above example is fairly useless since vector is fully defined in headers, except when a common include file (precompiled header?) uses extern template class vector<int> so as to keep it from instantiating it in all the other (1000?) files that use vector.

How do I initialize the base (super) class?

Both

SuperClass.__init__(self, x)

or

super(SubClass,self).__init__( x )

will work (I prefer the 2nd one, as it adheres more to the DRY principle).

See here: http://docs.python.org/reference/datamodel.html#basic-customization

Send and receive messages through NSNotificationCenter in Objective-C?

This one helped me:

// Add an observer that will respond to loginComplete
[[NSNotificationCenter defaultCenter] addObserver:self 
                                             selector:@selector(showMainMenu:) 
                                                 name:@"loginComplete" object:nil];


// Post a notification to loginComplete
[[NSNotificationCenter defaultCenter] postNotificationName:@"loginComplete" object:nil];


// the function specified in the same class where we defined the addObserver
- (void)showMainMenu:(NSNotification *)note {
    NSLog(@"Received Notification - Someone seems to have logged in"); 
}

Source: http://www.smipple.net/snippet/Sounden/Simple%20NSNotificationCenter%20example

In Java, how do you determine if a thread is running?

You can use: Thread.currentThread().isAlive();. Returns true if this thread is alive; false otherwise.

sys.path different in Jupyter and Python - how to import own modules in Jupyter?

The verified solution doesn't work for me, since my notebook is not in my sys.path. This works however;

import os,sys
sys.path.insert(1, os.path.join(os.getcwd()  , '..'))

Does Java support structs?

Java definitively has no structs :) But what you describe here looks like a JavaBean kind of class.

How to change owner of PostgreSql database?

ALTER DATABASE name OWNER TO new_owner;

See the Postgresql manual's entry on this for more details.

fatal error LNK1104: cannot open file 'kernel32.lib'

I got a similar error, the problem stopped when I checked my "Linker -> Input -> Additional Dependencies" list in the project properties. I was missing a semi colon ";" just before "%(AdditionalDependencies)". I also had the same entry in twice. You should edit this list separately for Debug and Release.

Convert a Unix timestamp to time in JavaScript

Using Moment.js, you can get time and date like this:

var dateTimeString = moment(1439198499).format("DD-MM-YYYY HH:mm:ss");

And you can get only time using this:

var timeString = moment(1439198499).format("HH:mm:ss");

Prevent flicker on webkit-transition of webkit-transform

I had to use:

-webkit-perspective: 1000;
-webkit-backface-visibility: hidden;    

on the element, or I would still get a flickr the first time a transition occurred after page load

Font.createFont(..) set color and size (java.awt.Font)

To set the color of a font, you must first initialize the color by doing this:

Color maroon = new Color (128, 0, 0);

Once you've done that, you then put:

Font font = new Font ("Courier New", 1, 25); //Initializes the font
c.setColor (maroon); //Sets the color of the font
c.setFont (font); //Sets the font
c.drawString ("Your text here", locationX, locationY); //Outputs the string

Note: The 1 represents the type of font and this can be used to replace Font.PLAIN and the 25 represents the size of your font.

Python socket.error: [Errno 111] Connection refused

The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND command on another connection, but it apparently was "not opening [it] up in sync with the client side".

Well, the main reason would be there was no synchronisation whatsoever. Calling:

cs.send("SEND " + FILE)
cs.close()

would just place the data into a OS buffer; close would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep after close might mitigate the problem, but this is not synchronisation.

The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK, or better PORT 36250 to indicate where to connect). This would make sure the server is already listening.

The other thing is you must check the return values of send to make sure how many bytes was taken from your buffer. Or use sendall.

(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)

HTTP Status 504

One thing I have observed regarding this error is that is appears only for the first response from the server, which in case of http should be the handshake response. Once an immediate response is sent from the server to the gateway, if after the main response takes time it does not give an error. The key here is that the first response on a request by a server should be fast.

How to check if an app is installed from a web-page on an iPhone?

@Alistair pointed out in this answer that sometimes users will return to the browser after opening the app. A commenter to that answer indicated that the times values used had to be changed depending on iOS version. When our team had to deal with this, we found that the time values for the initial timeout and telling whether we had returned to the browser had to be tuned, and often didn't work for all users and devices.

Rather than using an arbitrary time difference threshold to determine whether we had returned to the browser, it made sense to detect the "pagehide" and "pageshow" events.

I developed the following web page to help diagnose what was going on. It adds HTML diagnostics as the events unfold, mainly because using techniques like console logging, alerts, or Web Inspector, jsfiddle.net etc all had their drawbacks in this work flow. Rather than using a time threshold, the Javascript counts the number of "pagehide" and "pageshow" events to see whether they have occurred. And I found that the most robust strategy was to use an initial timeout of 1000 (rather than the 25, 50, or 100 reported/suggested by others).

This can be served on a local server, e.g. python -m SimpleHTTPServer and viewed on iOS Safari.

To play with it, press either the "Open an installed app" or "App not installed" links. These links should cause respectively the Maps app or the App Store to open. You can then return to Safari to see the sequence and timing of the events.

(Note: this will work for Safari only. For other browsers (like Chrome) you'd have to install handlers for the pagehide/show-equivalent events).

Update: As @Mikko has pointed out in the comments, the pageshow/pagehide events we are using are apparently no longer supported in iOS8.

<html>
<head>
</head>
<body>
<a href="maps://" onclick="clickHandler()">Open an installed app</a>
<br/><br/>
<a href="xmapsx://" onclick="clickHandler()">App not installed</a>
<br/>

<script>

var hideShowCount = 0 ;
window.addEventListener("pagehide", function() {
    hideShowCount++ ;
    showEventTime('pagehide') ;
});

window.addEventListener("pageshow", function() {
    hideShowCount++ ;
    showEventTime('pageshow') ;
});

function clickHandler(){
    var hideShowCountAtClick = hideShowCount ;
    showEventTime('click') ;
    setTimeout(function () {
               showEventTime('timeout function '+(hideShowCount-hideShowCountAtClick)+' hide/show events') ;
               if (hideShowCount == hideShowCountAtClick){
                    // app is not installed, go to App Store
                    window.location = 'http://itunes.apple.com/app' ;
               }
            }, 1000);
}

function currentTime()
{
    return Date.now()/1000 ;
}

function showEventTime(event){
    var time = currentTime() ;
    document.body.appendChild(document.createElement('br'));
    document.body.appendChild(document.createTextNode(time+' '+event));
}
</script>
</body>
</html>

Android ACTION_IMAGE_CAPTURE Intent

I had the same problem where the OK button in camera app did nothing, both on emulator and on nexus one.

The problem went away after specifying a safe filename that is without white spaces, without special characters, in MediaStore.EXTRA_OUTPUT Also, if you are specifying a file that resides in a directory that has not yet been created, you have to create it first. Camera app doesn't do mkdir for you.

Add text to Existing PDF using Python

You may have better luck breaking the problem down into converting PDF into an editable format, writing your changes, then converting it back into PDF. I don't know of a library that lets you directly edit PDF but there are plenty of converters between DOC and PDF for example.

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

As of Amazon Linux version 2017.09 python 3.6 is now available:

sudo yum install python36 python36-virtualenv python36-pip

See the Release Notes for more info and other packages

WSDL/SOAP Test With soapui

You can try opening the wsdl in web browser and saving with .wsdl extension. And set the WSDL in SOAP UI project to this .wsdl file. This really works.

Pandas: sum DataFrame rows for given columns

You can simply pass your dataframe into the following function:

def sum_frame_by_column(frame, new_col_name, list_of_cols_to_sum):
    frame[new_col_name] = frame[list_of_cols_to_sum].astype(float).sum(axis=1)
    return(frame)

Example:

I have a dataframe (awards_frame) as follows:

enter image description here

...and I want to create a new column that shows the sum of awards for each row:

Usage:

I simply pass my awards_frame into the function, also specifying the name of the new column, and a list of column names that are to be summed:

sum_frame_by_column(awards_frame, 'award_sum', ['award_1','award_2','award_3'])

Result:

enter image description here

How to change column width in DataGridView?

You could set the width of the abbrev column to a fixed pixel width, then set the width of the description column to the width of the DataGridView, minus the sum of the widths of the other columns and some extra margin (if you want to prevent a horizontal scrollbar from appearing on the DataGridView):

dataGridView1.Columns[1].Width = 108;  // or whatever width works well for abbrev
dataGridView1.Columns[2].Width = 
    dataGridView1.Width 
    - dataGridView1.Columns[0].Width 
    - dataGridView1.Columns[1].Width 
    - 72;  // this is an extra "margin" number of pixels

If you wanted the description column to always take up the "remainder" of the width of the DataGridView, you could put something like the above code in a Resize event handler of the DataGridView.

get current url in twig template?

{{ path(app.request.attributes.get('_route'),
     app.request.attributes.get('_route_params')) }}

If you want to read it into a view variable:

{% set currentPath = path(app.request.attributes.get('_route'),
                       app.request.attributes.get('_route_params')) %}

The app global view variable contains all sorts of useful shortcuts, such as app.session and app.security.token.user, that reference the services you might use in a controller.

How to dynamically add a class to manual class names?

A simple possible syntax will be:

<div className={`wrapper searchDiv ${this.state.something}`}>

Forward request headers from nginx proxy server

If you want to pass the variable to your proxy backend, you have to set it with the proxy module.

location / {
    proxy_pass                      http://example.com;
    proxy_set_header                Host example.com;
    proxy_set_header                HTTP_Country-Code $geoip_country_code;
    proxy_pass_request_headers      on;
}

And now it's passed to the proxy backend.

How to test if a DataSet is empty?

You don't have to test the dataset.

The Fill() method returns the # of rows added.

See DbDataAdapter.Fill Method (DataSet)

Accessing an array out of bounds gives no error, why?

When you write 'array[index]' in C it translates it to machine instructions.

The translation is goes something like:

  1. 'get the address of array'
  2. 'get the size of the type of objects array is made up of'
  3. 'multiply the size of the type by index'
  4. 'add the result to the address of array'
  5. 'read what's at the resulting address'

The result addresses something which may, or may not, be part of the array. In exchange for the blazing speed of machine instructions you lose the safety net of the computer checking things for you. If you're meticulous and careful it's not a problem. If you're sloppy or make a mistake you get burnt. Sometimes it might generate an invalid instruction that causes an exception, sometimes not.

Open file with associated application

Just write

System.Diagnostics.Process.Start(@"file path");

example

System.Diagnostics.Process.Start(@"C:\foo.jpg");
System.Diagnostics.Process.Start(@"C:\foo.doc");
System.Diagnostics.Process.Start(@"C:\foo.dxf");
...

And shell will run associated program reading it from the registry, like usual double click does.

how to get curl to output only http response body (json) and no other headers etc

You are specifying the -i option:

-i, --include

(HTTP) Include the HTTP-header in the output. The HTTP-header includes things like server-name, date of the document, HTTP-version and more...

Simply remove that option from your command line:

response=$(curl -sb -H "Accept: application/json" "http://host:8080/some/resource")

How to start a Process as administrator mode in C#

Here is an example of run process as administrator without Windows Prompt

  Process p = new Process();
  p.StartInfo.FileName = Server.MapPath("process.exe");
  p.StartInfo.Arguments = "";
  p.StartInfo.UseShellExecute = false;
  p.StartInfo.CreateNoWindow = true;
  p.StartInfo.RedirectStandardOutput = true;
  p.StartInfo.Verb = "runas";
  p.Start();
  p.WaitForExit();

How do I check if an object has a key in JavaScript?

You should use hasOwnProperty. For example:

myObj.hasOwnProperty('myKey');

Note: If you are using ESLint, the above may give you an error for violating the no-prototype-builtins rule, in that case the workaround is as below:

Object.prototype.hasOwnProperty.call(myObj, 'myKey');

Twitter Bootstrap Multilevel Dropdown Menu

[Twitter Bootstrap v3]

To create a n-level dropdown menu (touch device friendly) in Twitter Bootstrap v3,

CSS:

.dropdown-menu>li /* To prevent selection of text */
{   position:relative;
    -webkit-user-select: none; /* Chrome/Safari */        
    -moz-user-select: none; /* Firefox */
    -ms-user-select: none; /* IE10+ */
    /* Rules below not implemented in browsers yet */
    -o-user-select: none;
    user-select: none;
    cursor:pointer;
}
.dropdown-menu .sub-menu 
{
    left: 100%;
    position: absolute;
    top: 0;
    display:none;
    margin-top: -1px;
    border-top-left-radius:0;
    border-bottom-left-radius:0;
    border-left-color:#fff;
    box-shadow:none;
}
.right-caret:after,.left-caret:after
 {  content:"";
    border-bottom: 5px solid transparent;
    border-top: 5px solid transparent;
    display: inline-block;
    height: 0;
    vertical-align: middle;
    width: 0;
    margin-left:5px;
}
.right-caret:after
{   border-left: 5px solid #ffaf46;
}
.left-caret:after
{   border-right: 5px solid #ffaf46;
}

JQuery:

$(function(){
    $(".dropdown-menu > li > a.trigger").on("click",function(e){
        var current=$(this).next();
        var grandparent=$(this).parent().parent();
        if($(this).hasClass('left-caret')||$(this).hasClass('right-caret'))
            $(this).toggleClass('right-caret left-caret');
        grandparent.find('.left-caret').not(this).toggleClass('right-caret left-caret');
        grandparent.find(".sub-menu:visible").not(current).hide();
        current.toggle();
        e.stopPropagation();
    });
    $(".dropdown-menu > li > a:not(.trigger)").on("click",function(){
        var root=$(this).closest('.dropdown');
        root.find('.left-caret').toggleClass('right-caret left-caret');
        root.find('.sub-menu:visible').hide();
    });
});

HTML:

<div class="dropdown" style="position:relative">
    <a href="#" class="btn btn-primary dropdown-toggle" data-toggle="dropdown">Click Here <span class="caret"></span></a>
    <ul class="dropdown-menu">
        <li>
            <a class="trigger right-caret">Level 1</a>
            <ul class="dropdown-menu sub-menu">
                <li><a href="#">Level 2</a></li>
                <li>
                    <a class="trigger right-caret">Level 2</a>
                    <ul class="dropdown-menu sub-menu">
                        <li><a href="#">Level 3</a></li>
                        <li><a href="#">Level 3</a></li>
                        <li>
                            <a class="trigger right-caret">Level 3</a>
                            <ul class="dropdown-menu sub-menu">
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                                <li><a href="#">Level 4</a></li>
                            </ul>
                        </li>
                    </ul>
                </li>
                <li><a href="#">Level 2</a></li>
            </ul>
        </li>
        <li><a href="#">Level 1</a></li>
        <li><a href="#">Level 1</a></li>
    </ul>
</div>

Setting up FTP on Amazon Cloud Server

To enable passive ftp on an EC2 server, you need to configure the ports that your ftp server should use for inbound connections, then open a list of available ports for the ftp client data connections.

I'm not that familiar with linux, but the commands you posted are the steps to install the ftp server, configure the ec2 firewall rules (through the AWS API), then configure the ftp server to use the ports you allowed on the ec2 firewall.

So this step installs the ftp client (VSFTP)

> yum install vsftpd

These steps configure the ftp client

> vi /etc/vsftpd/vsftpd.conf
--    Add following lines at the end of file --
     pasv_enable=YES
     pasv_min_port=1024
     pasv_max_port=1048
     pasv_address=<Public IP of your instance> 
> /etc/init.d/vsftpd restart

but the other two steps are easier done through the amazon console under EC2 Security groups. There you need to configure the security group that is assigned to your server to allow connections on ports 20,21, and 1024-1048

ERROR 1044 (42000): Access denied for 'root' With All Privileges

Try to comment string "sql-mode=..." in file my.cnf and than restart mysql.

Read text file into string. C++ ifstream

getline(fin, buffer, '\n')
where fin is opened file(ifstream object) and buffer is of string/char type where you want to copy line.

Mockito verify order / sequence of method calls

Note that you can also use the InOrder class to verify that various methods are called in order on a single mock, not just on two or more mocks.

Suppose I have two classes Foo and Bar:

public class Foo {
  public void first() {}
  public void second() {}
}

public class Bar {
  public void firstThenSecond(Foo foo) {
    foo.first();
    foo.second();
  }
}

I can then add a test class to test that Bar's firstThenSecond() method actually calls first(), then second(), and not second(), then first(). See the following test code:

public class BarTest {
  @Test
  public void testFirstThenSecond() {
    Bar bar = new Bar();
    Foo mockFoo = Mockito.mock(Foo.class);
    bar.firstThenSecond(mockFoo);

    InOrder orderVerifier = Mockito.inOrder(mockFoo);
    // These lines will PASS
    orderVerifier.verify(mockFoo).first();
    orderVerifier.verify(mockFoo).second();

    // These lines will FAIL
    // orderVerifier.verify(mockFoo).second();
    // orderVerifier.verify(mockFoo).first();
  }
}

What's the difference between HEAD, working tree and index, in Git?

The difference between HEAD (current branch or last committed state on current branch), index (aka. staging area) and working tree (the state of files in checkout) is described in "The Three States" section of the "1.3 Git Basics" chapter of Pro Git book by Scott Chacon (Creative Commons licensed).

Here is the image illustrating it from this chapter:

Local Operations - working directory vs. staging area (index) vs git repository (HEAD)

In the above image "working directory" is the same as "working tree", the "staging area" is an alternate name for git "index", and HEAD points to currently checked out branch, which tip points to last commit in the "git directory (repository)"

Note that git commit -a would stage changes and commit in one step.

access key and value of object using *ngFor

There's a real nice library that does this among other nice pipes. It's called ngx-pipes.

For example, keys pipe returns keys for an object, and values pipe returns values for an object:

keys pipe

<div *ngFor="let key of {foo: 1, bar: 2} | keys">{{key}}</div> 
<!-- Output: 'foo' and 'bar -->

values pipe

<div *ngFor="let value of {foo: 1, bar: 2} | values">{{value}}</div>
<!-- Output: 1 and 2 -->

No need to create your own custom pipe :)

Spring Boot + JPA : Column name annotation ignored

you have to follow some naming strategy when you work with spring jpa. The column name should be in lowercase or uppercase.

@Column(name="TESTNAME")
private String testName;

or

@Column(name="testname")
private String testName;

keep in mind that, if you have your column name "test_name" format in the database then you have to follow the following way

@Column(name="TestName")
private String testName;

or

@Column(name="TEST_NAME")
private String testName;

or

@Column(name="test_name")
private String testName;

What is a JavaBean exactly?

As per the Wikipedia:

  1. The class must have a public default constructor (with no arguments). This allows easy instantiation within editing and activation frameworks.

  2. The class properties must be accessible using get, set, is (can be used for boolean properties instead of get), and other methods (so-called accessor methods and mutator methods) according to a standard naming convention. This allows easy automated inspection and updating of bean state within frameworks, many of which include custom editors for various types of properties. Setters can have one or more than one argument.

  3. The class should be serializable. (This allows applications and frameworks to reliably save, store, and restore the bean's state in a manner independent of the VM and of the platform.)

For more information follow this link.