Programs & Examples On #Visual c++ 2010 express

The April 2010 release of Microsoft Visual C++ Express, a C and C++ compiler for Windows. The Express product is a free, scaled-down version of their main product.

PHP + curl, HTTP POST sample code?

A live example of using php curl_exec to do an HTTP post:

Put this in a file called foobar.php:

<?php
  $ch = curl_init();
  $skipper = "luxury assault recreational vehicle";
  $fields = array( 'penguins'=>$skipper, 'bestpony'=>'rainbowdash');
  $postvars = '';
  foreach($fields as $key=>$value) {
    $postvars .= $key . "=" . $value . "&";
  }
  $url = "http://www.google.com";
  curl_setopt($ch,CURLOPT_URL,$url);
  curl_setopt($ch,CURLOPT_POST, 1);                //0 for a get request
  curl_setopt($ch,CURLOPT_POSTFIELDS,$postvars);
  curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch,CURLOPT_CONNECTTIMEOUT ,3);
  curl_setopt($ch,CURLOPT_TIMEOUT, 20);
  $response = curl_exec($ch);
  print "curl response is:" . $response;
  curl_close ($ch);
?>

Then run it with the command php foobar.php, it dumps this kind of output to screen:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" 
"http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Title</title>

<meta http-equiv="Pragma" content="no-cache">
<meta http-equiv="Expires" content="0">
<body>
  A mountain of content...
</body>
</html>

So you did a PHP POST to www.google.com and sent it some data.

Had the server been programmed to read in the post variables, it could decide to do something different based upon that.

JQuery, select first row of table

late in the game , but this worked for me:

$("#container>table>tbody>tr:first").trigger('click');

PG COPY error: invalid input syntax for integer

I think it's better to change your csv file like:

"age","first_name","last_name"
23,Ivan,Poupkine
,Eugene,Pirogov

It's also possible to define your table like

CREATE TABLE people (
  age        varchar(20),
  first_name varchar(20),
  last_name  varchar(20)
);

and after copy, you can convert empty strings:

select nullif(age, '')::int as age, first_name, last_name
from people

Difference between parameter and argument

Argument is often used in the sense of actual argument vs. formal parameter.

The formal parameter is what is given in the function declaration/definition/prototype, while the actual argument is what is passed when calling the function — an instance of a formal parameter, if you will.

That being said, they are often used interchangeably, their exact use depending on different programming languages and their communities. For example, I have also heard actual parameter etc.

So here, x and y would be formal parameters:

int foo(int x, int y) {
    ...
}

Whereas here, in the function call, 5 and z are the actual arguments:

foo(5, z);

How do I create a shortcut via command-line in Windows?

You could use a PowerShell command. Stick this in your batch script and it'll create a shortcut to %~f0 in %userprofile%\Start Menu\Programs\Startup:

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\%~n0.lnk');$s.TargetPath='%~f0';$s.Save()"

If you prefer not to use PowerShell, you could use mklink to make a symbolic link. Syntax:

mklink saveShortcutAs targetOfShortcut

See mklink /? in a console window for full syntax, and this web page for further information.

In your batch script, do:

mklink "%userprofile%\Start Menu\Programs\Startup\%~nx0" "%~f0"

The shortcut created isn't a traditional .lnk file, but it should work the same nevertheless. Be advised that this will only work if the .bat file is run from the same drive as your startup folder. Also, apparently admin rights are required to create symbolic links.

What do hjust and vjust do when making a plot using ggplot?

The value of hjust and vjust are only defined between 0 and 1:

  • 0 means left-justified
  • 1 means right-justified

Source: ggplot2, Hadley Wickham, page 196

(Yes, I know that in most cases you can use it beyond this range, but don't expect it to behave in any specific way. This is outside spec.)

hjust controls horizontal justification and vjust controls vertical justification.

An example should make this clear:

td <- expand.grid(
    hjust=c(0, 0.5, 1),
    vjust=c(0, 0.5, 1),
    angle=c(0, 45, 90),
    text="text"
)

ggplot(td, aes(x=hjust, y=vjust)) + 
    geom_point() +
    geom_text(aes(label=text, angle=angle, hjust=hjust, vjust=vjust)) + 
    facet_grid(~angle) +
    scale_x_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2)) +
    scale_y_continuous(breaks=c(0, 0.5, 1), expand=c(0, 0.2))

enter image description here


To understand what happens when you change the hjust in axis text, you need to understand that the horizontal alignment for axis text is defined in relation not to the x-axis, but to the entire plot (where this includes the y-axis text). (This is, in my view, unfortunate. It would be much more useful to have the alignment relative to the axis.)

DF <- data.frame(x=LETTERS[1:3],y=1:3)
p <- ggplot(DF, aes(x,y)) + geom_point() + 
    ylab("Very long label for y") +
    theme(axis.title.y=element_text(angle=0))


p1 <- p + theme(axis.title.x=element_text(hjust=0)) + xlab("X-axis at hjust=0")
p2 <- p + theme(axis.title.x=element_text(hjust=0.5)) + xlab("X-axis at hjust=0.5")
p3 <- p + theme(axis.title.x=element_text(hjust=1)) + xlab("X-axis at hjust=1")

library(ggExtra)
align.plots(p1, p2, p3)

enter image description here


To explore what happens with vjust aligment of axis labels:

DF <- data.frame(x=c("a\na","b","cdefghijk","l"),y=1:4)
p <- ggplot(DF, aes(x,y)) + geom_point()

p1 <- p + theme(axis.text.x=element_text(vjust=0, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0")
p2 <- p + theme(axis.text.x=element_text(vjust=0.5, colour="red")) + 
        xlab("X-axis labels aligned with vjust=0.5")
p3 <- p + theme(axis.text.x=element_text(vjust=1, colour="red")) + 
        xlab("X-axis labels aligned with vjust=1")


library(ggExtra)
align.plots(p1, p2, p3)

enter image description here

How to validate domain credentials?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Security;
using System.DirectoryServices.AccountManagement;

public struct Credentials
{
    public string Username;
    public string Password;
}

public class Domain_Authentication
{
    public Credentials Credentials;
    public string Domain;

    public Domain_Authentication(string Username, string Password, string SDomain)
    {
        Credentials.Username = Username;
        Credentials.Password = Password;
        Domain = SDomain;
    }

    public bool IsValid()
    {
        using (PrincipalContext pc = new PrincipalContext(ContextType.Domain, Domain))
        {
            // validate the credentials
            return pc.ValidateCredentials(Credentials.Username, Credentials.Password);
        }
    }
}

Cannot overwrite model once compiled Mongoose

The schema definition should be unique for a collection, it should not be more then one schema for a collection.

Turning off hibernate logging console output

Important notice: the property (part of hibernate configuration, NOT part of logging framework config!)

hibernate.show_sql

controls the logging directly to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like log4j, you should always set that property to false because it gives you no benefit at all.

That circumstance irritated me quite a long time because I never really cared about it until I tried to write some benchmark regarding Hibernate.

Checking if a variable is an integer in PHP

When the browser sends p in the querystring, it is received as a string, not an int. is_int() will therefore always return false.

Instead try is_numeric() or ctype_digit()

Generating a unique machine id

I hate to be the guy who says, "you're just doing it wrong" (I always hate that guy ;) but...

Does it have to be repeatably generated for the unique machine? Could you just assign the identifier or do a public/private key? Maybe if you could generate and store the value, you could access it from both OS installs on the same disk?

You've probably explored these options and they doesn't work for you, but if not, it's something to consider.

If it's not a matter of user trust, you could just use MAC addresses.

git revert back to certain commit

You can revert all your files under your working directory and index by typing following this command

git reset --hard <SHAsum of your commit>

You can also type

git reset --hard HEAD #your current head point

or

git reset --hard HEAD^ #your previous head point

Hope it helps

Force browser to refresh css, javascript, etc

You can turn off caching with Firefox's web developer toolbar.

How to create a List with a dynamic object type

It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.

Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.

DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj

...

The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.

var DyObjectsList = new List<dynamic>; 
if (condition1) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = true; 
    DyObj.Message = "Message 1"; 
    DyObjectsList .Add(DyObj); 
} 
if (condition2) { 
    dynamic DyObj = new ExpandoObject(); 
    DyObj.Required = false; 
    DyObj.Message = "Message 2"; 
    DyObjectsList .Add(DyObj); 
} 

your resulting List essentially looks like this

DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj

Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.

However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.

Compare two Timestamp in java

You can sort Timestamp as follows:

public int compare(Timestamp t1, Timestamp t2) {

    long l1 = t1.getTime();
    long l2 = t2.getTime();
    if (l2 > l1)
    return 1;
    else if (l1 > l2)
    return -1;
    else
    return 0;
}

ASP.NET MVC ActionLink and post method

I have done the same issue using following code:

@using (Html.BeginForm("Delete", "Admin"))
{
       @Html.Hidden("ProductID", item.ProductID)
       <input type="submit" value="Delete" />
}

jQuery Select first and second td

To select the first and the second cell in each row, you could do this:

$(".location table tbody tr").each(function() {
    $(this).children('td').slice(0, 2).addClass("black");
});

How to add an UIViewController's view as subview

Thanks to this guys I did it http://highoncoding.com/Articles/848_Creating_iPad_Dashboard_Using_UIViewController_Containment.aspx

Add UIView, connect it to header:

@property (weak, nonatomic) IBOutlet UIView *addViewToAddPlot;

In - (void)viewDidLoad do this:

ViewControllerToAdd *nonSystemsController = [[ViewControllerToAdd alloc] initWithNibName:@"ViewControllerToAdd" bundle:nil];
    nonSystemsController.view.frame = self.addViewToAddPlot.bounds;
    [self.addViewToAddPlot addSubview:nonSystemsController.view];
    [self addChildViewController:nonSystemsController];
    [nonSystemsController didMoveToParentViewController:self];

Enjoy

Adding 'serial' to existing column in Postgres

TL;DR

Here's a version where you don't need a human to read a value and type it out themselves.

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Another option would be to employ the reusable Function shared at the end of this answer.


A non-interactive solution

Just adding to the other two answers, for those of us who need to have these Sequences created by a non-interactive script, while patching a live-ish DB for instance.

That is, when you don't wanna SELECT the value manually and type it yourself into a subsequent CREATE statement.

In short, you can not do:

CREATE SEQUENCE foo_a_seq
    START WITH ( SELECT max(a) + 1 FROM foo );

... since the START [WITH] clause in CREATE SEQUENCE expects a value, not a subquery.

Note: As a rule of thumb, that applies to all non-CRUD (i.e.: anything other than INSERT, SELECT, UPDATE, DELETE) statements in pgSQL AFAIK.

However, setval() does! Thus, the following is absolutely fine:

SELECT setval('foo_a_seq', max(a)) FROM foo;

If there's no data and you don't (want to) know about it, use coalesce() to set the default value:

SELECT setval('foo_a_seq', coalesce(max(a), 0)) FROM foo;
--                         ^      ^         ^
--                       defaults to:       0

However, having the current sequence value set to 0 is clumsy, if not illegal.
Using the three-parameter form of setval would be more appropriate:

--                                             vvv
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
--                                                  ^   ^
--                                                is_called

Setting the optional third parameter of setval to false will prevent the next nextval from advancing the sequence before returning a value, and thus:

the next nextval will return exactly the specified value, and sequence advancement commences with the following nextval.

— from this entry in the documentation

On an unrelated note, you also can specify the column owning the Sequence directly with CREATE, you don't have to alter it later:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;

In summary:

CREATE SEQUENCE foo_a_seq OWNED BY foo.a;
SELECT setval('foo_a_seq', coalesce(max(a), 0) + 1, false) FROM foo;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq'); 

Using a Function

Alternatively, if you're planning on doing this for multiple columns, you could opt for using an actual Function.

CREATE OR REPLACE FUNCTION make_into_serial(table_name TEXT, column_name TEXT) RETURNS INTEGER AS $$
DECLARE
    start_with INTEGER;
    sequence_name TEXT;
BEGIN
    sequence_name := table_name || '_' || column_name || '_seq';
    EXECUTE 'SELECT coalesce(max(' || column_name || '), 0) + 1 FROM ' || table_name
            INTO start_with;
    EXECUTE 'CREATE SEQUENCE ' || sequence_name ||
            ' START WITH ' || start_with ||
            ' OWNED BY ' || table_name || '.' || column_name;
    EXECUTE 'ALTER TABLE ' || table_name || ' ALTER COLUMN ' || column_name ||
            ' SET DEFAULT nextVal(''' || sequence_name || ''')';
    RETURN start_with;
END;
$$ LANGUAGE plpgsql VOLATILE;

Use it like so:

INSERT INTO foo (data) VALUES ('asdf');
-- ERROR: null value in column "a" violates not-null constraint

SELECT make_into_serial('foo', 'a');
INSERT INTO foo (data) VALUES ('asdf');
-- OK: 1 row(s) affected

creating json object with variables

var formValues = {
    firstName: $('#firstName').val(),
    lastName: $('#lastName').val(),
    phone: $('#phoneNumber').val(),
    address: $('#address').val()
};

Note this will contain the values of the elements at the point in time the object literal was interpreted, not when the properties of the object are accessed. You'd need to write a getter for that.

How to implement HorizontalScrollView like Gallery?

You may use HorizontalScrollView to implement Horizontal scrolling.

Code

<HorizontalScrollView
android:id="@+id/hsv"
android:layout_width="fill_parent"
android:layout_height="100dp"
 android:layout_weight="0"
android:fillViewport="true"
android:measureAllChildren="false"
android:scrollbars="none" >
<LinearLayout
    android:id="@+id/innerLay"
    android:layout_width="wrap_content"
    android:layout_height="100dp"
    android:gravity="center_vertical"
    android:orientation="horizontal" >
    </LinearLayout>
    </HorizontalScrollView>

featured.xml:

<?xml version="1.0" encoding="utf-8"?>
   <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="160dp"
   android:layout_margin="4dp"
android:layout_height="match_parent"
android:orientation="vertical" >

      <RelativeLayout 
android:layout_width="fill_parent"
android:layout_height="fill_parent" 
>

<ProgressBar                
    android:layout_width="15dip"       
    android:layout_height="15dip"
    android:id="@+id/progress" 
    android:layout_centerInParent="true"
    />

<ImageView
    android:id="@+id/image"       
    android:layout_width="fill_parent"       
    android:layout_height="fill_parent"
    android:background="#20000000"
    />

<TextView
    android:id="@+id/textView1"
    android:layout_width="fill_parent"
    android:layout_height="30dp"
    android:layout_alignParentBottom="true"
    android:layout_alignParentRight="true"
    android:gravity="center"
    android:textColor="#000000"
    android:background="#ffffff"
    android:text="Image Text" />

      </RelativeLayout>
     </LinearLayout>

Java Code:

 LayoutInflater inflater;

    inflater=getLayoutInflater();
    LinearLayout inLay=(LinearLayout) findViewById(R.id.innerLay);

    for(int x=0;x<10;x++)
    {
        inLay.addView(getView(x));
    }




 View getView(final int x)
{
   View rootView = inflater.inflate( R.layout.featured_item,null);

   ImageView image = (ImageView) rootView.findViewById(R.id.image);

   //Thease Two Line is sufficient my dear to implement lazyLoading
   AQuery aq = new AQuery(rootView);
   String url="http://farm6.static.flickr.com/5035/5802797131_a729dac808_s.jpg";
   aq.id(image).progress(R.id.progress).image(url, true, true, 0, R.drawable.placeholder1);
   image.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View arg0) {
     Toast.makeText(PhotoActivity.this, "Click Here Postion "+x,     

         Toast.LENGTH_LONG).show();
        }
    });
   return rootView;
       }

Note: to implement lazy loading, please use this link for AQUERY

https://code.google.com/p/android-query/wiki/ImageLoading

Jquery-How to grey out the background while showing the loading icon over it

1) "container" is a class and not an ID 2) .container - set z-index and display: none in your CSS and not inline unless there is a really good reason to do so. Demo@fiddle

$("#button").click(function() {
    $(".container").css("opacity", 0.2);
   $("#loading-img").css({"display": "block"});
});

CSS:

#loading-img {
    background: url(http://web.bogdanteodoru.com/wp-content/uploads/2012/01/bouncy-css3-loading-animation.jpg) center center no-repeat;  /* different for testing purposes */
    display: none;
    height: 100px; /* for testing purposes */
    z-index: 12;
}

And a demo with animated image.

How to set radio button checked as default in radiogroup?

In case for xml attribute its android:checkedButton which takes the id of the RadioButton to be checked.

<RadioGroup
...
...
android:checkedButton="@+id/IdOfTheRadioButtonInsideThatTobeChecked"
... >....</RadioGroup>

Styling HTML email for Gmail

I agree with everyone who supports classes AND inline styles. You might have learned this by now, but if there is a single mistake in your style sheet, Gmail will disregard it.

You might think that your CSS is perfect, because you've done it so often, why would I have mistakes in my CSS? Run it through the CSS Validator (for example http://www.css-validator.org/) and see what happens. I did that after encountering some Gmail display issues, and to my surprise, several Microsoft Outlook specific style declarations showed up as mistakes.

Which made sense to me, so I removed them from the style sheet and put them into a only for Microsoft code block, like so:

<!--[if mso]>
<style type="text/css">
body, table, td, .mobile-text {
font-family: Arial, sans-serif !important;
}
</style>
<xml>
  <o:OfficeDocumentSettings>
    <o:AllowPNG/>
    <o:PixelsPerInch>96</o:PixelsPerInch>
  </o:OfficeDocumentSettings>
</xml>
<![endif]-->

This is just a simple example, but, who know, it might come in handy some time.

How to use the CSV MIME-type?

This code can be used to export any file, including csv

// application/octet-stream tells the browser not to try to interpret the file
header('Content-type: application/octet-stream');
header('Content-Length: ' . filesize($data));
header('Content-Disposition: attachment; filename="export.csv"');

Enable UTF-8 encoding for JavaScript

I too had this issue, I would copy the whole piece of code and put in Notepad, before pasting in Notepad, make sure you save the file type as ALL files and save the doc as utf-8 format. then you can paste your code and run, It should work. ?????? obiviously means unreadable characters.

SQL query to find record with ID not in another table

Keeping in mind the points made in @John Woo's comment/link above, this is how I typically would handle it:

SELECT t1.ID, t1.Name 
FROM   Table1 t1
WHERE  NOT EXISTS (
    SELECT TOP 1 NULL
    FROM Table2 t2
    WHERE t1.ID = t2.ID
)

Grouping functions (tapply, by, aggregate) and the *apply family

In the collapse package recently released on CRAN, I have attempted to compress most of the common apply functionality into just 2 functions:

  1. dapply (Data-Apply) applies functions to rows or (default) columns of matrices and data.frames and (default) returns an object of the same type and with the same attributes (unless the result of each computation is atomic and drop = TRUE). The performance is comparable to lapply for data.frame columns, and about 2x faster than apply for matrix rows or columns. Parallelism is available via mclapply (only for MAC).

Syntax:

dapply(X, FUN, ..., MARGIN = 2, parallel = FALSE, mc.cores = 1L, 
       return = c("same", "matrix", "data.frame"), drop = TRUE)

Examples:

# Apply to columns:
dapply(mtcars, log)
dapply(mtcars, sum)
dapply(mtcars, quantile)
# Apply to rows:
dapply(mtcars, sum, MARGIN = 1)
dapply(mtcars, quantile, MARGIN = 1)
# Return as matrix:
dapply(mtcars, quantile, return = "matrix")
dapply(mtcars, quantile, MARGIN = 1, return = "matrix")
# Same for matrices ...
  1. BY is a S3 generic for split-apply-combine computing with vector, matrix and data.frame method. It is significantly faster than tapply, by and aggregate (an also faster than plyr, on large data dplyr is faster though).

Syntax:

BY(X, g, FUN, ..., use.g.names = TRUE, sort = TRUE,
   expand.wide = FALSE, parallel = FALSE, mc.cores = 1L,
   return = c("same", "matrix", "data.frame", "list"))

Examples:

# Vectors:
BY(iris$Sepal.Length, iris$Species, sum)
BY(iris$Sepal.Length, iris$Species, quantile)
BY(iris$Sepal.Length, iris$Species, quantile, expand.wide = TRUE) # This returns a matrix 
# Data.frames
BY(iris[-5], iris$Species, sum)
BY(iris[-5], iris$Species, quantile)
BY(iris[-5], iris$Species, quantile, expand.wide = TRUE) # This returns a wider data.frame
BY(iris[-5], iris$Species, quantile, return = "matrix") # This returns a matrix
# Same for matrices ...

Lists of grouping variables can also be supplied to g.

Talking about performance: A main goal of collapse is to foster high-performance programming in R and to move beyond split-apply-combine alltogether. For this purpose the package has a full set of C++ based fast generic functions: fmean, fmedian, fmode, fsum, fprod, fsd, fvar, fmin, fmax, ffirst, flast, fNobs, fNdistinct, fscale, fbetween, fwithin, fHDbetween, fHDwithin, flag, fdiff and fgrowth. They perform grouped computations in a single pass through the data (i.e. no splitting and recombining).

Syntax:

fFUN(x, g = NULL, [w = NULL,] TRA = NULL, [na.rm = TRUE,] use.g.names = TRUE, drop = TRUE)

Examples:

v <- iris$Sepal.Length
f <- iris$Species

# Vectors
fmean(v)             # mean
fmean(v, f)          # grouped mean
fsd(v, f)            # grouped standard deviation
fsd(v, f, TRA = "/") # grouped scaling
fscale(v, f)         # grouped standardizing (scaling and centering)
fwithin(v, f)        # grouped demeaning

w <- abs(rnorm(nrow(iris)))
fmean(v, w = w)      # Weighted mean
fmean(v, f, w)       # Weighted grouped mean
fsd(v, f, w)         # Weighted grouped standard-deviation
fsd(v, f, w, "/")    # Weighted grouped scaling
fscale(v, f, w)      # Weighted grouped standardizing
fwithin(v, f, w)     # Weighted grouped demeaning

# Same using data.frames...
fmean(iris[-5], f)                # grouped mean
fscale(iris[-5], f)               # grouped standardizing
fwithin(iris[-5], f)              # grouped demeaning

# Same with matrices ...

In the package vignettes I provide benchmarks. Programming with the fast functions is significantly faster than programming with dplyr or data.table, especially on smaller data, but also on large data.

Which Python memory profiler is recommended?

guppy3 is quite simple to use. At some point in your code, you have to write the following:

from guppy import hpy
h = hpy()
print(h.heap())

This gives you some output like this:

Partition of a set of 132527 objects. Total size = 8301532 bytes.
Index  Count   %     Size   % Cumulative  % Kind (class / dict of class)
0  35144  27  2140412  26   2140412  26 str
1  38397  29  1309020  16   3449432  42 tuple
2    530   0   739856   9   4189288  50 dict (no owner)

You can also find out from where objects are referenced and get statistics about that, but somehow the docs on that are a bit sparse.

There is a graphical browser as well, written in Tk.

For Python 2.x, use Heapy.

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

Step one: Go to... C:\xampp\phpMyAdmin

Step Two: Open the config.inc.php file

Step Three: Locate the following information and change the password.

/* Authentication type and info */
$cfg['Servers'][$i]['auth_type'] = 'config';
$cfg['Servers'][$i]['user'] = 'ENTER_YOUR_USER_NAME_HERE';
$cfg['Servers'][$i]['password'] = 'ENTER_YOUR_PASS_HERE';
$cfg['Servers'][$i]['extension'] = 'mysqli';
$cfg['Servers'][$i]['AllowNoPassword'] = true;
$cfg['Lang'] = '';

Mongoose, Select a specific field with find

There is a shorter way of doing this now:

exports.someValue = function(req, res, next) {
    //query with mongoose
    dbSchemas.SomeValue.find({}, 'name', function(err, someValue){
      if(err) return next(err);
      res.send(someValue);
    });
    //this eliminates the .select() and .exec() methods
};

In case you want most of the Schema fields and want to omit only a few, you can prefix the field name with a -. For ex "-name" in the second argument will not include name field in the doc whereas the example given here will have only the name field in the returned docs.

JQuery Ajax - How to Detect Network Connection error when making Ajax call

Have you tried this?

$(document).ajaxError(function(){ alert('error'); }

That should handle all AjaxErrors. I´ve found it here. There you find also a possibility to write these errors to your firebug console.

How to deal with "java.lang.OutOfMemoryError: Java heap space" error?

You could specify per project how much heap space your project wants

Following is for Eclipse Helios/Juno/Kepler:

Right mouse click on

 Run As - Run Configuration - Arguments - Vm Arguments, 

then add this

-Xmx2048m

Set transparent background using ImageMagick and commandline prompt

You can Use this to make the background transparent

convert test.png -background rgba(0,0,0,0) test1.png

The above gives the prefect transparent background

enumerate() for dictionary in python

dict1={'a':1, 'b':'banana'}

To list the dictionary in Python 2.x:

for k,v in dict1.iteritems():
        print k,v 

In Python 3.x use:

for k,v in dict1.items():
        print(k,v)
# a 1
# b banana

Finally, as others have indicated, if you want a running index, you can have that too:

for i  in enumerate(dict1.items()):
   print(i)  

 # (0, ('a', 1))
 # (1, ('b', 'banana'))

But this defeats the purpose of a dictionary (map, associative array) , which is an efficient data structure for telephone-book-style look-up. Dictionary ordering could be incidental to the implementation and should not be relied upon. If you need the order, use OrderedDict instead.

How can I determine whether a 2D Point is within a Polygon?

David Segond's answer is pretty much the standard general answer, and Richard T's is the most common optimization, though therre are some others. Other strong optimizations are based on less general solutions. For example if you are going to check the same polygon with lots of points, triangulating the polygon can speed things up hugely as there are a number of very fast TIN searching algorithms. Another is if the polygon and points are on a limited plane at low resolution, say a screen display, you can paint the polygon onto a memory mapped display buffer in a given colour, and check the color of a given pixel to see if it lies in the polygons.

Like many optimizations, these are based on specific rather than general cases, and yield beneifits based on amortized time rather than single usage.

Working in this field, i found Joeseph O'Rourkes 'Computation Geometry in C' ISBN 0-521-44034-3 to be a great help.

Warning: Attempt to present * on * whose view is not in the window hierarchy - swift

I was getting this error while was presenting controller after the user opens the deeplink. I know this isn't the best solution, but if you are in short time frame here is a quick fix - just wrap your code in asyncAfter:

DispatchQueue.main.asyncAfter(deadline: .now() + 0.7, execute: { [weak self] in
                                navigationController.present(signInCoordinator.baseController, animated: animated, completion: completion)
                            })

It will give time for your presenting controller to call viewDidAppear.

Detect key input in Python

Use Tkinter there are a ton of tutorials online for this. basically, you can create events. Here is a link to a great site! This makes it easy to capture clicks. Also, if you are trying to make a game, Tkinter also has a GUI. Although, I wouldn't recommend Python for games at all, it could be a fun experiment. Good Luck!

VNC viewer with multiple monitors

tightVNC 2.5.X and even pre 2.5 supports multi monitor. When you connect, you get a huge virtual monitor. However, this is also has disadvantages. UltaVNC (Tho when I tried it, was buggy in this area) allows you to connect to one huge virtual monitor or just to 1 screen at a time. (With a button to cycle through them) TightVNC also plan to support such a feature.. (When , no idea) This feature is important as if you have large multi monitors and connecting over a reasonably slow link.. The screen updates are just to slow.. Cutting down to one monitor to focus on is desirable.

I like tightVNC, but UltraVNC seems to have a few more features right now..

I have found tightVNC more solid. And that is why I have stuck with it.

I would try both. They both work well, but I imagine one would suite slightly more then the other.

How do I set the default schema for a user in MySQL

If your user has a local folder e.g. Linux, in your users home folder you could create a .my.cnf file and provide the credentials to access the server there. for example:-

[client]
host=localhost
user=yourusername
password=yourpassword or exclude to force entry
database=mygotodb

Mysql would then open this file for each user account read the credentials and open the selected database.

Not sure on Windows, I upgraded from Windows because I needed the whole house not just the windows (aka Linux) a while back.

How do I install soap extension?

For Windows

  1. Find extension=php_soap.dll or extension=soap in php.ini and remove the commenting semicolon at the beginning of the line. Eventually check for soap.ini under the conf.d directory.

  2. Restart your server.

For Linux

Ubuntu:

PHP7

Apache

sudo apt-get install php7.0-soap 
sudo systemctl restart apache2

PHP5

sudo apt-get install php-soap
sudo systemctl restart apache2

OpenSuse:

PHP7

Apache

sudo zypper in php7-soap
sudo systemctl restart apache2

Nginx

sudo zypper in php7-soap
sudo systemctl restart nginx

Count table rows

It can be convenient to select count with filter by indexed field. Try this

EXPLAIN SELECT * FROM table_name WHERE key < anything; 

SQL Query Where Date = Today Minus 7 Days

DECLARE @Daysforward int
SELECT @Daysforward = 25 (no of days required)
Select * from table name

where CAST( columnDate AS date) < DATEADD(day,1+@Daysforward,CAST(GETDATE() AS date))

Intellij IDEA Java classes not auto compiling on save

I was getting error: some jars are not in classpath.So I just delete the corrupted jar and perrform below steps

1.Project >  Setting>Build,Execution,Deployment>Compiler>check build project automatically
2.CTRL+SHIFT+A find/search **registry** --Check for below param
compiler.automake.allow.when.app.running
compiler.automake.trigger.delay=500---According to ur requirement
3.Add devtool in pom.xml
         <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-devtools</artifactId>
            <optional>true</optional>
        </dependency>
4.Build ,If found any probelm while building ,saying some jar in not in class path.Just delete the corrupted jar
and re-build the project angain after sync with maven lib

How to access JSON Object name/value?

You should do

alert(data[0].name); //Take the property name of the first array

and not

 alert(data.myName)

jQuery should be able to sniff the dataType for you even if you don't set it so no need for JSON.parse.

fiddle here

http://jsfiddle.net/H2yN6/

How to add browse file button to Windows Form using C#

OpenFileDialog fdlg = new OpenFileDialog();
fdlg.Title = "C# Corner Open File Dialog" ;
fdlg.InitialDirectory = @"c:\" ;
fdlg.Filter = "All files (*.*)|*.*|All files (*.*)|*.*" ;
fdlg.FilterIndex = 2 ;
fdlg.RestoreDirectory = true ;
if(fdlg.ShowDialog() == DialogResult.OK)
{
textBox1.Text = fdlg.FileName ;
}

In this code you can put your address in a text box.

"Could not find acceptable representation" using spring-boot-starter-web

If using @FeignClient, add e.g.

produces = "application/json"

to the @RequestMapping annotation

Insert an element at a specific index in a list and return the updated list

Most performance efficient approach

You may also insert the element using the slice indexing in the list. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2  # Index at which you want to insert item

>>> b = a[:]   # Created copy of list "a" as "b".
               # Skip this step if you are ok with modifying the original list

>>> b[insert_at:insert_at] = [3]  # Insert "3" within "b"
>>> b
[1, 2, 3, 4]

For inserting multiple elements together at a given index, all you need to do is to use a list of multiple elements that you want to insert. For example:

>>> a = [1, 2, 4]
>>> insert_at = 2   # Index starting from which multiple elements will be inserted

# List of elements that you want to insert together at "index_at" (above) position
>>> insert_elements = [3, 5, 6]

>>> a[insert_at:insert_at] = insert_elements
>>> a   # [3, 5, 6] are inserted together in `a` starting at index "2"
[1, 2, 3, 5, 6, 4]

To know more about slice indexing, you can refer: Understanding slice notation.

Note: In Python 3.x, difference of performance between slice indexing and list.index(...) is significantly reduced and both are almost equivalent. However, in Python 2.x, this difference is quite noticeable. I have shared performance comparisons later in this answer.


Alternative using list comprehension (but very slow in terms of performance):

As an alternative, it can be achieved using list comprehension with enumerate too. (But please don't do it this way. It is just for illustration):

>>> a = [1, 2, 4]
>>> insert_at = 2

>>> b = [y for i, x in enumerate(a) for y in ((3, x) if i == insert_at else (x, ))]
>>> b
[1, 2, 3, 4]

Performance comparison of all solutions

Here's the timeit comparison of all the answers with list of 1000 elements on Python 3.9.1 and Python 2.7.16. Answers are listed in the order of performance for both the Python versions.

Python 3.9.1

  1. My answer using sliced insertion - Fastest ( 2.25 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 5: 2.25 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.33 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 5: 2.33 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (5.01 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    50000 loops, best of 5: 5.01 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 135 µsec per loop)

    python3 -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    2000 loops, best of 5: 135 µsec per loop
    

Python 2.7.16

  1. My answer using sliced insertion - Fastest (2.09 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b[500:500] = [3]"
    100000 loops, best of 3: 2.09 µsec per loop
    
  2. Rushy Panchal's answer with most votes using list.insert(...)- Second (2.36 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:]; b.insert(500, 3)"
    100000 loops, best of 3: 2.36 µsec per loop
    
  3. ATOzTOA's accepted answer based on merge of sliced lists - Third (4.44 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "b = a[:500] + [3] + a[500:]"
    100000 loops, best of 3: 4.44 µsec per loop
    
  4. My answer with List Comprehension and enumerate - Fourth (very slow with 103 µsec per loop)

    python -m timeit -s "a = list(range(1000))" "[y for i, x in enumerate(a) for y in ((3, x) if i == 500 else (x, )) ]"
    10000 loops, best of 3: 103 µsec per loop
    

How to get distinct results in hibernate with joins and row-based limiting (paging)?

NullPointerException in some cases! Without criteria.setProjection(Projections.distinct(Projections.property("id"))) all query goes well! This solution is bad!

Another way is use SQLQuery. In my case following code works fine:

List result = getSession().createSQLQuery(
"SELECT distinct u.id as usrId, b.currentBillingAccountType as oldUser_type,"
+ " r.accountTypeWhenRegister as newUser_type, count(r.accountTypeWhenRegister) as numOfRegUsers"
+ " FROM recommendations r, users u, billing_accounts b WHERE "
+ " r.user_fk = u.id and"
+ " b.user_fk = u.id and"
+ " r.activated = true and"
+ " r.audit_CD > :monthAgo and"
+ " r.bonusExceeded is null and"
+ " group by u.id, r.accountTypeWhenRegister")
.addScalar("usrId", Hibernate.LONG)
.addScalar("oldUser_type", Hibernate.INTEGER)
.addScalar("newUser_type", Hibernate.INTEGER)
.addScalar("numOfRegUsers", Hibernate.BIG_INTEGER)
.setParameter("monthAgo", monthAgo)
.setMaxResults(20)
.list();

Distinction is done in data base! In opposite to:

criteria.setResultTransformer(Criteria.DISTINCT_ROOT_ENTITY);

where distinction is done in memory, after load entities!

IIS Request Timeout on long ASP.NET operation

If you want to extend the amount of time permitted for an ASP.NET script to execute then increase the Server.ScriptTimeout value. The default is 90 seconds for .NET 1.x and 110 seconds for .NET 2.0 and later.

For example:

// Increase script timeout for current page to five minutes
Server.ScriptTimeout = 300;

This value can also be configured in your web.config file in the httpRuntime configuration element:

<!-- Increase script timeout to five minutes -->
<httpRuntime executionTimeout="300" 
  ... other configuration attributes ...
/>

enter image description here

Please note according to the MSDN documentation:

"This time-out applies only if the debug attribute in the compilation element is False. Therefore, if the debug attribute is True, you do not have to set this attribute to a large value in order to avoid application shutdown while you are debugging."

If you've already done this but are finding that your session is expiring then increase the ASP.NET HttpSessionState.Timeout value:

For example:

// Increase session timeout to thirty minutes
Session.Timeout = 30;

This value can also be configured in your web.config file in the sessionState configuration element:

<configuration>
  <system.web>
    <sessionState 
      mode="InProc"
      cookieless="true"
      timeout="30" />
  </system.web>
</configuration>

If your script is taking several minutes to execute and there are many concurrent users then consider changing the page to an Asynchronous Page. This will increase the scalability of your application.

The other alternative, if you have administrator access to the server, is to consider this long running operation as a candidate for implementing as a scheduled task or a windows service.

Event handlers for Twitter Bootstrap dropdowns?

In Bootstrap 3 'dropdown.js' provides us with the various events that are triggered.

click.bs.dropdown
show.bs.dropdown
shown.bs.dropdown

etc

how to hide keyboard after typing in EditText in android?

You can see marked answer on top. But i used getDialog().getCurrentFocus() and working well. I post this answer cause i cant type "this" in my oncreatedialog.

So this is my answer. If you tried marked answer and not worked , you can simply try this:

InputMethodManager inputManager = (InputMethodManager) getActivity().getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(getDialog().getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);

How do you create nested dict in Python?

UPDATE: For an arbitrary length of a nested dictionary, go to this answer.

Use the defaultdict function from the collections.

High performance: "if key not in dict" is very expensive when the data set is large.

Low maintenance: make the code more readable and can be easily extended.

from collections import defaultdict

target_dict = defaultdict(dict)
target_dict[key1][key2] = val

Create local maven repository

Set up a simple repository using a web server with its default configuration. The key is the directory structure. The documentation does not mention it explicitly, but it is the same structure as a local repository.

To set up an internal repository just requires that you have a place to put it, and then start copying required artifacts there using the same layout as in a remote repository such as repo.maven.apache.org. Source

Add a file to your repository like this:

mvn install:install-file \
  -Dfile=YOUR_JAR.jar -DgroupId=YOUR_GROUP_ID 
  -DartifactId=YOUR_ARTIFACT_ID -Dversion=YOUR_VERSION \
  -Dpackaging=jar \
  -DlocalRepositoryPath=/var/www/html/mavenRepository

If your domain is example.com and the root directory of the web server is located at /var/www/html/, then maven can find "YOUR_JAR.jar" if configured with <url>http://example.com/mavenRepository</url>.

Count unique values in a column in Excel

Here’s another quickie way to get the unique value count, as well as to get the unique values. Copy the column you care about into another worksheet, then select the entire column. Click on Data -> Remove Duplicates -> OK. This removes all duplicated values.

Text size of android design TabLayout tabs

Go on using tabTextAppearance as you did but

1) to fix the capital letter side effect add textAllCap in your style :

<style name="MyTabLayoutTextAppearance" parent="TextAppearance.AppCompat.Widget.ActionBar.Title.Inverse">
    <item name="android:textSize">14sp</item>
    <item name="android:textAllCaps">true</item>
</style>

2) to fix the selected tab color side effect add in TabLayout xml the following library attributes :

app:tabSelectedTextColor="@color/color1"
app:tabTextColor="@color/color2" 

Hope this helps.

Making an array of integers in iOS

C array:

NSInteger array[6] = {1, 2, 3, 4, 5, 6};

Objective-C Array:

NSArray *array = @[@1, @2, @3, @4, @5, @6];
// numeric values must in that case be wrapped into NSNumbers

Swift Array:

var array = [1, 2, 3, 4, 5, 6]

This is correct too:

var array = Array(1...10)

NB: arrays are strongly typed in Swift; in that case, the compiler infers from the content that the array is an array of integers. You could use this explicit-type syntax, too:

var array: [Int] = [1, 2, 3, 4, 5, 6]

If you wanted an array of Doubles, you would use :

var array = [1.0, 2.0, 3.0, 4.0, 5.0, 6.0] // implicit type-inference

or:

var array: [Double] = [1, 2, 3, 4, 5, 6] // explicit type

How do I install Python OpenCV through Conda?

i was on MAC machine inside one of anaconda virutal environment. For me,

conda install -c conda-forge opencv

worked fine.

It installed opencv version 3.4.4

Hope it helps.

How to downgrade to older version of Gradle

Change your gradle version in project setting: If you are using mac,click File->Project structure,then change gradle version,here: enter image description here

And check your build.gradle of project,change dependency of gradle,like this:

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:1.0.1'
    }
}

How can I manually generate a .pyc file from a .py file

To match the original question requirements (source path and destination path) the code should be like that:

import py_compile
py_compile.compile(py_filepath, pyc_filepath)

If the input code has errors then the py_compile.PyCompileError exception is raised.

How to auto-size an iFrame?

This solution worked best for me. It uses jQuery and the iframe's ".load" event.

How to include js file in another js file?

It is not possible directly. You may as well write some preprocessor which can handle that.

If I understand it correctly then below are the things that can be helpful to achieve that:

  • Use a pre-processor which will run through your JS files for example looking for patterns like "@import somefile.js" and replace them with the content of the actual file. Nicholas Zakas(Yahoo) wrote one such library in Java which you can use (http://www.nczonline.net/blog/2009/09/22/introducing-combiner-a-javascriptcss-concatenation-tool/)

  • If you are using Ruby on Rails then you can give Jammit asset packaging a try, it uses assets.yml configuration file where you can define your packages which can contain multiple files and then refer them in your actual webpage by the package name.

  • Try using a module loader like RequireJS or a script loader like LabJs with the ability to control the loading sequence as well as taking advantage of parallel downloading.

JavaScript currently does not provide a "native" way of including a JavaScript file into another like CSS ( @import ), but all the above mentioned tools/ways can be helpful to achieve the DRY principle you mentioned. I can understand that it may not feel intuitive if you are from a Server-side background but this is the way things are. For front-end developers this problem is typically a "deployment and packaging issue".

Hope it helps.

How do I fix the npm UNMET PEER DEPENDENCY warning?

Today available Angular 2 rc.7, and I had a similar problem with [email protected] UNMET PEER DEPENDENCY.

If you, like me, simply replaced @angular/...rc.6 to @angular/...rc.7 - it's not enough. Because, for example, @angular/router has no rc.6 version.

In this case, better review package.json in Quick start

How to add link to flash banner

If you have a flash FLA file that shows the FLV movie you can add a button inside the FLA file. This button can be given an action to load the URL.

on (release) {
  getURL("http://someurl/");
}

To make the button transparent you can place a square inside it that is moved to the hit-area frame of the button.

I think it would go too far to explain into depth with pictures how to go about in stackoverflow.

How to set the Android progressbar's height?

You can set progress bar's style to this:

style="@android:style/Widget.ProgressBar.Horizontal"    

Flask Error: "Method Not Allowed The method is not allowed for the requested URL"

I had the same problem, and my solving was to replace :

return redirect(url_for('index'))

with

return render_template('indexo.html',data=Todos.query.all())

in my POST and DELETE route.

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

How to run a PowerShell script

Using cmd (BAT) file:

@echo off
color 1F
echo.

C:\Windows\system32\WindowsPowerShell\v1.0\powershell.exe -ExecutionPolicy Bypass -File "PrepareEnvironment.ps1"

:EOF
echo Waiting seconds
timeout /t 10 /nobreak > NUL

If you need run as administrator:

  1. Make a shortcut pointed to the command prompt (I named it Administrative Command Prompt)
  2. Open the shortcut's properties and go to the Compatibility tab
  3. Under the Privilege Level section, make sure the checkbox next to "Run this program as an administrator" is checked

Calling a function in jQuery with click()

$("#closeLink").click(closeIt);

Let's say you want to call your function passing some args to it i.e., closeIt(1, false). Then, you should build an anonymous function and call closeIt from it.

$("#closeLink").click(function() {
    closeIt(1, false);
});

jquery-ui-dialog - How to hook into dialog close event

This is what worked for me...

$('#dialog').live("dialogclose", function(){
   //code to run on dialog close
});

Prompt Dialog in Windows Forms

Unfortunately C# still doesn't offer this capability in the built in libs. The best solution at present is to create a custom class with a method that pops up a small form. If you're working in Visual Studio you can do this by clicking on Project >Add class

Add Class

Visual C# items >code >class Add Class 2

Name the class PopUpBox (you can rename it later if you like) and paste in the following code:

using System.Drawing;
using System.Windows.Forms;

namespace yourNameSpaceHere
{
    public class PopUpBox
    {
        private static Form prompt { get; set; }

        public static string GetUserInput(string instructions, string caption)
        {
            string sUserInput = "";
            prompt = new Form() //create a new form at run time
            {
                Width = 500, Height = 150, FormBorderStyle = FormBorderStyle.FixedDialog, Text = caption,
                StartPosition = FormStartPosition.CenterScreen, TopMost = true
            };
            //create a label for the form which will have instructions for user input
            Label lblTitle = new Label() { Left = 50, Top = 20, Text = instructions, Dock = DockStyle.Top, TextAlign = ContentAlignment.TopCenter };
            TextBox txtTextInput = new TextBox() { Left = 50, Top = 50, Width = 400 };

            ////////////////////////////OK button
            Button btnOK = new Button() { Text = "OK", Left = 250, Width = 100, Top = 70, DialogResult = DialogResult.OK };
            btnOK.Click += (sender, e) => 
            {
                sUserInput = txtTextInput.Text;
                prompt.Close();
            };
            prompt.Controls.Add(txtTextInput);
            prompt.Controls.Add(btnOK);
            prompt.Controls.Add(lblTitle);
            prompt.AcceptButton = btnOK;
            ///////////////////////////////////////

            //////////////////////////Cancel button
            Button btnCancel = new Button() { Text = "Cancel", Left = 350, Width = 100, Top = 70, DialogResult = DialogResult.Cancel };
            btnCancel.Click += (sender, e) => 
            {
                sUserInput = "cancel";
                prompt.Close();
            };
            prompt.Controls.Add(btnCancel);
            prompt.CancelButton = btnCancel;
            ///////////////////////////////////////

            prompt.ShowDialog();
            return sUserInput;
        }

        public void Dispose()
        {prompt.Dispose();}
    }
}

You will need to change the namespace to whatever you're using. The method returns a string, so here's an example of how to implement it in your calling method:

bool boolTryAgain = false;

do
{
    string sTextFromUser = PopUpBox.GetUserInput("Enter your text below:", "Dialog box title");
    if (sTextFromUser == "")
    {
        DialogResult dialogResult = MessageBox.Show("You did not enter anything. Try again?", "Error", MessageBoxButtons.YesNo);
        if (dialogResult == DialogResult.Yes)
        {
            boolTryAgain = true; //will reopen the dialog for user to input text again
        }
        else if (dialogResult == DialogResult.No)
        {
            //exit/cancel
            MessageBox.Show("operation cancelled");
            boolTryAgain = false;
        }//end if
    }
    else
    {
        if (sTextFromUser == "cancel")
        {
            MessageBox.Show("operation cancelled");
        }
        else
        {
            MessageBox.Show("Here is the text you entered: '" + sTextFromUser + "'");
            //do something here with the user input
        }

    }
} while (boolTryAgain == true);

This method checks the returned string for a text value, empty string, or "cancel" (the getUserInput method returns "cancel" if the cancel button is clicked) and acts accordingly. If the user didn't enter anything and clicked OK it will tell the user and ask them if they want to cancel or re-enter their text.

Post notes: In my own implementation I found that all of the other answers were missing 1 or more of the following:

  • A cancel button
  • The ability to contain symbols in the string sent to the method
  • How to access the method and handle the returned value.

Thus, I have posted my own solution. I hope someone finds it useful. Credit to Bas and Gideon + commenters for your contributions, you helped me to come up with a workable solution!

Plot width settings in ipython notebook

This is way I did it:

%matplotlib inline
import matplotlib.pyplot as plt
plt.rcParams["figure.figsize"] = (12, 9) # (w, h)

You can define your own sizes.

JDBC ODBC Driver Connection

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

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

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

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

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

          }
      }
  }

JAVA - using FOR, WHILE and DO WHILE loops to sum 1 through 100

Your for loop looks good.

A possible while loop to accomplish the same thing:

int sum = 0;
int i = 1;
while (i <= 100) {
    sum += i;
    i++;
}
System.out.println("The sum is " + sum);

A possible do while loop to accomplish the same thing:

int sum = 0;
int i = 1;
do {
    sum += i;
    i++;
} while (i <= 100);
System.out.println("The sum is " + sum);

The difference between the while and the do while is that, with the do while, at least one iteration is sure to occur.

One-line list comprehension: if-else variants

You can do that with list comprehension too:

A=[[x*100, x][x % 2 != 0] for x in range(1,11)]
print A

How to call a asp:Button OnClick event using JavaScript?

If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

The main point is this:

col-lg-* col-md-* col-xs-* col-sm define how many columns will there be in these different screen sizes.

Example: if you want there to be two columns in desktop screens and in phone screens you put two col-md-6 and two col-xs-6 classes in your columns.

If you want there to be two columns in desktop screens and only one column in phone screens (ie two rows stacked on top of each other) you put two col-md-6 and two col-xs-12 in your columns and because sum will be 24 they will auto stack on top of each other, or just leave xs style out.

How can I disable mod_security in .htaccess file?

For anyone that simply are looking to bypass the ERROR page to display the content on shared hosting. You might wanna try and use redirect in .htaccess file. If it is say 406 error, on UnoEuro it didn't seem to work simply deactivating the security. So I used this instead:

ErrorDocument 406 /

Then you can always change the error status using PHP. But be aware that in my case doing so means I am opening a door to SQL injections as I am bypassing WAF. So you will need to make sure that you either have your own security measures or enable the security again asap.

How to search a string in String array

Every method, mentioned earlier does looping either internally or externally, so it is not really important how to implement it. Here another example of finding all references of target string

       string [] arr = {"One","Two","Three"};
       var target = "One";
       var results = Array.FindAll(arr, s => s.Equals(target));

open resource with relative path in Java

@GianCarlo: You can try calling System property user.dir that will give you root of your java project and then do append this path to your relative path for example:

String root = System.getProperty("user.dir");
String filepath = "/path/to/yourfile.txt"; // in case of Windows: "\\path \\to\\yourfile.txt
String abspath = root+filepath;



// using above path read your file into byte []
File file = new File(abspath);
FileInputStream fis = new FileInputStream(file);
byte []filebytes = new byte[(int)file.length()];
fis.read(filebytes);

Split bash string by newline characters

Another way:

x=$'Some\nstring'
readarray -t y <<<"$x"

Or, if you don't have bash 4, the bash 3.2 equivalent:

IFS=$'\n' read -rd '' -a y <<<"$x"

You can also do it the way you were initially trying to use:

y=(${x//$'\n'/ })

This, however, will not function correctly if your string already contains spaces, such as 'line 1\nline 2'. To make it work, you need to restrict the word separator before parsing it:

IFS=$'\n' y=(${x//$'\n'/ })

...and then, since you are changing the separator, you don't need to convert the \n to space anymore, so you can simplify it to:

IFS=$'\n' y=($x)

This approach will function unless $x contains a matching globbing pattern (such as "*") - in which case it will be replaced by the matched file name(s). The read/readarray methods require newer bash versions, but work in all cases.

Can I append an array to 'formdata' in javascript?

var formData = new FormData;
var alphaArray = ['A', 'B', 'C','D','E'];
for (var i = 0; i < alphaArray.length; i++) {
    formData.append('listOfAlphabet', alphaArray [i]);
}

And In your request you will get array of alphabets.

How to run an external program, e.g. notepad, using hyperlink?

Sorry this answer sucks, but you can't launch an just any external application via a click, as this would be a serious security issue, this functionality isn't available in HTML or javascript. Think of just launching cmd.exe with args...you want to launch WinMerge with arguments, but you can see the security problems introduced by allowing this for anything.

The only possibly viable exception I can think of would be a protocol handler (since these are explicitly defined handlers), like winmerge://, though the best way to pass 2 file parameters I'm not sure of, if it's an option it's worth looking into, but I'm not sure what you are or are not allowed to do to the client, so this may be a non-starter solution.

How do I implement IEnumerable<T>

Why do you do it manually? yield return automates the entire process of handling iterators. (I also wrote about it on my blog, including a look at the compiler generated code).

If you really want to do it yourself, you have to return a generic enumerator too. You won't be able to use an ArrayList any more since that's non-generic. Change it to a List<MyObject> instead. That of course assumes that you only have objects of type MyObject (or derived types) in your collection.

How to get the range of occupied cells in excel sheet

Excel.Range last = sheet.Cells.SpecialCells(Excel.XlCellType.xlCellTypeLastCell, Type.Missing);
Excel.Range range = sheet.get_Range("A1", last);

"range" will now be the occupied cell range

maxlength ignored for input type="number" in Chrome

The absolute solution that I've recently just tried is:

<input class="class-name" placeholder="1234567" name="elementname"  type="text" maxlength="4" onkeypress="return (event.charCode == 8 || event.charCode == 0 || event.charCode == 13) ? null : event.charCode >= 48 && event.charCode <= 57" />

Using only CSS, show div on hover over <a>

Don't forget. if you are trying to hover around an image, you have to put it around a container. css:

.brand:hover + .brand-sales {
    display: block;
}

.brand-sales {
    display: none;
}

If you hover on this:

<span className="brand">
   <img src="https://murmure.me/wp-content/uploads/2017/10/nike-square-1900x1900.jpg" 
     alt"some image class="product-card-place-logo"/>
</span>

This will show:

<div class="product-card-sales-container brand-sales">
    <div class="product-card-">Message from the business goes here. They can talk alot or not</div>
</div>

EXCEL Multiple Ranges - need different answers for each range

Nested if's in Excel Are ugly:

=If(G2 < 1, .1, IF(G2 < 5,.15,if(G2 < 15,.2,if(G2 < 30,.5,if(G2 < 100,.1,1.3)))))

That should cover it.

Powershell: count members of a AD group

In Powershell, you'll need to import the active directory module, then use the get-adgroupmember, and then measure-object. For example, to get the number of users belonging to the group "domain users", do the following:

Import-Module activedirecotry
Get-ADGroupMember "domain users" | Measure-Object

When entering the group name after "Get-ADGroupMember", if the name is a single string with no spaces, then no quotes are necessary. If the group name has spaces in it, use the quotes around it.

The output will look something like:

Count    : 12345
Average  :
Sum      :
Maximum  :
Minimum  :
Property :

Note - importing the active directory module may be redundant if you're already using PowerShell for other AD admin tasks.

How can I get the sha1 hash of a string in node.js?

See the crypto.createHash() function and the associated hash.update() and hash.digest() functions:

var crypto = require('crypto')
var shasum = crypto.createHash('sha1')
shasum.update('foo')
shasum.digest('hex') // => "0beec7b5ea3f0fdbc95d0dd47f3c5bc275da8a33"

SQL Server 2008 R2 Express permissions -- cannot create database or modify users

You may be an administrator on the workstation, but that means nothing to SQL Server. Your login has to be a member of the sysadmin role in order to perform the actions in question. By default, the local administrators group is no longer added to the sysadmin role in SQL 2008 R2. You'll need to login with something else (sa for example) in order to grant yourself the permissions.

Create array of regex matches

        Set<String> keyList = new HashSet();
        Pattern regex = Pattern.compile("#\\{(.*?)\\}");
        Matcher matcher = regex.matcher("Content goes here");
        while(matcher.find()) {
            keyList.add(matcher.group(1)); 
        }
        return keyList;

AttributeError: 'module' object has no attribute 'model'

I also got the same error but I noticed that I had typed in Foreign*k*ey and not Foreign*K*ey,(capital K) if there is a newbie out there, check out spelling and caps.

Deleting a local branch with Git

This worked for me...
I have removed the folders there in .git/worktrees folder and then tried "git delete -D branch-name".

How to use target in location.href

If you go with the solution by @qiao, perhaps you would want to remove the appended child since the tab remains open and subsequent clicks would add more elements to the DOM.

// Code by @qiao
var a = document.createElement('a')
a.href = 'http://www.google.com'
a.target = '_blank'
document.body.appendChild(a)
a.click()
// Added code
document.body.removeChild(a)

Maybe someone could post a comment to his post, because I cannot.

How to create a RelativeLayout programmatically with two buttons one on top of the other?

Found the answer in How to lay out Views in RelativeLayout programmatically?

We should explicitly set id's using setId(). Only then, RIGHT_OF rules make sense.

Another mistake I did is, reusing the layoutparams object between the controls. We should create new object for each control

beyond top level package error in relative import

from package.A import foo

I think it's clearer than

import sys
sys.path.append("..")

get DATEDIFF excluding weekends using sql server

I just want to share the code I created that might help you.

DECLARE @MyCounter int = 0, @TempDate datetime, @EndDate datetime;
SET @TempDate = DATEADD(d,1,'2017-5-27')
SET @EndDate = '2017-6-3'

WHILE @TempDate <= @EndDate
    BEGIN
    IF DATENAME(DW,@TempDate) = 'Sunday' OR DATENAME(DW,@TempDate) = 'Saturday'
        SET @MyCounter = @MyCounter
    ELSE IF @TempDate not in ('2017-1-1', '2017-1-16', '2017-2-20', '2017-5-29', '2017-7-4', '2017-9-4', '2017-10-9', '2017-11-11', '2017-12-25')
        SET @MyCounter = @MyCounter + 1

    SET @TempDate = DATEADD(d,1,@TempDate)
    CONTINUE

END
PRINT @MyCounter
PRINT @TempDate

If you do have a holiday table, you can also use that so that you don't have to list all the holidays in the ELSE IF section of the code. You can also create a function for this code and use the function whenever you need it in your query.

I hope this might help too.

How to find a min/max with Ruby

You can use

[5,10].min 

or

[4,7].max

It's a method for Arrays.

how to get the value of a textarea in jquery?

You can also get the value by element's name attribute.

var message = $("#formId textarea[name=message]").val();

Initialize class fields in constructor or at declaration?

The semantics of C# differs slightly from Java here. In C# assignment in declaration is performed before calling the superclass constructor. In Java it is done immediately after which allows 'this' to be used (particularly useful for anonymous inner classes), and means that the semantics of the two forms really do match.

If you can, make the fields final.

How to remove all duplicate items from a list

The modern way to do it that maintains the order is:

>>> from collections import OrderedDict
>>> list(OrderedDict.fromkeys(lseparatedOrbList))

as discussed by Raymond Hettinger (python core dev) in this answer. In python 3.5 and above this is also the fastest way - see the linked answer for details. However the keys must be hashable (as is the case in your list I think)

Turn a simple socket into an SSL socket

Here my example ssl socket server threads (multiple connection) https://github.com/breakermind/CppLinux/blob/master/QtSslServerThreads/breakermindsslserver.cpp

#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string>
#include <unistd.h>
#include <iostream>

#include <breakermindsslserver.h>

using namespace std;

int main(int argc, char *argv[])
{
    BreakermindSslServer boom;
    boom.Start(123,"/home/user/c++/qt/BreakermindServer/certificate.crt", "/home/user/c++/qt/BreakermindServer/private.key");
    return 0;
}

Check if a folder exist in a directory and create them using C#

if(!System.IO.Directory.Exists(@"c:\mp_upload"))
{
     System.IO.Directory.CreateDirectory(@"c:\mp_upload");
}

break statement in "if else" - java

The issue is that you are trying to have multiple statements in an if without using {}. What you currently have is interpreted like:

if( choice==5 )
{
    System.out.println( ... );
}
break;
else
{
    //...
}

You really want:

if( choice==5 )
{
    System.out.println( ... );
    break;
}
else
{
    //...
}

Also, as Farce has stated, it would be better to use else if for all the conditions instead of if because if choice==1, it will still go through and check if choice==5, which would fail, and it will still go into your else block.

if( choice==1 )
    //...
else if( choice==2 )
    //...
else if( choice==3 )
    //...
else if( choice==4 )
    //...
else if( choice==5 )
{
    //...
}
else
    //...

A more elegant solution would be using a switch statement. However, break only breaks from the most inner "block" unless you use labels. So you want to label your loop and break from that if the case is 5:

LOOP:
for(;;)
{
    System.out.println("---> Your choice: ");
    choice = input.nextInt();
    switch( choice )
    {
        case 1:
            playGame();
            break;
        case 2:
            loadGame();
            break;
        case 2:
            options();
            break;
        case 4:
            credits();
            break;
        case 5:
            System.out.println("End of Game\n Thank you for playing with us!");
            break LOOP;
        default:
            System.out.println( ... );
    }
}

Instead of labeling the loop, you could also use a flag to tell the loop to stop.

bool finished = false;
while( !finished )
{
    switch( choice )
    {
        // ...
        case 5:
            System.out.println( ... )
            finished = true;
            break;
        // ...
    }
}

How to programmatically add controls to a form in VB.NET

Public Class Form1
    Private boxes(5) As TextBox

    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        Dim newbox As TextBox
        For i As Integer = 1 To 5 'Create a new textbox and set its properties26.27.
        newbox = New TextBox
        newbox.Size = New Drawing.Size(100, 20)
        newbox.Location = New Point(10, 10 + 25 * (i - 1))
        newbox.Name = "TextBox" & i
        newbox.Text = newbox.Name   'Connect it to a handler, save a reference to the array & add it to the form control.
        AddHandler newbox.TextChanged, AddressOf TextBox_TextChanged
        boxes(i) = newbox
        Me.Controls.Add(newbox)
        Next
    End Sub

    Private Sub TextBox_TextChanged(sender As System.Object, e As System.EventArgs)
        'When you modify the contents of any textbox, the name of that textbox
        'and its current contents will be displayed in the title bar

        Dim box As TextBox = DirectCast(sender, TextBox)
        Me.Text = box.Name & ": " & box.Text
    End Sub
End Class

How to run vi on docker container?

Add the following line in your Dockerfile then rebuild the docker image.

RUN apt-get update && apt-get install -y vim

JavaScript unit test tools for TDD

Take a look at the Dojo Object Harness (DOH) unit test framework which is pretty much framework independent harness for JavaScript unit testing and doesn't have any Dojo dependencies. There is a very good description of it at Unit testing Web 2.0 applications using the Dojo Objective Harness.

If you want to automate the UI testing (a sore point of many developers) — check out doh.robot (temporary down. update: other link http://dojotoolkit.org/reference-guide/util/dohrobot.html ) and dijit.robotx (temporary down). The latter is designed for an acceptance testing. Update:

Referenced articles explain how to use them, how to emulate a user interacting with your UI using mouse and/or keyboard, and how to record a testing session, so you can "play" it later automatically.

Max parallel http connections in a browser?

HTTP/1.1

IE 6 and 7:      2
IE 8:            6
IE 9:            6
IE 10:           8
IE 11:           8
Firefox 2:       2
Firefox 3:       6
Firefox 4 to 46: 6
Opera 9.63:      4
Opera 10:        8
Opera 11 and 12: 6
Chrome 1 and 2:  6
Chrome 3:        4
Chrome 4 to 23:  6
Safari 3 and 4:  4

source: http://p2p.wrox.com/book-professional-website-performance-optimizing-front-end-back-end-705/

HTTP/2(SPDY)

Multiplexed support(one single TCP connection for all requests)

How to submit a form using PhantomJS

As it was mentioned above CasperJS is the best tool to fill and send forms. Simplest possible example of how to fill & submit form using fill() function:

casper.start("http://example.com/login", function() {
//searches and fills the form with id="loginForm"
  this.fill('form#loginForm', {
    'login':    'admin',
    'password':    '12345678'
   }, true);
  this.evaluate(function(){
    //trigger click event on submit button
    document.querySelector('input[type="submit"]').click();
  });
});

The most efficient way to implement an integer based power function pow(int, int)

In addition to the answer by Elias, which causes Undefined Behaviour when implemented with signed integers, and incorrect values for high input when implemented with unsigned integers,

here is a modified version of the Exponentiation by Squaring that also works with signed integer types, and doesn't give incorrect values:

#include <stdint.h>

#define SQRT_INT64_MAX (INT64_C(0xB504F333))

int64_t alx_pow_s64 (int64_t base, uint8_t exp)
{
    int_fast64_t    base_;
    int_fast64_t    result;

    base_   = base;

    if (base_ == 1)
        return  1;
    if (!exp)
        return  1;
    if (!base_)
        return  0;

    result  = 1;
    if (exp & 1)
        result *= base_;
    exp >>= 1;
    while (exp) {
        if (base_ > SQRT_INT64_MAX)
            return  0;
        base_ *= base_;
        if (exp & 1)
            result *= base_;
        exp >>= 1;
    }

    return  result;
}

Considerations for this function:

(1 ** N) == 1
(N ** 0) == 1
(0 ** 0) == 1
(0 ** N) == 0

If any overflow or wrapping is going to take place, return 0;

I used int64_t, but any width (signed or unsigned) can be used with little modification. However, if you need to use a non-fixed-width integer type, you will need to change SQRT_INT64_MAX by (int)sqrt(INT_MAX) (in the case of using int) or something similar, which should be optimized, but it is uglier, and not a C constant expression. Also casting the result of sqrt() to an int is not very good because of floating point precission in case of a perfect square, but as I don't know of any implementation where INT_MAX -or the maximum of any type- is a perfect square, you can live with that.

Iterating through list of list in Python

If you wonder to get all values in the same list you can use the following code:

text = [u'sam', [['Test', [['one', [], []]], [(u'file.txt', ['id', 1, 0])]], ['Test2', [], [(u'file2.txt', ['id', 1, 2])]]], []]

def get_values(lVals):
    res = []
    for val in lVals:
        if type(val) not in [list, set, tuple]:
            res.append(val)
        else:
            res.extend(get_values(val))
    return res

get_values(text)

React.js: Set innerHTML vs dangerouslySetInnerHTML

Based on (dangerouslySetInnerHTML).

It's a prop that does exactly what you want. However they name it to convey that it should be use with caution

How to fix git error: RPC failed; curl 56 GnuTLS

To solve this issue:

Rebuilding git with openssl instead of gnutls fixed my problem.

I followed these instructions

Use of *args and **kwargs

Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:

>>> import operator
>>> def multiply(*args):
...  return reduce(operator.mul, args)

Then you use this function like:

>>> multiply(1,2,3)
6

or

>>> numbers = [1,2,3]
>>> multiply(*numbers)
6

What's the difference between a single precision and double precision floating point operation?

First of all float and double are both used for representation of numbers fractional numbers. So, the difference between the two stems from the fact with how much precision they can store the numbers.

For example: I have to store 123.456789 One may be able to store only 123.4567 while other may be able to store the exact 123.456789.

So, basically we want to know how much accurately can the number be stored and is what we call precision.

Quoting @Alessandro here

The precision indicates the number of decimal digits that are correct, i.e. without any kind of representation error or approximation. In other words, it indicates how many decimal digits one can safely use.

Float can accurately store about 7-8 digits in the fractional part while Double can accurately store about 15-16 digits in the fractional part

So, double can store double the amount of fractional part as of float. That is why Double is called double the float

JavaScript string encryption and decryption?

crypt.subtle AES-GCM, self-contained, tested:

async function aesGcmEncrypt(plaintext, password)

async function aesGcmDecrypt(ciphertext, password) 

https://gist.github.com/chrisveness/43bcda93af9f646d083fad678071b90a

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

How to make div's percentage width relative to parent div and not viewport

Specifying a non-static position, e.g., position: absolute/relative on a node means that it will be used as the reference for absolutely positioned elements within it http://jsfiddle.net/E5eEk/1/

See https://developer.mozilla.org/en-US/docs/Learn/CSS/CSS_layout/Positioning#Positioning_contexts

We can change the positioning context — which element the absolutely positioned element is positioned relative to. This is done by setting positioning on one of the element's ancestors.

_x000D_
_x000D_
#outer {_x000D_
  min-width: 2000px; _x000D_
  min-height: 1000px; _x000D_
  background: #3e3e3e; _x000D_
  position:relative_x000D_
}_x000D_
_x000D_
#inner {_x000D_
  left: 1%; _x000D_
  top: 45px; _x000D_
  width: 50%; _x000D_
  height: auto; _x000D_
  position: absolute; _x000D_
  z-index: 1;_x000D_
}_x000D_
_x000D_
#inner-inner {_x000D_
  background: #efffef;_x000D_
  position: absolute; _x000D_
  height: 400px; _x000D_
  right: 0px; _x000D_
  left: 0px;_x000D_
}
_x000D_
<div id="outer">_x000D_
  <div id="inner">_x000D_
    <div id="inner-inner"></div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to set proxy for wget?

start wget through socks5 proxy using tsocks:

  1. install tsocks: sudo apt install tsocks
  2. config tsocks

    # vi /etc/tsocks.conf
    
    server = 127.0.0.1
    server_type = 5
    server_port = 1080
    
  3. start: tsocks wget http://url_to_get

How to connect to a MySQL Data Source in Visual Studio

This seems to be a common problem. I had to uninstall the latest Connector/NET driver (6.7.4) and install an older version (6.6.5) for it to work. Others report 6.6.6 working for them.

See other topic with more info: MySQL Data Source not appearing in Visual Studio

HttpContext.Current.Request.Url.Host what it returns?

Try this:

string callbackurl = Request.Url.Host != "localhost" 
    ? Request.Url.Host : Request.Url.Authority;

This will work for local as well as production environment. Because the local uses url with port no that is possible using Url.Host.

How to prevent the "Confirm Form Resubmission" dialog?

It has nothing to do with your form or the values in it. It gets fired by the browser to prevent the user from repeating the same request with the cached data. If you really need to enable the refreshing of the result page, you should redirect the user, either via PHP (header('Location:result.php');) or other server-side language you're using. Meta tag solution should work also to disable the resending on refresh.

VARCHAR to DECIMAL

create function [Sistema].[fParseDecimal]
(
    @Valor nvarchar(4000)
)
returns decimal(18, 4) as begin
    declare @Valores table (Valor varchar(50));

    insert into @Valores values (@Valor);

    declare @Resultado decimal(18, 4) = (select top 1 
        cast('' as xml).value('sql:column("Valor") cast as xs:decimal ?', 'decimal(18, 4)')
    from @Valores);
    
    return @Resultado;
END

background: fixed no repeat not working on mobile

background-attachment:fixed in IOS Safari has been a known bug for as long as I can recall.

Here's some other options for you:

https://stackoverflow.com/a/23420490/1004312

Since the fixed position in general is not all that stable on touch (some more than others, Chrome works great), it is still acting up in Safari IOS 8 in situations that used to work in IOS 7, therefore I generally just use JS to detect touch devices, including Windows mobile.

/* ============== SUPPORTS TOUCH OR NOT ========= */
/*! Detects touch support and adds appropriate classes to html and returns a JS object
  Copyright (c) 2013 Izilla Partners Pty Ltd  | http://www.izilla.com.au 
  Licensed under the MIT license  |  https://coderwall.com/p/egbgdw 
*/
var supports = (function() {
    var d = document.documentElement,
        c = "ontouchstart" in window || navigator.msMaxTouchPoints;
    if (c) {
        d.className += " touch";
        return {
            touch: true
        }
    } else {
        d.className += " no-touch";
        return {
            touch: false
        }
    }
})();

CSS example assumes mobile first:

.myBackgroundPrecious {
   background: url(1.jpg) no-repeat center center;
   background-size: cover;
}

.no-touch .myBackgroundPrecious {
   background-attachment:fixed;
}

Change IPython/Jupyter notebook working directory

If you are using ipython in linux, then follow the steps:
!cd /directory_name/
You can try all the commands which work in you linux terminal.
!vi file_name.py

Just specify the exclamation(!) symbol before your linux commands.

What to do on TransactionTooLargeException

This exception is typically thrown when the app is being sent to the background.

So I've decided to use the data Fragment method to completely circumvent the onSavedInstanceStae lifecycle. My solution also handles complex instance states and frees memory ASAP.

First I've created a simple Fargment to store the data:

package info.peakapps.peaksdk.logic;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.Bundle;

/**
 * A neat trick to avoid TransactionTooLargeException while saving our instance state
 */

public class SavedInstanceFragment extends Fragment {

    private static final String TAG = "SavedInstanceFragment";
    private Bundle mInstanceBundle = null;

    public SavedInstanceFragment() { // This will only be called once be cause of setRetainInstance()
        super();
        setRetainInstance( true );
    }

    public SavedInstanceFragment pushData( Bundle instanceState )
    {
        if ( this.mInstanceBundle == null ) {
            this.mInstanceBundle = instanceState;
        }
        else
        {
            this.mInstanceBundle.putAll( instanceState );
        }
        return this;
    }

    public Bundle popData()
    {
        Bundle out = this.mInstanceBundle;
        this.mInstanceBundle = null;
        return out;
    }

    public static final SavedInstanceFragment getInstance(FragmentManager fragmentManager )
    {
        SavedInstanceFragment out = (SavedInstanceFragment) fragmentManager.findFragmentByTag( TAG );

        if ( out == null )
        {
            out = new SavedInstanceFragment();
            fragmentManager.beginTransaction().add( out, TAG ).commit();
        }
        return out;
    }
}

Then on my main Activity I circumvent the saved instance cycle completely, and defer the respoinsibilty to my data Fragment. No need to use this on the Fragments themselves, sice their state is added to the Activity's state automatically):

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);

    SavedInstanceFragment.getInstance( getFragmentManager() ).pushData( (Bundle) outState.clone() );
    outState.clear(); // We don't want a TransactionTooLargeException, so we handle things via the SavedInstanceFragment
}

What's left is simply to pop the saved instance:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(SavedInstanceFragment.getInstance(getFragmentManager()).popData());
}

@Override
protected void onRestoreInstanceState(Bundle savedInstanceState) {
    super.onRestoreInstanceState( SavedInstanceFragment.getInstance( getFragmentManager() ).popData() );
}

Full details: http://www.devsbedevin.net/avoiding-transactiontoolargeexception-on-android-nougat-and-up/

What is a loop invariant?

It is hard to keep track of what is happening with loops. Loops which don't terminate or terminate without achieving their goal behavior is a common problem in computer programming. Loop invariants help. A loop invariant is a formal statement about the relationship between variables in your program which holds true just before the loop is ever run (establishing the invariant) and is true again at the bottom of the loop, each time through the loop (maintaining the invariant). Here is the general pattern of the use of Loop Invariants in your code:

... // the Loop Invariant must be true here
while ( TEST CONDITION ) {
// top of the loop
...
// bottom of the loop
// the Loop Invariant must be true here
}
// Termination + Loop Invariant = Goal
...
Between the top and bottom of the loop, headway is presumably being made towards reaching the loop's goal. This might disturb (make false) the invariant. The point of Loop Invariants is the promise that the invariant will be restored before repeating the loop body each time. There are two advantages to this:

Work is not carried forward to the next pass in complicated, data dependent ways. Each pass through the loop in independent of all others, with the invariant serving to bind the passes together into a working whole. Reasoning that your loop works is reduced to reasoning that the loop invariant is restored with each pass through the loop. This breaks the complicated overall behavior of the loop into small simple steps, each which can be considered separately. The test condition of the loop is not part of the invariant. It is what makes the loop terminate. You consider separately two things: why the loop should ever terminate, and why the loop achieves its goal when it terminates. The loop will terminate if each time through the loop you move closer to satisfying the termination condition. It is often easy to assure this: e.g. stepping a counter variable by one until it reaches a fixed upper limit. Sometimes the reasoning behind termination is more difficult.

The loop invariant should be created so that when the condition of termination is attained, and the invariant is true, then the goal is reached:

invariant + termination => goal
It takes practice to create invariants which are simple and relate which capture all of goal attainment except for termination. It is best to use mathematical symbols to express loop invariants, but when this leads to over-complicated situations, we rely on clear prose and common-sense.

Installing SQL Server 2012 - Error: Prior Visual Studio 2010 instances requiring update

I did everything provided in the previous answers to this question, but still had the issue. I did have the update installed, but I ran the installer again, reapplying the update while SQL 2012 Installer was open on the screen where I could run the check again. After it finished, I ran the check again and it passed.

Bind failed: Address already in use

Everyone is correct. However, if you're also busy testing your code your own application might still "own" the socket if it starts and stops relatively quickly. Try SO_REUSEADDR as a socket option:

What exactly does SO_REUSEADDR do?

This socket option tells the kernel that even if this port is busy (in the TIME_WAIT state), go ahead and reuse it anyway. If it is busy, but with another state, you will still get an address already in use error. It is useful if your server has been shut down, and then restarted right away while sockets are still active on its port. You should be aware that if any unexpected data comes in, it may confuse your server, but while this is possible, it is not likely.

It has been pointed out that "A socket is a 5 tuple (proto, local addr, local port, remote addr, remote port). SO_REUSEADDR just says that you can reuse local addresses. The 5 tuple still must be unique!" by Michael Hunter ([email protected]). This is true, and this is why it is very unlikely that unexpected data will ever be seen by your server. The danger is that such a 5 tuple is still floating around on the net, and while it is bouncing around, a new connection from the same client, on the same system, happens to get the same remote port. This is explained by Richard Stevens in ``2.7 Please explain the TIME_WAIT state.''.

CURL to pass SSL certifcate and password

Should be:

curl --cert certificate_file.pem:password https://www.example.com/some_protected_page

Set value for particular cell in pandas DataFrame using index

Update: The .set_value method is going to be deprecated. .iat/.at are good replacements, unfortunately pandas provides little documentation


The fastest way to do this is using set_value. This method is ~100 times faster than .ix method. For example:

df.set_value('C', 'x', 10)

Display XML content in HTML page

You can use the old <xmp> tag. I don't know about browser support, but it should still work.

<HTML>

your code/tables

<xmp>
    <catalog>
        <cd>
            <title>Empire Burlesque</title>
            <artist>Bob Dylan</artist>
            <country>USA</country>
            <country>Columbia</country>
            <price>10.90</price>
            <year>1985</year>
        </cd>
    </catalog>
</xmp>

Output:

your code/tables
<catalog>
    <cd>
        <title>Empire Burlesque</title>
        <artist>Bob Dylan</artist>
        <country>USA</country>
        <country>Columbia</country>
        <price>10.90</price>
        <year>1985</year>
    </cd>
</catalog>

Returning a regex match in VBA (excel)

You need to access the matches in order to get at the SDI number. Here is a function that will do it (assuming there is only 1 SDI number per cell).

For the regex, I used "sdi followed by a space and one or more numbers". You had "sdi followed by a space and zero or more numbers". You can simply change the + to * in my pattern to go back to what you had.

Function ExtractSDI(ByVal text As String) As String

Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = "(sdi \d+)"
RE.Global = True
RE.IgnoreCase = True
Set allMatches = RE.Execute(text)

If allMatches.count <> 0 Then
    result = allMatches.Item(0).submatches.Item(0)
End If

ExtractSDI = result

End Function

If a cell may have more than one SDI number you want to extract, here is my RegexExtract function. You can pass in a third paramter to seperate each match (like comma-seperate them), and you manually enter the pattern in the actual function call:

Ex) =RegexExtract(A1, "(sdi \d+)", ", ")

Here is:

Function RegexExtract(ByVal text As String, _
                      ByVal extract_what As String, _
                      Optional seperator As String = "") As String

Dim i As Long, j As Long
Dim result As String
Dim allMatches As Object
Dim RE As Object
Set RE = CreateObject("vbscript.regexp")

RE.pattern = extract_what
RE.Global = True
Set allMatches = RE.Execute(text)

For i = 0 To allMatches.count - 1
    For j = 0 To allMatches.Item(i).submatches.count - 1
        result = result & seperator & allMatches.Item(i).submatches.Item(j)
    Next
Next

If Len(result) <> 0 Then
    result = Right(result, Len(result) - Len(seperator))
End If

RegexExtract = result

End Function

*Please note that I have taken "RE.IgnoreCase = True" out of my RegexExtract, but you could add it back in, or even add it as an optional 4th parameter if you like.

How to squash commits in git after they have been pushed?

On a branch I was able to do it like this (for the last 4 commits)

git checkout my_branch
git reset --soft HEAD~4
git commit
git push --force origin my_branch

SQL Query Where Field DOES NOT Contain $x

What kind of field is this? The IN operator cannot be used with a single field, but is meant to be used in subqueries or with predefined lists:

-- subquery
SELECT a FROM x WHERE x.b NOT IN (SELECT b FROM y);
-- predefined list
SELECT a FROM x WHERE x.b NOT IN (1, 2, 3, 6);

If you are searching a string, go for the LIKE operator (but this will be slow):

-- Finds all rows where a does not contain "text"
SELECT * FROM x WHERE x.a NOT LIKE '%text%';

If you restrict it so that the string you are searching for has to start with the given string, it can use indices (if there is an index on that field) and be reasonably fast:

-- Finds all rows where a does not start with "text"
SELECT * FROM x WHERE x.a NOT LIKE 'text%';

SQL: IF clause within WHERE clause

    WHERE OrderNumber LIKE CASE WHEN IsNumeric(@OrderNumber) = 1 THEN @OrderNumber ELSE  '%' + @OrderNumber END

In line case Condition will work properly.

How to get the number of days of difference between two dates on mysql?

Note if you want to count FULL 24h days between 2 dates, datediff can return wrong values for you.

As documentation states:

Only the date parts of the values are used in the calculation.

which results in

select datediff('2016-04-14 11:59:00', '2016-04-13 12:00:00')

returns 1 instead of expected 0.

Solution is using select timestampdiff(DAY, '2016-04-13 11:00:01', '2016-04-14 11:00:00'); (note the opposite order of arguments compared to datediff).

Some examples:

  • select timestampdiff(DAY, '2016-04-13 11:00:01', '2016-04-14 11:00:00'); returns 0
  • select timestampdiff(DAY, '2016-04-13 11:00:00', '2016-04-14 11:00:00'); returns 1
  • select timestampdiff(DAY, '2016-04-13 11:00:00', now()); returns how many full 24h days has passed since 2016-04-13 11:00:00 until now.

Hope it will help someone, because at first it isn't much obvious why datediff returns values which seems to be unexpected or wrong.

JavaScript loop through json array?

It is working. I just added square brackets to JSON data. The data is:

var data = [
    { 
        "id": "1",
        "msg": "hi", 
        "tid": "2013-05-05 23:35", 
        "fromWho": "[email protected]" 
    }, 
    { 
        "id": "2", 
        "msg": "there", 
        "tid": "2013-05-05 23:45", 
        "fromWho": "[email protected]"
    }
]

And the loop is:

for (var key in data) {
   if (data.hasOwnProperty(key)) {
         alert(data[key].id);
   }
} 

Unable to Build using MAVEN with ERROR - Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.1:compile

For my situation, I switched the value of "fork" to false, such as <fork>false</fork>. I do not understand why, hope someone could explain to me. Thanks in advance.

Select method in List<t> Collection

I have used a script but to make a join, maybe I can help you

string Email = String.Join(", ", Emails.Where(i => i.Email != "").Select(i => i.Email).Distinct());

Select first 10 distinct rows in mysql

Try this SELECT DISTINCT 10 * ...

Run reg command in cmd (bat file)?

You could also just create a Group Policy Preference and have it create the reg key for you. (no scripting involved)

PHP date yesterday

How easy :)

date("F j, Y", strtotime( '-1 days' ) );

Example:

echo date("Y-m-j H:i:s", strtotime( '-1 days' ) ); // 2018-07-18 07:02:43

Output:

2018-07-17 07:02:43

What's the pythonic way to use getters and setters?

You can use accessors/mutators (i.e. @attr.setter and @property) or not, but the most important thing is to be consistent!

If you're using @property to simply access an attribute, e.g.

class myClass:
    def __init__(a):
        self._a = a

    @property
    def a(self):
        return self._a

use it to access every* attribute! It would be a bad practice to access some attributes using @property and leave some other properties public (i.e. name without an underscore) without an accessor, e.g. do not do

class myClass:
    def __init__(a, b):
        self.a = a
        self.b = b

    @property
    def a(self):
        return self.a

Note that self.b does not have an explicit accessor here even though it's public.

Similarly with setters (or mutators), feel free to use @attribute.setter but be consistent! When you do e.g.

class myClass:
    def __init__(a, b):
        self.a = a
        self.b = b 

    @a.setter
    def a(self, value):
        return self.a = value

It's hard for me to guess your intention. On one hand you're saying that both a and b are public (no leading underscore in their names) so I should theoretically be allowed to access/mutate (get/set) both. But then you specify an explicit mutator only for a, which tells me that maybe I should not be able to set b. Since you've provided an explicit mutator I am not sure if the lack of explicit accessor (@property) means I should not be able to access either of those variables or you were simply being frugal in using @property.

*The exception is when you explicitly want to make some variables accessible or mutable but not both or you want to perform some additional logic when accessing or mutating an attribute. This is when I am personally using @property and @attribute.setter (otherwise no explicit acessors/mutators for public attributes).

Lastly, PEP8 and Google Style Guide suggestions:

PEP8, Designing for Inheritance says:

For simple public data attributes, it is best to expose just the attribute name, without complicated accessor/mutator methods. Keep in mind that Python provides an easy path to future enhancement, should you find that a simple data attribute needs to grow functional behavior. In that case, use properties to hide functional implementation behind simple data attribute access syntax.

On the other hand, according to Google Style Guide Python Language Rules/Properties the recommendation is to:

Use properties in new code to access or set data where you would normally have used simple, lightweight accessor or setter methods. Properties should be created with the @property decorator.

The pros of this approach:

Readability is increased by eliminating explicit get and set method calls for simple attribute access. Allows calculations to be lazy. Considered the Pythonic way to maintain the interface of a class. In terms of performance, allowing properties bypasses needing trivial accessor methods when a direct variable access is reasonable. This also allows accessor methods to be added in the future without breaking the interface.

and cons:

Must inherit from object in Python 2. Can hide side-effects much like operator overloading. Can be confusing for subclasses.

%Like% Query in spring JpaRepository

Found solution without @Query (actually I tried which one which is "accepted". However, it didn't work).

Have to return Page<Entity> instead of List<Entity>:

public interface EmployeeRepository 
                          extends PagingAndSortingRepository<Employee, Integer> {
    Page<Employee> findAllByNameIgnoreCaseStartsWith(String name, Pageable pageable);
}

IgnoreCase part was critical for achieving this!

Using Linq to group a list of objects into a new grouped list of list of objects

Still an old one, but answer from Lee did not give me the group.Key as result. Therefore, I am using the following statement to group a list and return a grouped list:

public IOrderedEnumerable<IGrouping<string, User>> groupedCustomerList;

groupedCustomerList =
        from User in userList
        group User by User.GroupID into newGroup
        orderby newGroup.Key
        select newGroup;

Each group now has a key, but also contains an IGrouping which is a collection that allows you to iterate over the members of the group.

What are the First and Second Level caches in (N)Hibernate?

There's a pretty good explanation of first level caching on the Streamline Logic blog.

Basically, first level caching happens on a per session basis where as second level caching can be shared across multiple sessions.

Sorting an ArrayList of objects using a custom sorting order

You shoud use the Arrays.sort function. The containing classes should implement Comparable.

OPENSSL file_get_contents(): Failed to enable crypto

Had same problem - it was somewhere in the ca certificate, so I used the ca bundle used for curl, and it worked. You can download the curl ca bundle here: https://curl.haxx.se/docs/caextract.html

For encryption and security issues see this helpful article:
https://www.venditan.com/labs/2014/06/26/ssl-and-php-streams-part-1-you-are-doing-it-wrongtm/432

Here is the example:

    $url = 'https://www.example.com/api/list';
    $cn_match = 'www.example.com';

    $data = array (     
        'apikey' => '[example api key here]',               
        'limit' => intval($limit),
        'offset' => intval($offset)
        );

    // use key 'http' even if you send the request to https://...
    $options = array(
        'http' => array(
            'header'  => "Content-type: application/x-www-form-urlencoded\r\n",
            'method'  => 'POST',                
            'content' => http_build_query($data)                
            )
        , 'ssl' => array(
            'verify_peer' => true,
            'cafile' => [path to file] . "cacert.pem",
            'ciphers' => 'HIGH:TLSv1.2:TLSv1.1:TLSv1.0:!SSLv3:!SSLv2',
            'CN_match' => $cn_match,
            'disable_compression' => true,
            )
        );

    $context  = stream_context_create($options);
    $response = file_get_contents($url, false, $context);

Hope that helps

How to run a program without an operating system?

How do you run a program all by itself without an operating system running?

You place your binary code to a place where processor looks for after rebooting (e.g. address 0 on ARM).

Can you create assembly programs that the computer can load and run at startup ( e.g. boot the computer from a flash drive and it runs the program that is on the drive)?

General answer to the question: it can be done. It's often referred to as "bare metal programming". To read from flash drive, you want to know what's USB, and you want to have some driver to work with this USB. The program on this drive would also have to be in some particular format, on some particular filesystem... This is something that boot loaders usually do, but your program could include its own bootloader so it's self-contained, if the firmware will only load a small block of code.

Many ARM boards let you do some of those things. Some have boot loaders to help you with basic setup.

Here you may find a great tutorial on how to do a basic operating system on a Raspberry Pi.

Edit: This article, and the whole wiki.osdev.org will anwer most of your questions http://wiki.osdev.org/Introduction

Also, if you don't want to experiment directly on hardware, you can run it as a virtual machine using hypervisors like qemu. See how to run "hello world" directly on virtualized ARM hardware here.

How to show and update echo on same line

The rest of answers are pretty good, but just wanted to add some extra information in case someone comes here looking for a solution to replace/update a multiline echo.

So I would like to share an example with you all. The following script was tried on a CentOS system and uses "timedatectl" command which basically prints some detailed time information of your system.

I decided to use that command as its output contains multiple lines and works perfectly for the example below:

#!/bin/bash
while true; do
  COMMAND=$(timedatectl) #Save command result in a var.
  echo "$COMMAND" #Print command result, including new lines.

  sleep 3 #Keep above's output on screen during 3 seconds before clearing it

  #Following code clears previously printed lines
  LINES=$(echo "$COMMAND" | wc -l) #Calculate number of lines for the output previously printed
  for (( i=1; i <= $(($LINES)); i++ ));do #For each line printed as a result of "timedatectl"
    tput cuu1 #Move cursor up by one line
    tput el #Clear the line
  done

done

The above will print the result of "timedatectl" forever and will replace the previous echo with updated results.

I have to mention that this code is only an example, but maybe not the best solution for you depending on your needs. A similar command that would do almost the same (at least visually) is "watch -n 3 timedatectl".

But that's a different story. :)

Hope that helps!

How I add Headers to http.get or http.post in Typescript and angular 2?

You can define a Headers object with a dictionary of HTTP key/value pairs, and then pass it in as an argument to http.get() and http.post() like this:

const headerDict = {
  'Content-Type': 'application/json',
  'Accept': 'application/json',
  'Access-Control-Allow-Headers': 'Content-Type',
}

const requestOptions = {                                                                                                                                                                                 
  headers: new Headers(headerDict), 
};

return this.http.get(this.heroesUrl, requestOptions)

Or, if it's a POST request:

const data = JSON.stringify(heroData);
return this.http.post(this.heroesUrl, data, requestOptions);

Since Angular 7 and up you have to use HttpHeaders class instead of Headers:

const requestOptions = {                                                                                                                                                                                 
  headers: new HttpHeaders(headerDict), 
};

SQL Server Group By Month

DECLARE @start [datetime] = 2010/4/1;

Should be...

DECLARE @start [datetime] = '2010-04-01';

The one you have is dividing 2010 by 4, then by 1, then converting to a date. Which is the 57.5th day from 1900-01-01.

Try SELECT @start after your initialisation to check if this is correct.

MySQL update CASE WHEN/THEN/ELSE

Try this

UPDATE `table` SET `uid` = CASE
    WHEN id = 1 THEN 2952
    WHEN id = 2 THEN 4925
    WHEN id = 3 THEN 1592
    ELSE `uid`
    END
WHERE id  in (1,2,3)

IE throws JavaScript Error: The value of the property 'googleMapsQuery' is null or undefined, not a Function object (works in other browsers)

So I had a similar situation with the same error. I forgot I changed the compatibility mode on my dev machine and I had a console.log command in my javascript as well. I changed compatibility mode back in IE, and removed the console.log command. No more issue.

Run/install/debug Android applications over Wi-Fi?

I wrote a simple script for Windows:

Step 1. Make a batch file with the below commands and call the file wifi_dedug.bat and copy the below contents:

    adb tcpip 5555
    pause
    adb shell "ip addr show wlan0  | grep 'inet ' | cut -d' ' -f6|cut -d/ -f1" > tmpFile 
    pause
    set /p ip= < tmpFile 
    @echo %ip%
    del tmpFile
    @echo %ip%
    adb connect %ip%
    pause

Step 2. connect your device to pc.

Step 3. start batch file (key enter when requested)

Step 4. disconnect your device and deploy/debug via wifi.

How to make the main content div fill height of screen with css

Using top: 40px and bottom: 40px (assuming your footer is also 40px) with no defined height, you can get this to work.

.header {
    width: 100%;
    height: 40px;
    position: absolute;
    top: 0;
    background-color:red;
}
.mainBody {
    width: 100%;
    top: 40px;
    bottom: 40px;
    position: absolute;
    background-color: gray;
}
.footer {
    width: 100%;
    height: 40px;
    position: absolute;
    bottom: 0;
    background-color: blue;
}

JSFiddle

What is difference between monolithic and micro kernel?

1.Monolithic Kernel (Pure Monolithic) :all

  • All Kernel Services From single component

    (-) addition/removal is not possible, less/Zero flexible

    (+) inter Component Communication is better

e.g. :- Traditional Unix

2.Micro Kernel :few

  • few services(Memory management ,CPU management,IPC etc) from core kernel, other services(File management,I/O management. etc.) from different layers/component

  • Split Approach [Some services is in privileged(kernel) mode and some are in Normal(user) mode]

    (+)flexible for changes/up-gradations

    (-)communication overhead

e.g.:- QNX etc.

3.Modular kernel(Modular Monolithic) :most

  • Combination of Micro and Monolithic kernel

  • Collection of Modules -- modules can be --> Static + Dynamic

  • Drivers come in the form of Modules

e.g. :- Linux Modern OS

Convert multiple rows into one with comma as separator

you can use stuff() to convert rows as comma separated values

select
EmployeeID,
stuff((
  SELECT ',' + FPProjectMaster.GroupName 
      FROM     FPProjectInfo AS t INNER JOIN
              FPProjectMaster ON t.ProjectID = FPProjectMaster.ProjectID
      WHERE  (t.EmployeeID = FPProjectInfo.EmployeeID)
              And t.STatusID = 1
              ORDER BY t.ProjectID
       for xml path('')
       ),1,1,'') as name_csv
from FPProjectInfo
group by EmployeeID;

Thanks @AlexKuznetsov for the reference to get this answer.

Installing jdk8 on ubuntu- "unable to locate package" update doesn't fix

Command Line option - Ubuntu

sudo apt-get install python-software-properties
sudo add-apt-repository ppa:webupd8team/java
sudo apt-get update

Then in terminal

sudo apt-get install oracle-java8-installer

When there are multiple Java installations on your System, the Java version to use as default can be chosen. To do this, execute the following command.

sudo update-alternatives --config java
sudo update-alternatives --config javac
sudo update-alternatives --config javaws

Edit - Manual Java Installation

Download oracle jdk

http://www.oracle.com/technetwork/java/javase/downloads/index.html

Extract zip into desired folder

 e.g  /usr/local/  after extract /usr/local/jdk1.8.0_65

Setup

sudo update-alternatives --install  /usr/bin/java java /usr/local/jdk1.8.0_65/bin/java 1
sudo update-alternatives --install  /usr/bin/javac javac /usr/local/jdk1.8.0_65/bin/javac 1
sudo update-alternatives --install  /usr/bin/javaws javaws /usr/local/jdk1.8.0_65/bin/javaws 1

sudo update-alternatives --set  java /usr/local/jdk1.8.0_65/bin/java
sudo update-alternatives --set  javac /usr/local/jdk1.8.0_65/bin/javac
sudo update-alternatives --set  javaws /usr/local/jdk1.8.0_65/bin/javaws

Edit /etc/environment set JAVA_HOME path for external applications like Eclipse and Idea

AngularJS - convert dates in controller

create a filter.js and you can make this as reusable

angular.module('yourmodule').filter('date', function($filter)
{
    return function(input)
    {
        if(input == null){ return ""; }
        var _date = $filter('date')(new Date(input), 'dd/MM/yyyy');
        return _date.toUpperCase();
    };
});

view

<span>{{ d.time | date }}</span>

or in controller

var filterdatetime = $filter('date')( yourdate );

Date filtering and formatting in Angular js.

Adding 30 minutes to time formatted as H:i in PHP

In order for that to work $time has to be a timestamp. You cannot pass in "10:00" or something like $time = date('H:i', '10:00'); which is what you seem to do, because then I get 0:30 and 1:30 as results too.

Try

$time = strtotime('10:00');

As an alternative, consider using DateTime (the below requires PHP 5.3 though):

$dt = DateTime::createFromFormat('H:i', '10:00'); // create today 10 o'clock
$dt->sub(new DateInterval('PT30M'));              // substract 30 minutes
echo $dt->format('H:i');                          // echo modified time
$dt->add(new DateInterval('PT1H'));               // add 1 hour
echo $dt->format('H:i');                          // echo modified time

or procedural if you don't like OOP

$dateTime = date_create_from_format('H:i', '10:00');
date_sub($dateTime, date_interval_create_from_date_string('30 minutes'));
echo date_format($dateTime, 'H:i');
date_add($dateTime, date_interval_create_from_date_string('1 hour'));
echo date_format($dateTime, 'H:i');

How can I get the count of line in a file in an efficient way?

All previous answers suggest to read though the whole file and count the amount of newlines you find while doing this. You commented some as "not effective" but thats the only way you can do that. A "line" is nothing else as a simple character inside the file. And to count that character you must have a look at every single character within the file.

I'm sorry, but you have no choice. :-)

Is there a way to take the first 1000 rows of a Spark Dataframe?

Limit is very simple, example limit first 50 rows

val df_subset = data.limit(50)

Razor Views not seeing System.Web.Mvc.HtmlHelper

I had run a project clean, and installed or reinstalled everything and was still getting lots of Intellisense errors, even though my site was compiling and running fine. Intellisense finally worked for me when I changed the version numbers in my web.config file in the Views folder. In my case I'm coding a module in Orchard, which runs in an MVC area, but I think this will help anyone using the latest release of MVC. Here is my web.config from the Views folder

    <?xml version="1.0"?>
    <configuration>
      <configSections>
        <sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
          <section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
          <section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
        </sectionGroup>
      </configSections>

      <system.web.webPages.razor>
        <host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
        <pages pageBaseType="Orchard.Mvc.ViewEngines.Razor.WebViewPage">
          <namespaces>
            <add namespace="System.Web.Mvc" />
            <add namespace="System.Web.Mvc.Ajax" />
            <add namespace="System.Web.Mvc.Html" />
            <add namespace="System.Web.Routing" />
            <add namespace="System.Linq" />
            <add namespace="System.Collections.Generic" />
          </namespaces>
        </pages>
      </system.web.webPages.razor>

      <system.web>

        <!--
            Enabling request validation in view pages would cause validation to occur
            after the input has already been processed by the controller. By default
            MVC performs request validation before a controller processes the input.
            To change this behavior apply the ValidateInputAttribute to a
            controller or action.
        -->
        <pages
            validateRequest="false"
            pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"
            pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL"
            userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL">
          <controls>
            <add assembly="System.Web.Mvc, Version=5.1.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35, processorArchitecture=MSIL" namespace="System.Web.Mvc" tagPrefix="mvc" />
          </controls>
        </pages>
      </system.web>

      <system.webServer>
        <validation validateIntegratedModeConfiguration="false" />

        <handlers>
          <remove name="BlockViewHandler"/>
          <add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
        </handlers>
      </system.webServer>
    </configuration>

HTTP Status 500 - Servlet.init() for servlet Dispatcher threw exception

You map your dispatcher on *.do:

<servlet-mapping>
   <servlet-name>Dispatcher</servlet-name>
   <url-pattern>*.do</url-pattern>
</servlet-mapping>

but your controller is mapped on an url without .do:

@RequestMapping("/editPresPage")

Try changing this to:

@RequestMapping("/editPresPage.do")

mappedBy reference an unknown target entity property

I know the answer by @Pascal Thivent has solved the issue. I would like to add a bit more to his answer to others who might be surfing this thread.

If you are like me in the initial days of learning and wrapping your head around the concept of using the @OneToMany annotation with the 'mappedBy' property, it also means that the other side holding the @ManyToOne annotation with the @JoinColumn is the 'owner' of this bi-directional relationship.

Also, mappedBy takes in the instance name (mCustomer in this example) of the Class variable as an input and not the Class-Type (ex:Customer) or the entity name(Ex:customer).

BONUS : Also, look into the orphanRemoval property of @OneToMany annotation. If it is set to true, then if a parent is deleted in a bi-directional relationship, Hibernate automatically deletes it's children.

How to display a date as iso 8601 format with PHP

Using the DateTime class available in PHP version 5.2 it would be done like this:

$datetime = new DateTime('17 Oct 2008');
echo $datetime->format('c');

See it in action

As of PHP 5.4 you can do this as a one-liner:

echo (new DateTime('17 Oct 2008'))->format('c');

How to host material icons offline?

I solved it using this package (@mdi/font) and importing it on main.js:

import '@mdi/font/css/materialdesignicons.css'

How to decode viewstate

Normally, ViewState should be decryptable if you have the machine-key, right? After all, ASP.net needs to decrypt it, and that is certainly not a black box.

Partly cherry-picking a commit with Git

I know I'm answering an old question, but it looks like there's a new way to do this with interactively checking out:

git checkout -p bc66559

Credit to Can I interactively pick hunks from another git commit?

How can I open a website in my web browser using Python?

Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get("http://www.python.org")

sqlalchemy IS NOT NULL select

In case anyone else is wondering, you can use is_ to generate foo IS NULL:

>>> from sqlalchemy.sql import column
>>> print column('foo').is_(None)
foo IS NULL
>>> print column('foo').isnot(None)
foo IS NOT NULL

Angular 2 'component' is not a known element

This convoluted framework is driving me nuts. Given that you defined the custom component in the the template of another component part of the SAME module, then you do not need to use exports in the module (e.g. app.module.ts). You simply need to specify the declaration in the @NgModule directive of the aforementioned module:

// app.module.ts

import { JsonInputComponent } from './json-input/json-input.component';

@NgModule({
  declarations: [
    AppComponent,
    JsonInputComponent
  ],
  ...

You do NOT need to import the JsonInputComponent (in this example) into AppComponent (in this example) to use the JsonInputComponent custom component in AppComponent template. You simply need to prefix the custom component with the module name of which both components have been defined (e.g. app):

<form [formGroup]="reactiveForm">
  <app-json-input formControlName="result"></app-json-input>
</form>

Notice app-json-input not json-input!

Demo here: https://github.com/lovefamilychildrenhappiness/AngularCustomComponentValidation

Delete data with foreign key in SQL Server table

SET foreign_key_checks = 0; DELETE FROM yourtable; SET foreign_key_checks = 1;

Change string color with NSAttributedString?

You can create NSAttributedString

NSDictionary *attributes = @{ NSForegroundColorAttributeName : [UIColor redColor] };
NSAttributedString *attrStr = [[NSAttributedString alloc] initWithString:@"My Color String" attributes:attrs];

OR NSMutableAttributedString to apply custom attributes with Ranges.

NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@%@", methodPrefix, method] attributes: @{ NSFontAttributeName : FONT_MYRIADPRO(48) }];
[attributedString addAttribute:NSFontAttributeName value:FONT_MYRIADPRO_SEMIBOLD(48) range:NSMakeRange(methodPrefix.length, method.length)];

Available Attributes: NSAttributedStringKey


UPDATE:

Swift 5.1

let message: String = greeting + someMessage
let paragraphStyle = NSMutableParagraphStyle()
paragraphStyle.lineSpacing = 2.0
    
// Note: UIFont(appFontFamily:ofSize:) is extended init.
let regularAttributes: [NSAttributedString.Key : Any] = [.font : UIFont(appFontFamily: .regular, ofSize: 15)!, .paragraphStyle : paragraphStyle]
let boldAttributes = [NSAttributedString.Key.font : UIFont(appFontFamily: .semiBold, ofSize: 15)!]

let mutableString = NSMutableAttributedString(string: message, attributes: regularAttributes)
mutableString.addAttributes(boldAttributes, range: NSMakeRange(0, greeting.count))

How can I generate an ObjectId with mongoose?

You can find the ObjectId constructor on require('mongoose').Types. Here is an example:

var mongoose = require('mongoose');
var id = mongoose.Types.ObjectId();

id is a newly generated ObjectId.

You can read more about the Types object at Mongoose#Types documentation.

How do I do word Stemming or Lemmatization?

Based on various answers on Stack Overflow and blogs I've come across, this is the method I'm using, and it seems to return real words quite well. The idea is to split the incoming text into an array of words (use whichever method you'd like), and then find the parts of speech (POS) for those words and use that to help stem and lemmatize the words.

You're sample above doesn't work too well, because the POS can't be determined. However, if we use a real sentence, things work much better.

import nltk
from nltk.corpus import wordnet

lmtzr = nltk.WordNetLemmatizer().lemmatize


def get_wordnet_pos(treebank_tag):
    if treebank_tag.startswith('J'):
        return wordnet.ADJ
    elif treebank_tag.startswith('V'):
        return wordnet.VERB
    elif treebank_tag.startswith('N'):
        return wordnet.NOUN
    elif treebank_tag.startswith('R'):
        return wordnet.ADV
    else:
        return wordnet.NOUN


def normalize_text(text):
    word_pos = nltk.pos_tag(nltk.word_tokenize(text))
    lemm_words = [lmtzr(sw[0], get_wordnet_pos(sw[1])) for sw in word_pos]

    return [x.lower() for x in lemm_words]

print(normalize_text('cats running ran cactus cactuses cacti community communities'))
# ['cat', 'run', 'ran', 'cactus', 'cactuses', 'cacti', 'community', 'community']

print(normalize_text('The cactus ran to the community to see the cats running around cacti between communities.'))
# ['the', 'cactus', 'run', 'to', 'the', 'community', 'to', 'see', 'the', 'cat', 'run', 'around', 'cactus', 'between', 'community', '.']

UIView with rounded corners and drop shadow?

var shadows = UIView()
shadows.frame = view.frame
shadows.clipsToBounds = false
view.addSubview(shadows)


let shadowPath0 = UIBezierPath(roundedRect: shadows.bounds, cornerRadius: 10)
let layer0 = CALayer()
layer0.shadowPath = shadowPath0.cgPath
layer0.shadowColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.23).cgColor
layer0.shadowOpacity = 1
layer0.shadowRadius = 6
layer0.shadowOffset = CGSize(width: 0, height: 3)
layer0.bounds = shadows.bounds
layer0.position = shadows.center

shadows.layer.addSublayer(layer0)

Removing duplicate characters from a string

 mylist=["ABA", "CAA", "ADA"]
 results=[]
 for item in mylist:
     buffer=[]
     for char in item:
         if char not in buffer:
             buffer.append(char)
     results.append("".join(buffer))
    
 print(results)

 output
 ABA
 CAA
 ADA
 ['AB', 'CA', 'AD']

Export a graph to .eps file with R

The easiest way I've found to create postscripts is the following, using the setEPS() command:

setEPS()
postscript("whatever.eps")
plot(rnorm(100), main="Hey Some Data")
dev.off()

Download history stock prices automatically from yahoo finance in python

Short answer: Yes. Use Python's urllib to pull the historical data pages for the stocks you want. Go with Yahoo! Finance; Google is both less reliable, has less data coverage, and is more restrictive in how you can use it once you have it. Also, I believe Google specifically prohibits you from scraping the data in their ToS.

Longer answer: This is the script I use to pull all the historical data on a particular company. It pulls the historical data page for a particular ticker symbol, then saves it to a csv file named by that symbol. You'll have to provide your own list of ticker symbols that you want to pull.

import urllib

base_url = "http://ichart.finance.yahoo.com/table.csv?s="
def make_url(ticker_symbol):
    return base_url + ticker_symbol

output_path = "C:/path/to/output/directory"
def make_filename(ticker_symbol, directory="S&P"):
    return output_path + "/" + directory + "/" + ticker_symbol + ".csv"

def pull_historical_data(ticker_symbol, directory="S&P"):
    try:
        urllib.urlretrieve(make_url(ticker_symbol), make_filename(ticker_symbol, directory))
    except urllib.ContentTooShortError as e:
        outfile = open(make_filename(ticker_symbol, directory), "w")
        outfile.write(e.content)
        outfile.close()

How to pass parameters to a Script tag?

Create an attribute that contains a list of the parameters, like so:

<script src="http://path/to/widget.js" data-params="1, 3"></script>

Then, in your JavaScript, get the parameters as an array:

var script = document.currentScript || 
/*Polyfill*/ Array.prototype.slice.call(document.getElementsByTagName('script')).pop();

var params = (script.getAttribute('data-params') || '').split(/, */);

params[0]; // -> 1
params[1]; // -> 3

Position Relative vs Absolute?

Let's discuss a scenario to explain the difference between absolute vs relative.

Inside the body element say you have an header element whose height is 95% of viewheight i.e 95vh. Within this container you placed an image and reduced it's opacity to say 0.5. And now you want to place a logo image near the top left corner. I hope you understood the scenario. So you will have a lighter image in the header section with a logo on the top of it at the specified position.

But before starting this, i have set margin and padding to 0 like this

*{
   margin:0px;
   padding:0px;
   box-sizing: border-box; 
}

This ensures no default margins and padding is applied to elements.

So you can achieve your requirement in two ways.

First Way

  • you give a class to the image say logo.
  • in css you write

    .logo{ float:left; margin-top:40px; margin-left:40px; }

  • this placed the logo to the 40px from the top and left of the enclosing parent which is the header. The image will appear as if it placed as desired.

But my friend this is a bad design as to place an image you unnecessarily consumed so much of space around by giving it some margin when it was not required. All you needed is to place the image to that location. You managed it by cushioning it with margins around. The margin took space and pushed it's content deeper giving an impression that it is positioned exactly where you wanted. Hope you understood the issue by working it around like this. You are taking more space than required to place just an image at the desired location.

Now let's try a different approach.

Second Way

  • the image with logo class is inside the header element with say header class. So the parent class is header and the child class is logo as before.
  • you set the position property of the header class to relative like this

    .header{ position: relative; }

  • then you added the following properties to the logo class

    .logo{ position:absolute; top:40px; left:40px }

There you go. You placed the image at exactly the same place. There won't be any apparent difference in the positioning from the naked eye between the first approach and second approach. But if you inspect the image element , you will find that it has not taken any extra space. It's occupying exactly the same area as much as it's own width and height.

So how is this possible? I said to the image logo class that you will be placed relative to the header class as you are the child of this class and that i specifically mentioned it's position as relative. So that any child of it's will be placed relative to it's top left corner. And that Your position need to be fixed inside this parent element. so you are given absolute. And That you need to move a little from top and left to the position i want you to be. Hence you are given top and left property with 40px as value. In this way you will be placed relative to your parent only. So if tomorrow i move your parent up or down or just anywhere, you will always be 40px to the top and left of your parent header's top left corner. So your position is fixed inside your parent no matter whether your parent's position is fixed or not in future(as it is not absolute like you).

So use relative and absolute for parent and child respectively. Secondly use it when you want to only place the child element at some location inside it's parent element. Do not use fillers like margins to push it forcibly. Give parent relative value and child which you want to move, the absolute value. Specify top, left bottom or right property to child class to place it inside parent anywhere you want.

Thanks.

How to change the default encoding to UTF-8 for Apache?

Where all the HTML files are in UTF-8 and don't have meta tags for content type, I was only able to set the needed default for these files to be sent by Apache 2.4 by adding both directives:

AddLanguage ru .html
AddCharset UTF-8 .html

How to execute INSERT statement using JdbcTemplate class from Spring Framework

If you use spring-boot, you don't need to create a DataSource class, just specify the data url/username/password/driver in application.properties, then you can simply @Autowired it.

@Repository
public class JdbcRepository {

    private final JdbcTemplate jdbcTemplate;

    @Autowired
    public DynamicRepository(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }

    public void insert() {
        jdbcTemplate.update("INSERT INTO BOOK (name, description) VALUES ('book name', 'book description')");
    }
}

Example of application.properties:

#Basic Spring Boot Config for Oracle
spring.datasource.url=jdbc:oracle:thin:@(DESCRIPTION=(ADDRESS=(PROTOCOL=TCP)(HOST=YourHostIP)(PORT=YourPort))(CONNECT_DATA=(SERVER=dedicated)(SERVICE_NAME=YourServiceName)))
spring.datasource.username=username
spring.datasource.password=password
spring.datasource.driver-class-name=oracle.jdbc.OracleDriver

#hibernate config
spring.jpa.database-platform=org.hibernate.dialect.Oracle10gDialect

Then add the driver and connection pool dependencies in pom.xml

<dependency>
    <groupId>com.oracle</groupId>
    <artifactId>ojdbc7</artifactId>
    <version>12.1.0.1</version>
</dependency>

<!-- HikariCP connection pool -->
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>2.6.0</version>
</dependency>

See the official doc for more details.

Pandas every nth row

There is an even simpler solution to the accepted answer that involves directly invoking df.__getitem__.

df = pd.DataFrame('x', index=range(5), columns=list('abc'))
df

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x
3  x  x  x
4  x  x  x

For example, to get every 2 rows, you can do

df[::2]

   a  b  c
0  x  x  x
2  x  x  x
4  x  x  x

There's also GroupBy.first/GroupBy.head, you group on the index:

df.index // 2
# Int64Index([0, 0, 1, 1, 2], dtype='int64')

df.groupby(df.index // 2).first()
# Alternatively,
# df.groupby(df.index // 2).head(1)

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

The index is floor-divved by the stride (2, in this case). If the index is non-numeric, instead do

# df.groupby(np.arange(len(df)) // 2).first()
df.groupby(pd.RangeIndex(len(df)) // 2).first()

   a  b  c
0  x  x  x
1  x  x  x
2  x  x  x

"And" and "Or" troubles within an IF statement

This is not an answer, but too long for a comment.

In reply to JP's answers / comments, I have run the following test to compare the performance of the 2 methods. The Profiler object is a custom class - but in summary, it uses a kernel32 function which is fairly accurate (Private Declare Sub GetLocalTime Lib "kernel32" (lpSystemTime As SYSTEMTIME)).

Sub test()

  Dim origNum As String
  Dim creditOrDebit As String
  Dim b As Boolean
  Dim p As Profiler
  Dim i As Long

  Set p = New_Profiler

  origNum = "30062600006"
  creditOrDebit = "D"

  p.startTimer ("nested_ifs")

  For i = 1 To 1000000

    If creditOrDebit = "D" Then
      If origNum = "006260006" Then
        b = True
      ElseIf origNum = "30062600006" Then
        b = True
      End If
    End If

  Next i

  p.stopTimer ("nested_ifs")
  p.startTimer ("or_and")

  For i = 1 To 1000000

    If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
      b = True
    End If

  Next i

  p.stopTimer ("or_and")

  p.printReport

End Sub

The results of 5 runs (in ms for 1m loops):

20-Jun-2012 19:28:25
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:26
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:27
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 125 - Last Run: 125 - Average Run: 125

20-Jun-2012 19:28:28
nested_ifs (x1): 140 - Last Run: 140 - Average Run: 140
or_and (x1): 141 - Last Run: 141 - Average Run: 141

20-Jun-2012 19:28:29
nested_ifs (x1): 156 - Last Run: 156 - Average Run: 156
or_and (x1): 125 - Last Run: 125 - Average Run: 125

Note

If creditOrDebit is not "D", JP's code runs faster (around 60ms vs. 125ms for the or/and code).

How to get data from Magento System Configuration

$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName');

sectionName, groupName and fieldName are present in etc/system.xml file of your module.

The above code will automatically fetch config value of currently viewed store.

If you want to fetch config value of any other store than the currently viewed store then you can specify store ID as the second parameter to the getStoreConfig function as below:

$store = Mage::app()->getStore(); // store info
$configValue = Mage::getStoreConfig('sectionName/groupName/fieldName', $store);

How do I make a <div> move up and down when I'm scrolling the page?

Here is the Jquery Code

$(document).ready(function () {
     var el = $('#Container');
        var originalelpos = el.offset().top; // take it where it originally is on the page

        //run on scroll
        $(window).scroll(function () {
            var el = $('#Container'); // important! (local)
            var elpos = el.offset().top; // take current situation
            var windowpos = $(window).scrollTop();
            var finaldestination = windowpos + originalelpos;
            el.stop().animate({ 'top': finaldestination }, 1000);
        });
    });

R dplyr: Drop multiple columns

If you have a special character in the column names, either select or select_may not work as expected. This property of dplyr of using ".". To refer to the data set in the question, the following line can be used to solve this problem:

drop.cols <- c('Sepal.Length', 'Sepal.Width')
  iris %>% .[,setdiff(names(.),drop.cols)]

How do I convert a Django QuerySet into list of dicts?

You can use the values() method on the dict you got from the Django model field you make the queries on and then you can easily access each field by a index value.

Call it like this -

myList = dictOfSomeData.values()
itemNumberThree = myList[2] #If there's a value in that index off course...

css absolute position won't work with margin-left:auto margin-right: auto

When you are defining styles for division which is positioned absolutely, they specifying margins are useless. Because they are no longer inside the regular DOM tree.

You can use float to do the trick.

.divtagABS {
    float: left;
    margin-left: auto;  
    margin-right:auto;
 }

Structure padding and packing

(The above answers explained the reason quite clearly, but seems not totally clear about the size of padding, so, I will add an answer according to what I learned from The Lost Art of Structure Packing, it has evolved to not limit to C, but also applicable to Go, Rust.)


Memory align (for struct)

Rules:

  • Before each individual member, there will be padding so that to make it start at an address that is divisible by its size.
    e.g on 64 bit system,int should start at address divisible by 4, and long by 8, short by 2.
  • char and char[] are special, could be any memory address, so they don't need padding before them.
  • For struct, other than the alignment need for each individual member, the size of whole struct itself will be aligned to a size divisible by size of largest individual member, by padding at end.
    e.g if struct's largest member is long then divisible by 8, int then by 4, short then by 2.

Order of member:

  • The order of member might affect actual size of struct, so take that in mind. e.g the stu_c and stu_d from example below have the same members, but in different order, and result in different size for the 2 structs.

Address in memory (for struct)

Rules:

  • 64 bit system
    Struct address starts from (n * 16) bytes. (You can see in the example below, all printed hex addresses of structs end with 0.)
    Reason: the possible largest individual struct member is 16 bytes (long double).
  • (Update) If a struct only contains a char as member, its address could start at any address.

Empty space:

  • Empty space between 2 structs could be used by non-struct variables that could fit in.
    e.g in test_struct_address() below, the variable x resides between adjacent struct g and h.
    No matter whether x is declared, h's address won't change, x just reused the empty space that g wasted.
    Similar case for y.

Example

(for 64 bit system)

memory_align.c:

/**
 * Memory align & padding - for struct.
 * compile: gcc memory_align.c
 * execute: ./a.out
 */ 
#include <stdio.h>

// size is 8, 4 + 1, then round to multiple of 4 (int's size),
struct stu_a {
    int i;
    char c;
};

// size is 16, 8 + 1, then round to multiple of 8 (long's size),
struct stu_b {
    long l;
    char c;
};

// size is 24, l need padding by 4 before it, then round to multiple of 8 (long's size),
struct stu_c {
    int i;
    long l;
    char c;
};

// size is 16, 8 + 4 + 1, then round to multiple of 8 (long's size),
struct stu_d {
    long l;
    int i;
    char c;
};

// size is 16, 8 + 4 + 1, then round to multiple of 8 (double's size),
struct stu_e {
    double d;
    int i;
    char c;
};

// size is 24, d need align to 8, then round to multiple of 8 (double's size),
struct stu_f {
    int i;
    double d;
    char c;
};

// size is 4,
struct stu_g {
    int i;
};

// size is 8,
struct stu_h {
    long l;
};

// test - padding within a single struct,
int test_struct_padding() {
    printf("%s: %ld\n", "stu_a", sizeof(struct stu_a));
    printf("%s: %ld\n", "stu_b", sizeof(struct stu_b));
    printf("%s: %ld\n", "stu_c", sizeof(struct stu_c));
    printf("%s: %ld\n", "stu_d", sizeof(struct stu_d));
    printf("%s: %ld\n", "stu_e", sizeof(struct stu_e));
    printf("%s: %ld\n", "stu_f", sizeof(struct stu_f));

    printf("%s: %ld\n", "stu_g", sizeof(struct stu_g));
    printf("%s: %ld\n", "stu_h", sizeof(struct stu_h));

    return 0;
}

// test - address of struct,
int test_struct_address() {
    printf("%s: %ld\n", "stu_g", sizeof(struct stu_g));
    printf("%s: %ld\n", "stu_h", sizeof(struct stu_h));
    printf("%s: %ld\n", "stu_f", sizeof(struct stu_f));

    struct stu_g g;
    struct stu_h h;
    struct stu_f f1;
    struct stu_f f2;
    int x = 1;
    long y = 1;

    printf("address of %s: %p\n", "g", &g);
    printf("address of %s: %p\n", "h", &h);
    printf("address of %s: %p\n", "f1", &f1);
    printf("address of %s: %p\n", "f2", &f2);
    printf("address of %s: %p\n", "x", &x);
    printf("address of %s: %p\n", "y", &y);

    // g is only 4 bytes itself, but distance to next struct is 16 bytes(on 64 bit system) or 8 bytes(on 32 bit system),
    printf("space between %s and %s: %ld\n", "g", "h", (long)(&h) - (long)(&g));

    // h is only 8 bytes itself, but distance to next struct is 16 bytes(on 64 bit system) or 8 bytes(on 32 bit system),
    printf("space between %s and %s: %ld\n", "h", "f1", (long)(&f1) - (long)(&h));

    // f1 is only 24 bytes itself, but distance to next struct is 32 bytes(on 64 bit system) or 24 bytes(on 32 bit system),
    printf("space between %s and %s: %ld\n", "f1", "f2", (long)(&f2) - (long)(&f1));

    // x is not a struct, and it reuse those empty space between struts, which exists due to padding, e.g between g & h,
    printf("space between %s and %s: %ld\n", "x", "f2", (long)(&x) - (long)(&f2));
    printf("space between %s and %s: %ld\n", "g", "x", (long)(&x) - (long)(&g));

    // y is not a struct, and it reuse those empty space between struts, which exists due to padding, e.g between h & f1,
    printf("space between %s and %s: %ld\n", "x", "y", (long)(&y) - (long)(&x));
    printf("space between %s and %s: %ld\n", "h", "y", (long)(&y) - (long)(&h));

    return 0;
}

int main(int argc, char * argv[]) {
    test_struct_padding();
    // test_struct_address();

    return 0;
}

Execution result - test_struct_padding():

stu_a: 8
stu_b: 16
stu_c: 24
stu_d: 16
stu_e: 16
stu_f: 24
stu_g: 4
stu_h: 8

Execution result - test_struct_address():

stu_g: 4
stu_h: 8
stu_f: 24
address of g: 0x7fffd63a95d0  // struct variable - address dividable by 16,
address of h: 0x7fffd63a95e0  // struct variable - address dividable by 16,
address of f1: 0x7fffd63a95f0 // struct variable - address dividable by 16,
address of f2: 0x7fffd63a9610 // struct variable - address dividable by 16,
address of x: 0x7fffd63a95dc  // non-struct variable - resides within the empty space between struct variable g & h.
address of y: 0x7fffd63a95e8  // non-struct variable - resides within the empty space between struct variable h & f1.
space between g and h: 16
space between h and f1: 16
space between f1 and f2: 32
space between x and f2: -52
space between g and x: 12
space between x and y: 12
space between h and y: 8

Thus address start for each variable is g:d0 x:dc h:e0 y:e8

enter image description here