Programs & Examples On #Setthreadaffinitymask

What's the difference between window.location= and window.location.replace()?

window.location adds an item to your history in that you can (or should be able to) click "Back" and go back to the current page.

window.location.replace replaces the current history item so you can't go back to it.

See window.location:

assign(url): Load the document at the provided URL.

replace(url):Replace the current document with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session history, meaning the user won't be able to use the Back button to navigate to it.

Oh and generally speaking:

window.location.href = url;

is favoured over:

window.location = url;

iterating over and removing from a map

As of Java 8 you could do this as follows:

map.entrySet().removeIf(e -> <boolean expression>);

Oracle Docs: entrySet()

The set is backed by the map, so changes to the map are reflected in the set, and vice-versa

How to include external Python code to use in other files?

I've found the python inspect module to be very useful

For example with teststuff.py

import inspect

def dostuff():
    return __name__

DOSTUFF_SOURCE = inspect.getsource(dostuff)

if __name__ == "__main__":

    dostuff()

And from the another script or the python console

import teststuff

exec(DOSTUFF_SOURCE)

dostuff()

And now dostuff should be in the local scope and dostuff() will return the console or scripts _name_ whereas executing test.dostuff() will return the python modules name.

Java - ignore exception and continue

Printing the STACK trace, logging it or send message to the user, are very bad ways to process the exceptions. Does any one can describe solutions to fix the exception in proper steps then can trying the broken instruction again?

Generate fixed length Strings filled with whitespaces

This code works great. Expected output

  String ItemNameSpacing = new String(new char[10 - masterPojos.get(i).getName().length()]).replace('\0', ' ');
  printData +=  masterPojos.get(i).getName()+ "" + ItemNameSpacing + ":   " + masterPojos.get(i).getItemQty() +" "+ masterPojos.get(i).getItemMeasure() + "\n";

Happy Coding!!

How to keep a git branch in sync with master

The accepted answer via git merge will get the job done but leaves a messy commit hisotry, correct way should be 'rebase' via the following steps(assuming you want to keep your feature branch in sycn with develop before you do the final push before PR).

1 git fetch from your feature branch (make sure the feature branch you are working on is update to date)

2 git rebase origin/develop

3 if any conflict shall arise, resolve them one by one

4 use git rebase --continue once all conflicts are dealt with

5 git push --force

Why use Gradle instead of Ant or Maven?

Gradle can be used for many purposes - it's a much better Swiss army knife than Ant - but it's specifically focused on multi-project builds.

First of all, Gradle is a dependency programming tool which also means it's a programming tool. With Gradle you can execute any random task in your setup and Gradle will make sure all declared dependecies are properly and timely executed. Your code can be spread across many directories in any kind of layout (tree, flat, scattered, ...).

Gradle has two distinct phases: evaluation and execution. Basically, during evaluation Gradle will look for and evaluate build scripts in the directories it is supposed to look. During execution Gradle will execute tasks which have been loaded during evaluation taking into account task inter-dependencies.

On top of these dependency programming features Gradle adds project and JAR dependency features by intergration with Apache Ivy. As you know Ivy is a much more powerful and much less opinionated dependency management tool than say Maven.

Gradle detects dependencies between projects and between projects and JARs. Gradle works with Maven repositories (download and upload) like the iBiblio one or your own repositories but also supports and other kind of repository infrastructure you might have.

In multi-project builds Gradle is both adaptable and adapts to the build's structure and architecture. You don't have to adapt your structure or architecture to your build tool as would be required with Maven.

Gradle tries very hard not to get in your way, an effort Maven almost never makes. Convention is good yet so is flexibility. Gradle gives you many more features than Maven does but most importantly in many cases Gradle will offer you a painless transition path away from Maven.

How To Set Up GUI On Amazon EC2 Ubuntu server

This can be done. Following are the steps to setup the GUI

Create new user with password login

sudo useradd -m awsgui
sudo passwd awsgui
sudo usermod -aG admin awsgui

sudo vim /etc/ssh/sshd_config # edit line "PasswordAuthentication" to yes

sudo /etc/init.d/ssh restart

Setting up ui based ubuntu machine on AWS.

In security group open port 5901. Then ssh to the server instance. Run following commands to install ui and vnc server:

sudo apt-get update
sudo apt-get install ubuntu-desktop
sudo apt-get install vnc4server

Then run following commands and enter the login password for vnc connection:

su - awsgui

vncserver

vncserver -kill :1

vim /home/awsgui/.vnc/xstartup

Then hit the Insert key, scroll around the text file with the keyboard arrows, and delete the pound (#) sign from the beginning of the two lines under the line that says "Uncomment the following two lines for normal desktop." And on the second line add "sh" so the line reads

exec sh /etc/X11/xinit/xinitrc. 

When you're done, hit Ctrl + C on the keyboard, type :wq and hit Enter.

Then start vnc server again.

vncserver

You can download xtightvncviewer to view desktop(for Ubutnu) from here https://help.ubuntu.com/community/VNC/Clients

In the vnc client, give public DNS plus ":1" (e.g. www.example.com:1). Enter the vnc login password. Make sure to use a normal connection. Don't use the key files.

Additional guide available here: http://www.serverwatch.com/server-tutorials/setting-up-vnc-on-ubuntu-in-the-amazon-ec2-Page-3.html

Mac VNC client can be downloaded from here: https://www.realvnc.com/en/connect/download/viewer/

Port opening on console

sudo iptables -A INPUT -p tcp --dport 5901 -j ACCEPT

If the grey window issue comes. Mostly because of ".vnc/xstartup" file on different user. So run the vnc server also on same user instead of "awsgui" user.

vncserver

Any way to make plot points in scatterplot more transparent in R?

Transparency can be coded in the color argument as well. It is just two more hex numbers coding a transparency between 0 (fully transparent) and 255 (fully visible). I once wrote this function to add transparency to a color vector, maybe it is usefull here?

addTrans <- function(color,trans)
{
  # This function adds transparancy to a color.
  # Define transparancy with an integer between 0 and 255
  # 0 being fully transparant and 255 being fully visable
  # Works with either color and trans a vector of equal length,
  # or one of the two of length 1.

  if (length(color)!=length(trans)&!any(c(length(color),length(trans))==1)) stop("Vector lengths not correct")
  if (length(color)==1 & length(trans)>1) color <- rep(color,length(trans))
  if (length(trans)==1 & length(color)>1) trans <- rep(trans,length(color))

  num2hex <- function(x)
  {
    hex <- unlist(strsplit("0123456789ABCDEF",split=""))
    return(paste(hex[(x-x%%16)/16+1],hex[x%%16+1],sep=""))
  }
  rgb <- rbind(col2rgb(color),trans)
  res <- paste("#",apply(apply(rgb,2,num2hex),2,paste,collapse=""),sep="")
  return(res)
}

Some examples:

cols <- sample(c("red","green","pink"),100,TRUE)

# Fully visable:
plot(rnorm(100),rnorm(100),col=cols,pch=16,cex=4)

# Somewhat transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,200),pch=16,cex=4)

# Very transparant:
plot(rnorm(100),rnorm(100),col=addTrans(cols,100),pch=16,cex=4)

ImageView - have height match width?

Maybe this will answer your question:

<ImageView
    android:id="@+id/cover_image"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:scaleType="fitCenter"
    android:adjustViewBounds="true" />

You can ignore the scaleType attribute for this particular situation.

FPDF error: Some data has already been output, can't send PDF

For fpdf to work properly, there cannot be any output at all beside what fpdf generates. For example, this will work:

<?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

While this will not (note the leading space before the opening <? tag)

 <?php
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

Also, this will not work either (the echo will break it):

<?php
echo "About to create pdf";
$pdf = new FPDF();
$pdf->AddPage();
$pdf->SetFont('Arial','B',16);
$pdf->Cell(40,10,'Hello World!');
$pdf->Output();
?>

I'm not sure about the drupal side of things, but I know that absolutely zero non-fpdf output is a requirement for fpdf to work.


add ob_start (); at the top and at the end add ob_end_flush();

<?php
    ob_start();
    require('fpdf.php');
    $pdf = new FPDF();
    $pdf->AddPage();
    $pdf->SetFont('Arial','B',16);
    $pdf->Cell(40,10,'Hello World!');
    $pdf->Output();
    ob_end_flush(); 
?>

give me an error as below:
FPDF error: Some data has already been output, can't send PDF

to over come this error: go to fpdf.php in that,goto line number 996

function Output($name='', $dest='')

after that make changes like this:

function Output($name='', $dest='') {   
    ob_clean();     //Output PDF to so

Hi do you have a session header on the top of your page. or any includes If you have then try to add this codes on top pf your page it should works fine.

<?

while (ob_get_level())
ob_end_clean();
header("Content-Encoding: None", true);

?>

cheers :-)


In my case i had set:

ini_set('display_errors', 'on');
error_reporting(E_ALL | E_STRICT);

When i made the request to generate the report, some warnings were displayed in the browser (like the usage of deprecated functions).
Turning off the display_errors option, the report was generated successfully.

Starting with Zend Tutorial - Zend_DB_Adapter throws Exception: "SQLSTATE[HY000] [2002] No such file or directory"

i had this problem when running the magento indexer in osx. and yes its related to php problem when connecting to mysql through pdo

in mac osx xampp, to fix this you have create symbolic link to directory /var/mysql, here is how

cd /var/mysql && sudo ln -s /Applications/XAMPP/xamppfiles/var/mysql/mysql.sock

if the directory /var/mysql doesnt exist, we must create it with

sudo mkdir /var/mysql

Multiple conditions in WHILE loop

If your code, if the user enters 'X' (for instance), when you reach the while condition evaluation it will determine that 'X' is differente from 'n' (nChar != 'n') which will make your loop condition true and execute the code inside of your loop. The second condition is not even evaluated.

Angular 2 - NgFor using numbers instead collections

You can use lodash:

@Component({
  selector: 'board',
  template: `
<div *ngFor="let i of range">
{{i}}
</div>
`,
  styleUrls: ['./board.component.css']
})
export class AppComponent implements OnInit {
  range = _.range(8);
}

I didn't test code but it should work.

How to show Alert Message like "successfully Inserted" after inserting to DB using ASp.net MVC3

Little Edit

Try adding

return new JavascriptResult() { Script = "alert('Successfully registered');" };

in place of

return RedirectToAction("Index");

Conditionally displaying JSF components

Yes, use the rendered attribute.

<h:form rendered="#{some boolean condition}">

You usually tie it to the model rather than letting the model grab the component and manipulate it.

E.g.

<h:form rendered="#{bean.booleanValue}" />
<h:form rendered="#{bean.intValue gt 10}" />
<h:form rendered="#{bean.objectValue eq null}" />
<h:form rendered="#{bean.stringValue ne 'someValue'}" />
<h:form rendered="#{not empty bean.collectionValue}" />
<h:form rendered="#{not bean.booleanValue and bean.intValue ne 0}" />
<h:form rendered="#{bean.enumValue eq 'ONE' or bean.enumValue eq 'TWO'}" />

Note the importance of keyword based EL operators such as gt, ge, le and lt instead of >, >=, <= and < as angle brackets < and > are reserved characters in XML. See also this related Q&A: Error parsing XHTML: The content of elements must consist of well-formed character data or markup.

As to your specific use case, let's assume that the link is passing a parameter like below:

<a href="page.xhtml?form=1">link</a>

You can then show the form as below:

<h:form rendered="#{param.form eq '1'}">

(the #{param} is an implicit EL object referring to a Map representing the request parameters)

See also:

How can I emulate a get request exactly like a web browser?

Are you sure the curl module honors ini_set('user_agent',...)? There is an option CURLOPT_USERAGENT described at http://docs.php.net/function.curl-setopt.
Could there also be a cookie tested by the server? That you can handle by using CURLOPT_COOKIE, CURLOPT_COOKIEFILE and/or CURLOPT_COOKIEJAR.

edit: Since the request uses https there might also be error in verifying the certificate, see CURLOPT_SSL_VERIFYPEER.

$url="https://new.aol.com/productsweb/subflows/ScreenNameFlow/AjaxSNAction.do?s=username&f=firstname&l=lastname";
$agent= 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.0.3705; .NET CLR 1.1.4322)';

$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_VERBOSE, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERAGENT, $agent);
curl_setopt($ch, CURLOPT_URL,$url);
$result=curl_exec($ch);
var_dump($result);

How to sum data.frame column values?

to order after the colsum :

order(colSums(people),decreasing=TRUE)

if more than 20+ columns

order(colSums(people[,c(5:25)],decreasing=TRUE) ##in case of keeping the first 4 columns remaining.

SQL Query To Obtain Value that Occurs more than once

For postgresql:

SELECT * AS rec 
FROM (
    SELECT lastname, COUNT(*) AS counter 
    FROM students 
    GROUP BY lastname) AS tbl 
WHERE counter > 1;

SQL Call Stored Procedure for each Row without using a cursor

A better solution for this is to

  1. Copy/past code of Stored Procedure
  2. Join that code with the table for which you want to run it again (for each row)

This was you get a clean table-formatted output. While if you run SP for every row, you get a separate query result for each iteration which is ugly.

SQL: How to get the id of values I just INSERTed?

In TransactSQL, you can use OUTPUT clause to achieve that.

INSERT INTO my_table(col1,col2,col3) OUTPUT INSERTED.id VALUES('col1Value','col2Value','col3Value')

FRI: http://msdn.microsoft.com/en-us/library/ms177564.aspx

Limiting number of displayed results when using ngRepeat

Use limitTo filter to display a limited number of results in ng-repeat.

<ul class="phones">
      <li ng-repeat="phone in phones | limitTo:5">
        {{phone.name}}
        <p>{{phone.snippet}}</p>
      </li>
</ul>

JOIN two SELECT statement results

Try something like this:

SELECT 
* 
FROM
(SELECT ks, COUNT(*) AS '# Tasks' FROM Table GROUP BY ks) t1 
INNER JOIN
(SELECT ks, COUNT(*) AS '# Late' FROM Table WHERE Age > Palt GROUP BY ks) t2
ON t1.ks = t2.ks

What does ':' (colon) do in JavaScript?

You guys are forgetting that the colon is also used in the ternary operator (though I don't know if jquery uses it for this purpose).

the ternary operator is an expression form (expressions return a value) of an if/then statement. it's used like this:

var result = (condition) ? (value1) : (value2) ;

A ternary operator could also be used to produce side effects just like if/then, but this is profoundly bad practice.

Fail during installation of Pillow (Python module) in Linux

The alternative, if you don't want to install libjpeg:

CFLAGS="--disable-jpeg" pip install pillow

From https://pillow.readthedocs.io/en/3.0.0/installation.html#external-libraries

How do write IF ELSE statement in a MySQL query

you must write it in SQL not it C/PHP style

IF( action = 2 AND state = 0, 1, 0 ) AS state

for use in query

IF ( action = 2 AND state = 0 ) THEN SET state = 1

for use in stored procedures or functions

c#: getter/setter

In C# 6:

It is now possible to declare the auto-properties just as a field:

public string FirstName { get; set; } = "Ropert";

Read-Only Auto-Properties

public string FirstName { get;} = "Ropert";

Spring Security with roles and permissions

Just for sake of completeness (maybe someone else won't have to implement it from scratch):

We've implemented our own small library, as everyone else. It's supposed to make things easier, so that our developers don't have to reimplement it each time. It would be great if spring security would provide support of rbac out of the box, as this approach is much better than the default permission based one.

Have a look at Github (OSS, MIT license) to see if it suits your needs. It's basically only addressing the role <-> privileges mapping. The missing piece, you'll have to provide on your own is basically the user <-> roles mapping, e.g. by mapping groups (racf/ad groups) to roles (1:1) or by implementing an additional mapping. That one's different in each project, so it doesn't make sense to provide some implementation.

We've basically used this internally, so that we can start with rbac from the beginning. We can still replace it with some other implementation later on, if the application is growing, but it's important for us to get the setup right at the beginning.

If you don't use rbac, there's a good chance, that the permissions are scattered throughout the codebase and you'll have a hard time to extract/group those (into roles) later on. The generated graphs do also help to reason about it/restructure it later on.

Can't connect to MySQL server on 'localhost' (10061) after Installation

press Windows+R it opens Run then.. Enter services.msc

then Find out mysql right click and start

it works

How do I parse command line arguments in Bash?

The top answer to this question seemed a bit buggy when I tried it -- here's my solution which I've found to be more robust:

boolean_arg=""
arg_with_value=""

while [[ $# -gt 0 ]]
do
key="$1"
case $key in
    -b|--boolean-arg)
    boolean_arg=true
    shift
    ;;
    -a|--arg-with-value)
    arg_with_value="$2"
    shift
    shift
    ;;
    -*)
    echo "Unknown option: $1"
    exit 1
    ;;
    *)
    arg_num=$(( $arg_num + 1 ))
    case $arg_num in
        1)
        first_normal_arg="$1"
        shift
        ;;
        2)
        second_normal_arg="$1"
        shift
        ;;
        *)
        bad_args=TRUE
    esac
    ;;
esac
done

# Handy to have this here when adding arguments to
# see if they're working. Just edit the '0' to be '1'.
if [[ 0 == 1 ]]; then
    echo "first_normal_arg: $first_normal_arg"
    echo "second_normal_arg: $second_normal_arg"
    echo "boolean_arg: $boolean_arg"
    echo "arg_with_value: $arg_with_value"
    exit 0
fi

if [[ $bad_args == TRUE || $arg_num < 2 ]]; then
    echo "Usage: $(basename "$0") <first-normal-arg> <second-normal-arg> [--boolean-arg] [--arg-with-value VALUE]"
    exit 1
fi

Length of a JavaScript object

I had a similar need to calculate the bandwidth used by objects received over a websocket. Simply finding the length of the Stringified object was enough for me.

websocket.on('message', data => {
    dataPerSecond += JSON.stringify(data).length;
}

Set Focus After Last Character in Text Box

You should code like this.

var num = $('#Number').val();        
$('#Number').focus().val('').val(num);    

Highlight label if checkbox is checked

I like Andrew's suggestion, and in fact the CSS rule only needs to be:

:checked + label {
   font-weight: bold;
}

I like to rely on implicit association of the label and the input element, so I'd do something like this:

<label>
   <input type="checkbox"/>
   <span>Bah</span>
</label>

with CSS:

:checked + span {
    font-weight: bold;
}

Example: http://jsfiddle.net/wrumsby/vyP7c/

Sniff HTTP packets for GET and POST requests from an application

post in http
Put http.request.method == "POST" in the display filter of wireshark to only show POST requests. Click on the packet

Loading class `com.mysql.jdbc.Driver'. This is deprecated. The new driver class is `com.mysql.cj.jdbc.Driver'

Change driver property in your ORM config file from

 <property name="driver" value="com.mysql.jdbc.Driver"/>

to

<property name="driver" value="com.mysql.cj.jdbc.Driver"/>

This will resolve the warning :-)

How do you make Git work with IntelliJ?

On unix systems, you can use the following command to determine where git is installed:

whereis git

If you are using MacOS and did a recent update, it is possible you have to agree to the licence terms again. Try typing 'git' in a terminal, and see if you get the following message:

Agreeing to the Xcode/iOS license requires admin privileges, please re-run as root via sudo.

Bound method error

There's no error here. You're printing a function, and that's what functions look like.

To actually call the function, you have to put parens after that. You're already doing that above. If you want to print the result of calling the function, just have the function return the value, and put the print there. For example:

print test.sort_word_list()

On the other hand, if you want the function to mutate the object's state, and then print the state some other way, that's fine too.

Now, your code seems to work in some places, but not others; let's look at why:

  • parser sets a variable called word_list, and you later print test.word_list, so that works.
  • sort_word_list sets a variable called sorted_word_list, and you later print test.sort_word_list—that is, the function, not the variable. So, you see the bound method. (Also, as Jon Clements points out, even if you fix this, you're going to print None, because that's what sort returns.)
  • num_words sets a variable called num_words, and you again print the function—but in this case, the variable has the same name as the function, meaning that you're actually replacing the function with its output, so it works. This is probably not what you want to do, however.

(There are cases where, at first glance, that seems like it might be a good idea—you only want to compute something once, and then access it over and over again without constantly recomputing that. But this isn't the way to do it. Either use a @property, or use a memoization decorator.)

How to redirect the output of a PowerShell to a file during its execution

Maybe Start-Transcript would work for you. First stop it if it's already running, then start it, and stop it when done.

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue"
Start-Transcript -path C:\output.txt -append
# Do some stuff
Stop-Transcript

You can also have this running while working on stuff and have it saving your command line sessions for later reference.

If you want to completely suppress the error when attempting to stop a transcript that is not transcribing, you could do this:

$ErrorActionPreference="SilentlyContinue"
Stop-Transcript | out-null
$ErrorActionPreference = "Continue" # or "Stop"

How to automate browsing using python?

You can also take a look at mechanize. Its meant to handle "stateful programmatic web browsing" (as per their site).

Is there a way to detect if a browser window is not currently active?

There is a neat library available on GitHub:

https://github.com/serkanyersen/ifvisible.js

Example:

// If page is visible right now
if( ifvisible.now() ){
  // Display pop-up
  openPopUp();
}

I've tested version 1.0.1 on all browsers I have and can confirm that it works with:

  • IE9, IE10
  • FF 26.0
  • Chrome 34.0

... and probably all newer versions.

Doesn't fully work with:

  • IE8 - always indicate that tab/window is currently active (.now() always returns true for me)

In CSS Flexbox, why are there no "justify-items" and "justify-self" properties?

I just found my own solution to this problem, or at least my problem.
I was using justify-content: space-around instead of justify-content: space-between;.

This way the end elements will stick to the top and bottom, and you could have custom margins if you wanted.

Label points in geom_point

Instead of using the ifelse as in the above example, one can also prefilter the data prior to labeling based on some threshold values, this saves a lot of work for the plotting device:

xlimit <- 36
ylimit <- 24
ggplot(myData)+geom_point(aes(myX,myY))+
    geom_label(data=myData[myData$myX > xlimit & myData$myY> ylimit,], aes(myX,myY,myLabel))

Add button to navigationbar programmatically

If you are not looking for a BarButtonItem but simple button on navigationBar then below code works:

UIButton *aButton = [UIButton buttonWithType:UIButtonTypeCustom];
[aButton setBackgroundImage:[UIImage imageNamed:@"NavBar.png"] forState:UIControlStateNormal];
[aButton addTarget:self
            action:@selector(showButtonView:)
  forControlEvents:UIControlEventTouchUpInside];
aButton.frame = CGRectMake(260.0, 10.0, 30.0, 30.0);
[self.navigationController.navigationBar addSubview:aButton];

Return value in SQL Server stored procedure

You can either do 1 of the following:

Change:

SET @UserId = 0 to SELECT @UserId

This will return the value in the same way your 2nd part of the IF statement is.


Or, seeing as @UserId is set as an Output, change:

SELECT SCOPE_IDENTITY() to SET @UserId = SCOPE_IDENTITY()


It depends on how you want to access the data afterwards. If you want the value to be in your result set, use SELECT. If you want to access the new value of the @UserId parameter afterwards, then use SET @UserId


Seeing as you're accepting the 2nd condition as correct, the query you could write (without having to change anything outside of this query) is:

@EmailAddress varchar(200),
@NickName varchar(100),
@Password varchar(150),
@Sex varchar(50),
@Age int,
@EmailUpdates int,
@UserId int OUTPUT
IF 
    (SELECT COUNT(UserId) FROM RegUsers WHERE EmailAddress = @EmailAddress) > 0
    BEGIN
        SELECT 0
    END
ELSE
    BEGIN
        INSERT INTO RegUsers (EmailAddress,NickName,PassWord,Sex,Age,EmailUpdates) VALUES (@EmailAddress,@NickName,@Password,@Sex,@Age,@EmailUpdates)
        SELECT SCOPE_IDENTITY()
    END

END

How to make a form close when pressing the escape key?

If you have a cancel button on your form, you can set the Form.CancelButton property to that button and then pressing escape will effectively 'click the button'.

If you don't have such a button, check out the Form.KeyPreview property.

jQuery 'each' loop with JSON array

Brief code but full-featured

The following is a hybrid jQuery solution that formats each data "record" into an HTML element and uses the data's properties as HTML attribute values.

The jquery each runs the inner loop; I needed the regular JavaScript for on the outer loop to be able to grab the property name (instead of value) for display as the heading. According to taste it can be modified for slightly different behaviour.

This is only 5 main lines of code but wrapped onto multiple lines for display:

$.get("data.php", function(data){

    for (var propTitle in data) {

        $('<div></div>') 
            .addClass('heading')
            .insertBefore('#contentHere')
            .text(propTitle);

            $(data[propTitle]).each(function(iRec, oRec) {

                $('<div></div>')
                    .addClass(oRec.textType)
                    .attr('id', 'T'+oRec.textId)
                    .insertBefore('#contentHere')
                    .text(oRec.text);
            });
    }

});

Produces the output

(Note: I modified the JSON data text values by prepending a number to ensure I was displaying the proper records in the proper sequence - while "debugging")

<div class="heading">
    justIn
</div>
<div id="T123" class="Greeting">
    1Hello
</div>
<div id="T514" class="Question">
    1What's up?
</div>
<div id="T122" class="Order">
    1Come over here
</div>
<div class="heading">
    recent
</div>
<div id="T1255" class="Greeting">
    2Hello
</div>
<div id="T6564" class="Question">
    2What's up?
</div>
<div id="T0192" class="Order">
    2Come over here
</div>
<div class="heading">
    old
</div>
<div id="T5213" class="Greeting">
    3Hello
</div>
<div id="T9758" class="Question">
    3What's up?
</div>
<div id="T7655" class="Order">
    3Come over here
</div>
<div id="contentHere"></div>

Apply a style sheet

<style>
.heading { font-size: 24px; text-decoration:underline }
.Greeting { color: green; }
.Question { color: blue; }
.Order { color: red; }
</style>

to get a "beautiful" looking set of data

alt text

More Info
The JSON data was used in the following way:

for each category (key name the array is held under):

  • the key name is used as the section heading (e.g. justIn)

for each object held inside an array:

  • 'text' becomes the content of a div
  • 'textType' becomes the class of the div (hooked into a style sheet)
  • 'textId' becomes the id of the div
  • e.g. <div id="T122" class="Order">Come over here</div>

How to initialize a private static const map in C++?

A different approach to the problem:

struct A {
    static const map<int, string> * singleton_map() {
        static map<int, string>* m = NULL;
        if (!m) {
            m = new map<int, string>;
            m[42] = "42"
            // ... other initializations
        }
        return m;
    }

    // rest of the class
}

This is more efficient, as there is no one-type copy from stack to heap (including constructor, destructors on all elements). Whether this matters or not depends on your use case. Does not matter with strings! (but you may or may not find this version "cleaner")

Tuples( or arrays ) as Dictionary keys in C#

The good, clean, fast, easy and readable ways is:

  • generate equality members (Equals() and GetHashCode()) method for the current type. Tools like ReSharper not only creates the methods, but also generates the necessary code for an equality check and/or for calculating hash code. The generated code will be more optimal than Tuple realization.
  • just make a simple key class derived from a tuple.

add something similar like this:

public sealed class myKey : Tuple<TypeA, TypeB, TypeC>
{
    public myKey(TypeA dataA, TypeB dataB, TypeC dataC) : base (dataA, dataB, dataC) { }

    public TypeA DataA => Item1; 

    public TypeB DataB => Item2;

    public TypeC DataC => Item3;
}

So you can use it with dictionary:

var myDictinaryData = new Dictionary<myKey, string>()
{
    {new myKey(1, 2, 3), "data123"},
    {new myKey(4, 5, 6), "data456"},
    {new myKey(7, 8, 9), "data789"}
};
  • You also can use it in contracts
  • as a key for join or groupings in linq
  • going this way you never ever mistype order of Item1, Item2, Item3 ...
  • you no need to remember or look into to code to understand where to go to get something
  • no need to override IStructuralEquatable, IStructuralComparable, IComparable, ITuple they all alredy here

How do I find a particular value in an array and return its index?

The syntax you have there for your function doesn't make sense (why would the return value have a member called arr?).

To find the index, use std::distance and std::find from the <algorithm> header.

int x = std::distance(arr, std::find(arr, arr + 5, 3));

Or you can make it into a more generic function:

template <typename Iter>
size_t index_of(Iter first, Iter last, typename const std::iterator_traits<Iter>::value_type& x)
{
    size_t i = 0;
    while (first != last && *first != x)
      ++first, ++i;
    return i;
}

Here, I'm returning the length of the sequence if the value is not found (which is consistent with the way the STL algorithms return the last iterator). Depending on your taste, you may wish to use some other form of failure reporting.

In your case, you would use it like so:

size_t x = index_of(arr, arr + 5, 3);

converting drawable resource image into bitmap

In res/drawable folder,

1. Create a new Drawable Resources.

2. Input file name.

A new file will be created inside the res/drawable folder.

Replace this code inside the newly created file and replace ic_action_back with your drawable file name.

<bitmap xmlns:android="http://schemas.android.com/apk/res/android"
    android:src="@drawable/ic_action_back"
    android:tint="@color/color_primary_text" />

Now, you can use it with Resource ID, R.id.filename.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Create a Game model which extends Eloquent and use this:

Game::take(30)->skip(30)->get();

take() here will get 30 records and skip() here will offset to 30 records.


In recent Laravel versions you can also use:

Game::limit(30)->offset(30)->get();

'Use of Unresolved Identifier' in Swift

'Use of Unresolved Identifier' in Swift my also happen when you forgot to import a library. For example I have the error: enter image description here

In which I forgot the UIKit

import UIKit

/usr/lib/libstdc++.so.6: version `GLIBCXX_3.4.15' not found

gcc version 4.8.1, the error seems like:

/root/bllvm/build/Release+Asserts/bin/llvm-tblgen: /usr/lib64/libstdc++.so.6: version `GLIBCXX_3.4.15' not found (required by /root/bllvm/build/Release+Asserts/bin/llvm-tblgen)

I found the libstdc++.so.6.0.18 at the place where I complied gcc 4.8.1

Then I do like this

cp ~/objdir/x86_64-unknown-linux-gnu/libstdc++-v3/src/.libs/libstdc++.so.6.0.18 /usr/lib64/

rm /usr/lib64/libstdc++.so.6

ln -s libstdc++.so.6.0.18 libstdc++.so.6

problem solved.

How to sort by Date with DataTables jquery plugin?

Datatables only can order by DateTime in "ISO-8601" format, so you have to convert your date in "date-order" to this format (example using Razor):

<td data-sort="@myDate.ToString("o")">@myDate.ToShortDateString() - @myDate.ToShortTimeString()</td>

Open window in JavaScript with HTML inserted

You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open

var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

Show DataFrame as table in iPython Notebook

This answer is based on the 2nd tip from this blog post: 28 Jupyter Notebook tips, tricks and shortcuts

You can add the following code to the top of your notebook

from IPython.core.interactiveshell import InteractiveShell
InteractiveShell.ast_node_interactivity = "all"

This tells Jupyter to print the results for any variable or statement on it’s own line. So you can then execute a cell solely containing

df1
df2

and it will "print out the beautiful tables for both datasets".

Select2 open dropdown on focus

an important thing is to keep the multiselect open all the time. The simplest way is to fire open event on 'conditions' in your code:

<select data-placeholder="Choose a Country..." multiple class="select2-select" id="myList">
    <option value="United States">United States</option>
    <option value="United Kingdom">United Kingdom</option>
    <option value="Afghanistan">Afghanistan</option>
    <option value="Aland Islands">Aland Islands</option>
    <option value="Albania">Albania</option>
    <option value="Algeria">Algeria</option>
</select>

javascript:

$(".select2-select").select2({closeOnSelect:false});
$("#myList").select2("open");

fiddle: http://jsfiddle.net/xpvt214o/153442/

How to disable manual input for JQuery UI Datepicker field?

When you make the input, set it to be readonly.

<input type="text" name="datepicker" id="datepicker" readonly="readonly" />

How to activate the Bootstrap modal-backdrop?

Pretty strange, it should work out of the box as the ".modal-backdrop" class is defined top-level in the css.

<div class="modal-backdrop"></div>

Made a small demo: http://jsfiddle.net/PfBnq/

Expected block end YAML error

In my case, the error occured when I tried to pass a variable which was looking like a bytes-object (b"xxxx") but was actually a string.

You can convert the string to a real bytes object like this:

foo.strip('b"').replace("\\n", "\n").encode()

How to use Spring Boot with MySQL database and JPA?

In the spring boot reference,it said:

When a class doesn’t include a package declaration it is considered to be in the “default package”. The use of the “default package” is generally discouraged, and should be avoided. It can cause particular problems for Spring Boot applications that use @ComponentScan, @EntityScan or @SpringBootApplication annotations, since every class from every jar, will be read.

com
 +- example
     +- myproject
         +- Application.java
         |
         +- domain
         |   +- Customer.java
         |   +- CustomerRepository.java
         |
         +- service
         |   +- CustomerService.java
         |
         +- web
             +- CustomerController.java

In your cases. You must add scanBasePackages in the @SpringBootApplication annotation.just like@SpringBootApplication(scanBasePackages={"domain","contorller"..})

How to check if one DateTime is greater than the other in C#

This is probably too late, but to benefit other people who might stumble upon this, I used an extension method do to this using IComparable like this:

public static class BetweenExtension
    {
        public static bool IsBetween<T>(this T value, T min, T max) where T : IComparable
        {
            return (min.CompareTo(value) <= 0) && (value.CompareTo(max) <= 0);
        }
    }

Using this extension method with IComparable makes this method more generic and makes it usable with a wide variety of data types and not just dates.

You would use it like this:

DateTime start = new DateTime(2015,1,1);
DateTime end = new DateTime(2015,12,31);
DateTime now = new DateTime(2015,8,20);

if(now.IsBetween(start, end))
{
     //Your code here
}

npm install private github repositories by dependency in package.json

"dependencies": {
  "some-package": "github:github_username/some-package"
}

or just

"dependencies": {
  "some-package": "github_username/some-package"
}

https://docs.npmjs.com/files/package.json#github-urls

Store select query's output in one array in postgres

I had exactly the same problem. Just one more working modification of the solution given by Denis (the type must be specified):

SELECT ARRAY(
SELECT column_name::text
FROM information_schema.columns
WHERE table_name='aean'
)

Disabling browser caching for all browsers from ASP.NET

I'm going to test adding the no-store tag to our site to see if this makes a difference to browser caching (Chrome has sometimes been caching the pages). I also found this article very useful on documentation on how and why caching works and will look at ETag's next if the no-store is not reliable:

http://www.mnot.net/cache_docs/

http://en.wikipedia.org/wiki/HTTP_ETag

Node.js request CERT_HAS_EXPIRED

Try to temporarily modify request.js and harcode everywhere rejectUnauthorized = true, but it would be better to get the certificate extended as a long-term solution.

Android: show/hide status bar/power bar

used for kolin in android for hide status bar in kolin no need to used semicolon(;) at the end of the line

window.addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN)

in android using java language for hid status bar

getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);

Why do I need to explicitly push a new branch?

If you enable to push new changes from your new branch first time. And getting below error:

*git push -f
fatal: The current branch Coding_Preparation has no upstream branch.

To push the current branch and set the remote as upstream, use

git push -u origin new_branch_name


** Successful Result:** 
 git push -u origin Coding_Preparation
Enumerating objects: 5, done.
Counting objects: 100% (5/5), done.
Delta compression using up to 4 threads
Compressing objects: 100% (3/3), done.
Writing objects: 100% (3/3), 599 bytes | 599.00 KiB/s, done.
Total 3 (delta 0), reused 0 (delta 0)
remote:
remote: Create a pull request for 'Coding_Preparation' on GitHub by visiting: ...
 * [new branch]      Coding_Preparation -> Coding_Preparation
Branch 'Coding_Preparation' set up to track remote branch 'Coding_Preparation' from 'origin'.

How to stop line breaking in vim

You may find set lbr useful; with set wrap on this will wrap but only cutting the line on whitespace and not in the middle of a word.

e.g.

without lbr the li
ne can be split on
a word

and

with lbr on the
line will be
split on 
whitespace only

Why can't non-default arguments follow default arguments?

All required parameters must be placed before any default arguments. Simply because they are mandatory, whereas default arguments are not. Syntactically, it would be impossible for the interpreter to decide which values match which arguments if mixed modes were allowed. A SyntaxError is raised if the arguments are not given in the correct order:

Let us take a look at keyword arguments, using your function.

def fun1(a="who is you", b="True", x, y):
...     print a,b,x,y

Suppose its allowed to declare function as above, Then with the above declarations, we can make the following (regular) positional or keyword argument calls:

func1("ok a", "ok b", 1)  # Is 1 assigned to x or ?
func1(1)                  # Is 1 assigned to a or ?
func1(1, 2)               # ?

How you will suggest the assignment of variables in the function call, how default arguments are going to be used along with keyword arguments.

>>> def fun1(x, y, a="who is you", b="True"):
...     print a,b,x,y
... 

Reference O'Reilly - Core-Python
Where as this function make use of the default arguments syntactically correct for above function calls. Keyword arguments calling prove useful for being able to provide for out-of-order positional arguments, but, coupled with default arguments, they can also be used to "skip over" missing arguments as well.

How to insert a large block of HTML in JavaScript?

If I understand correctly, you're looking for a multi-line representation, for readability? You want something like a here-string in other languages. Javascript can come close with this:

var x =
    "<div> \
    <span> \
    <p> \
    some text \
    </p> \
    </div>";

Using AES encryption in C#

If you just want to use the built-in crypto provider RijndaelManaged, check out the following help article (it also has a simple code sample):

http://msdn.microsoft.com/en-us/library/system.security.cryptography.rijndaelmanaged.aspx

And just in case you need the sample in a hurry, here it is in all its plagiarized glory:

using System;
using System.IO;
using System.Security.Cryptography;

namespace RijndaelManaged_Example
{
    class RijndaelExample
    {
        public static void Main()
        {
            try
            {

                string original = "Here is some data to encrypt!";

                // Create a new instance of the RijndaelManaged 
                // class.  This generates a new key and initialization  
                // vector (IV). 
                using (RijndaelManaged myRijndael = new RijndaelManaged())
                {

                    myRijndael.GenerateKey();
                    myRijndael.GenerateIV();
                    // Encrypt the string to an array of bytes. 
                    byte[] encrypted = EncryptStringToBytes(original, myRijndael.Key, myRijndael.IV);

                    // Decrypt the bytes to a string. 
                    string roundtrip = DecryptStringFromBytes(encrypted, myRijndael.Key, myRijndael.IV);

                    //Display the original data and the decrypted data.
                    Console.WriteLine("Original:   {0}", original);
                    Console.WriteLine("Round Trip: {0}", roundtrip);
                }

            }
            catch (Exception e)
            {
                Console.WriteLine("Error: {0}", e.Message);
            }
        }
        static byte[] EncryptStringToBytes(string plainText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (plainText == null || plainText.Length <= 0)
                throw new ArgumentNullException("plainText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");
            byte[] encrypted;
            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decryptor to perform the stream transform.
                ICryptoTransform encryptor = rijAlg.CreateEncryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for encryption. 
                using (MemoryStream msEncrypt = new MemoryStream())
                {
                    using (CryptoStream csEncrypt = new CryptoStream(msEncrypt, encryptor, CryptoStreamMode.Write))
                    {
                        using (StreamWriter swEncrypt = new StreamWriter(csEncrypt))
                        {

                            //Write all data to the stream.
                            swEncrypt.Write(plainText);
                        }
                        encrypted = msEncrypt.ToArray();
                    }
                }
            }


            // Return the encrypted bytes from the memory stream. 
            return encrypted;

        }

        static string DecryptStringFromBytes(byte[] cipherText, byte[] Key, byte[] IV)
        {
            // Check arguments. 
            if (cipherText == null || cipherText.Length <= 0)
                throw new ArgumentNullException("cipherText");
            if (Key == null || Key.Length <= 0)
                throw new ArgumentNullException("Key");
            if (IV == null || IV.Length <= 0)
                throw new ArgumentNullException("IV");

            // Declare the string used to hold 
            // the decrypted text. 
            string plaintext = null;

            // Create an RijndaelManaged object 
            // with the specified key and IV. 
            using (RijndaelManaged rijAlg = new RijndaelManaged())
            {
                rijAlg.Key = Key;
                rijAlg.IV = IV;

                // Create a decrytor to perform the stream transform.
                ICryptoTransform decryptor = rijAlg.CreateDecryptor(rijAlg.Key, rijAlg.IV);

                // Create the streams used for decryption. 
                using (MemoryStream msDecrypt = new MemoryStream(cipherText))
                {
                    using (CryptoStream csDecrypt = new CryptoStream(msDecrypt, decryptor, CryptoStreamMode.Read))
                    {
                        using (StreamReader srDecrypt = new StreamReader(csDecrypt))
                        {

                            // Read the decrypted bytes from the decrypting stream 
                            // and place them in a string.
                            plaintext = srDecrypt.ReadToEnd();
                        }
                    }
                }

            }

            return plaintext;

        }
    }
}

Skip first line(field) in loop using CSV file?

Probably you want something like:

firstline = True
for row in kidfile:
    if firstline:    #skip first line
        firstline = False
        continue
    # parse the line

An other way to achive the same result is calling readline before the loop:

kidfile.readline()   # skip the first line
for row in kidfile:
    #parse the line

Can I Set "android:layout_below" at Runtime Programmatically?

Alternatively you can use the views current layout parameters and modify them:

RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) viewToLayout.getLayoutParams();
params.addRule(RelativeLayout.BELOW, R.id.below_id);

Wait until page is loaded with Selenium WebDriver for Python

The webdriver will wait for a page to load by default via .get() method.

As you may be looking for some specific element as @user227215 said, you should use WebDriverWait to wait for an element located in your page:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
try:
    myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
    print "Page is ready!"
except TimeoutException:
    print "Loading took too much time!"

I have used it for checking alerts. You can use any other type methods to find the locator.

EDIT 1:

I should mention that the webdriver will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url'), your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions.

Update TensorFlow

(tensorflow)$ pip install --upgrade pip  # for Python 2.7
(tensorflow)$ pip3 install --upgrade pip # for Python 3.n

(tensorflow)$ pip install --upgrade tensorflow      # for Python 2.7
(tensorflow)$ pip3 install --upgrade tensorflow     # for Python 3.n
(tensorflow)$ pip install --upgrade tensorflow-gpu  # for Python 2.7 and GPU
(tensorflow)$ pip3 install --upgrade tensorflow-gpu # for Python 3.n and GPU

(tensorflow)$ pip install --upgrade tensorflow-gpu==1.4.1 # for a specific version

Details on install tensorflow.

How to align input forms in HTML

Another example, this uses CSS, I simply put the form in a div with the container class. And specified that input elements contained within are to be 100% of the container width and not have any elements on either side.

_x000D_
_x000D_
.container {_x000D_
  width: 500px;_x000D_
  clear: both;_x000D_
}_x000D_
_x000D_
.container input {_x000D_
  width: 100%;_x000D_
  clear: both;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <title>Example form</title>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <div class="container">_x000D_
    <form>_x000D_
      <label>First Name</label>_x000D_
      <input type="text" name="first"><br />_x000D_
      <label>Last Name</label>_x000D_
      <input type="text" name="last"><br />_x000D_
      <label>Email</label>_x000D_
      <input type="text" name="email"><br />_x000D_
    </form>_x000D_
  </div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

"NoClassDefFoundError: Could not initialize class" error

Realised that I was using OpenJDK when I saw this error. Fixed it once I installed the Oracle JDK instead.

ssh_exchange_identification: Connection closed by remote host under Git bash

Got the same error too when connecting to GitHub with ssh as I move from one workplace to another. according to my situation, it seems that dns servers of different networks may get various ip address of github and the known_hosts file not identify it when changes happened. So change dns or switch back original network may work.

how to count the total number of lines in a text file using python

I am not new to stackoverflow, just never had an account and usually came here for answers. I can't comment or vote up an answer yet. BUT wanted to say that the code from Michael Bacon above works really well. I am new to Python but not to programming. I have been reading Python Crash Course and there are a few things I wanted to do to break up the reading cover to cover approach. One utility that has uses from an ETL or even data quality perspective would be to capture the row count of a file independently from any ETL. The file has X number of rows, you import into SQL or Hadoop and you end up with X number of rows. You can validate at the lowest level the row count of a raw data file.

I have been playing with his code and doing some testing and this code is very efficient so far. I have created several different CSV files, various sizes, and row counts. You can see my code below and my comments provide the times and details. The code Michael Bacon above provided runs about 6 times faster than the normal Python method of just looping the lines.

Hope this helps someone.


 import time
from itertools import (takewhile,repeat)

def readfilesimple(myfile):

    # watch me whip
    linecounter = 0
    with open(myfile,'r') as file_object:
        # watch me nae nae
         for lines in file_object:
            linecounter += 1

    return linecounter

def readfileadvanced(myfile):

    # watch me whip
    f = open(myfile, 'rb')
    # watch me nae nae
    bufgen = takewhile(lambda x: x, (f.raw.read(1024 * 1024) for _ in repeat(None)))
    return sum(buf.count(b'\n') for buf in bufgen if buf)
    #return linecounter


# ************************************
# Main
# ************************************

#start the clock

start_time = time.time()

# 6.7 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfilesimple("c:/junk/book1.csv")

# 0.67 seconds to read a 475MB file that has 24 million rows and 3 columns
#mycount = readfileadvanced("c:/junk/book1.csv")

# 25.9 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")

# 5.7 seconds to read a 3.9Gb file that has 3.25 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig1.csv")


# 292.92 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
mycount = readfilesimple("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")

# 57 seconds to read a 43Gb file that has 35.7 million rows and 104 columns
#mycount = readfileadvanced("c:/junk/WideCsvExample/ReallyWideReallyBig.csv")


#stop the clock
elapsed_time = time.time() - start_time


print("\nCode Execution: " + str(elapsed_time) + " seconds\n")
print("File contains: " + str(mycount) + " lines of text.")

Mips how to store user input string

# This code works fine in QtSpim simulator

.data
    buffer: .space 20
    str1:  .asciiz "Enter string"
    str2:  .asciiz "You wrote:\n"

.text

main:
    la $a0, str1    # Load and print string asking for string
    li $v0, 4
    syscall

    li $v0, 8       # take in input

    la $a0, buffer  # load byte space into address
    li $a1, 20      # allot the byte space for string

    move $t0, $a0   # save string to t0
    syscall

    la $a0, str2    # load and print "you wrote" string
    li $v0, 4
    syscall

    la $a0, buffer  # reload byte space to primary address
    move $a0, $t0   # primary address = t0 address (load pointer)
    li $v0, 4       # print string
    syscall

    li $v0, 10      # end program
    syscall

how to set radio button checked in edit mode in MVC razor view

Don't do this at the view level. Just set the default value to the property in your view model's constructor. Clean and simple. In your post-backs, your selected value will automatically populate the correct selection.

For example

public class MyViewModel
{
        public MyViewModel()
        {
            Gender = "Male";
        }
}

_x000D_
_x000D_
<table>_x000D_
  <tr>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Male")Male</label></td>_x000D_
 <td><label>@Html.RadioButtonFor(i => i.Gender, "Female")Female</label></td>_x000D_
  </tr>_x000D_
 </table>
_x000D_
_x000D_
_x000D_

How to delete all records from table in sqlite with Android?

use Sqlit delete function with last two null parameters.

db.delete(TABLE_NAME,null,null)

How do I trigger a macro to run after a new mail is received in Outlook?

Try something like this inside ThisOutlookSession:

Private Sub Application_NewMail()
    Call Your_main_macro
End Sub

My outlook vba just fired when I received an email and had that application event open.

Edit: I just tested a hello world msg box and it ran after being called in the application_newmail event when an email was received.

Java division by zero doesnt throw an ArithmeticException - why?

When divided by zero

  1. If you divide double by 0, JVM will show Infinity.

    public static void main(String [] args){ double a=10.00; System.out.println(a/0); }
    

    Console: Infinity

  2. If you divide int by 0, then JVM will throw Arithmetic Exception.

    public static void main(String [] args){
        int a=10;
        System.out.println(a/0);
    }
    

    Console: Exception in thread "main" java.lang.ArithmeticException: / by zero

php - How do I fix this illegal offset type error

I had a similar problem. As I got a Character from my XML child I had to convert it first to a String (or Integer, if you expect one). The following shows how I solved the problem.

foreach($xml->children() as $newInstr){
        $iInstrument = new Instrument($newInstr['id'],$newInstr->Naam,$newInstr->Key);
        $arrInstruments->offsetSet((String)$iInstrument->getID(), $iInstrument);
    }

How to make scipy.interpolate give an extrapolated result beyond the input range?

I'm afraid that there is no easy to do this in Scipy to my knowledge. You can, as I'm fairly sure that you are aware, turn off the bounds errors and fill all function values beyond the range with a constant, but that doesn't really help. See this question on the mailing list for some more ideas. Maybe you could use some kind of piecewise function, but that seems like a major pain.

How to build a RESTful API?

As simon marc said, the process is much the same as it is for you or I browsing a website. If you are comfortable with using the Zend framework, there are some easy to follow tutorials to that make life quite easy to set things up. The hardest part of building a restful api is the design of the it, and making it truly restful, think CRUD in database terms.

It could be that you really want an xmlrpc interface or something else similar. What do you want this interface to allow you to do?

--EDIT

Here is where I got started with restful api and Zend Framework. Zend Framework Example

In short don't use Zend rest server, it's obsolete.

Playing .mp3 and .wav in Java?

The easiest way I found was to download the JLayer jar file from http://www.javazoom.net/javalayer/sources.html and to add it to the Jar library http://www.wikihow.com/Add-JARs-to-Project-Build-Paths-in-Eclipse-%28Java%29

Here is the code for the class

public class SimplePlayer {

    public SimplePlayer(){

        try{

             FileInputStream fis = new FileInputStream("File location.");
             Player playMP3 = new Player(fis);

             playMP3.play();

        }  catch(Exception e){
             System.out.println(e);
           }
    } 
}

and here are the imports

import javazoom.jl.player.*;
import java.io.FileInputStream;

remove inner shadow of text input

Add border: none or border: 0 to remove border at all, or border: 1px solid #ccc to make border thin and flat.

To remove ghost padding in Firefox, you can use ::-moz-focus-inner:

::-moz-focus-inner {
    border: 0;
    padding: 0;
}

See live demo.

Open directory using C

Parameters passed to the C program executable is nothing but an array of string(or character pointer),so memory would have been already allocated for these input parameter before your program access these parameters,so no need to allocate buffer,and that way you can avoid error handling code in your program as well(Reduce chances of segfault :)).

Declare variable in table valued function

There are two flavors of table valued functions. One that is just a select statement and one that can have more rows than just a select statement.

This can not have a variable:

create function Func() returns table
as
return
select 10 as ColName

You have to do like this instead:

create function Func()
returns @T table(ColName int)
as
begin
  declare @Var int
  set @Var = 10
  insert into @T(ColName) values (@Var)
  return
end

ORA-00907: missing right parenthesis

I would recommend separating out all of the foreign-key constraints from your CREATE TABLE statements. Create all the tables first without FK constraints, and then create all the FK constraints once you have created the tables.

You can add an FK constraint to a table using SQL like the following:

ALTER TABLE orders ADD CONSTRAINT orders_FK
  FOREIGN KEY (m_p_unique_id) REFERENCES library (m_p_unique_id);

In particular, your formats and library tables both have foreign-key constraints on one another. The two CREATE TABLE statements to create these two tables can never run successfully, as each will only work when the other table has already been created.

Separating out the constraint creation allows you to create tables with FK constraints on one another. Also, if you have an error with a constraint, only that constraint fails to be created. At present, because you have errors in the constraints in your CREATE TABLE statements, then entire table creation fails and you get various knock-on errors because FK constraints may depend on these tables that failed to create.

Check cell for a specific letter or set of letters

Just use = IF(A1="Bla*","YES","NO"). When you insert the asterisk, it acts as a wild card for any amount of characters after the specified text.

Boto3 Error: botocore.exceptions.NoCredentialsError: Unable to locate credentials

I also had the same issue,it can be solved by creating a config and credential file in the home directory. Below show the steps I did to solve this issue.

Create a config file :

touch ~/.aws/config

And in that file I entered the region

[default]
region = us-west-2

Then create the credential file:

touch ~/.aws/credentials

Then enter your credentials

[Profile1]
aws_access_key_id = XXXXXXXXXXXXXXXXXXXX 
aws_secret_access_key = YYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYYY

After set all these, then my python file to connect bucket. Run this file will list all the contents.

import boto3
import os

os.environ['AWS_PROFILE'] = "Profile1"
os.environ['AWS_DEFAULT_REGION'] = "us-west-2"

s3 = boto3.client('s3', region_name='us-west-2')
print("[INFO:] Connecting to cloud")

# Retrieves all regions/endpoints that work with S3

response = s3.list_buckets()
print('Regions:', response)

You can also refer below links:

Why SQL Server throws Arithmetic overflow error converting int to data type numeric?

Precision and scale are often misunderstood. In numeric(3,2) you want 3 digits overall, but 2 to the right of the decimal. If you want 15 => 15.00 so the leading 1 causes the overflow (since if you want 2 digits to the right of the decimal, there is only room on the left for one more digit). With 4,2 there is no problem because all 4 digits fit.

Convert Enumeration to a Set/List

There is a simple example of convert enumeration to list. for this i used Collections.list(enum) method.

public class EnumerationToList {

    public static void main(String[] args) {
        Vector<String> vt = new Vector<String>();
        vt.add("java");
        vt.add("php");
        vt.add("array");
        vt.add("string");
        vt.add("c");

        Enumeration<String> enm = vt.elements();
        List<String> ll = Collections.list(enm);
        System.out.println("List elements: " + ll);
    }

}

Reference : How to convert enumeration to list

Bootstrap 4 - Responsive cards in card-columns

Update 2019 - Bootstrap 4

You can simply use the SASS mixin to change the number of cards across in each breakpoint / grid tier.

.card-columns {
  @include media-breakpoint-only(xl) {
    column-count: 5;
  }
  @include media-breakpoint-only(lg) {
    column-count: 4;
  }
  @include media-breakpoint-only(md) {
    column-count: 3;
  }
  @include media-breakpoint-only(sm) {
    column-count: 2;
  }
}

SASS Demo: http://www.codeply.com/go/FPBCQ7sOjX

Or, CSS only like this...

@media (min-width: 576px) {
    .card-columns {
        column-count: 2;
    }
}

@media (min-width: 768px) {
    .card-columns {
        column-count: 3;
    }
}

@media (min-width: 992px) {
    .card-columns {
        column-count: 4;
    }
}

@media (min-width: 1200px) {
    .card-columns {
        column-count: 5;
    }
}

CSS-only Demo: https://www.codeply.com/go/FIqYTyyWWZ

ORA-12560: TNS:protocol adaptor error

Seems like database is not up. It might be due to restarting machine and the instance is not set to autostart and it so not started munually after starting from services Screen.

Just goto Command prompt

  1. Set Oracle SID C:>set oracle_sid=ORCL

  2. Now run Net start command. C:>net start oracleserviceORCL

How to make for loops in Java increase by increments other than 1

Since nobody else has actually tackled Could someone please explain this to me? I believe I will:

j++ is shorthand, it's not an actual operation (ok it really IS, but bear with me for the explanation)

j++ is really equal to the operation j = j + 1; except it's not a macro or something that does inline replacement. There are a lot of discussions on here about the operations of i+++++i and what that means (because it could be intepreted as i++ + ++i OR (i++)++ + i

Which brings us to: i++ versus ++i. They are called the post-increment and pre-increment operators. Can you guess why they are so named? The important part is how they're used in assignments. For instance, you could do: j=i++; or j=++i; We shall now do an example experiment:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i++;
k = ++i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example

What are the values of i, j, and k?

I'll give you the answers and let you work it out ;)

i = 7, j = 5, k = 7; That's the power of the pre and post increment operators, and the hazards of using them wrong. But here's the alternate way of writing that same order of operations:

// declare them all with the same value, for clarity and debug flow purposes ;)
int i = 0;
int j = 0;
int k = 0;

// yes we could have already set the value to 5 before, but I chose not to.
i = 5;

j = i;
i = i + 1; //post-increment

i = i + 1; //pre-increment
k = i;

print(i, j, k); 
//pretend this command prints them out nicely 
//to the console screen or something, it's an example

Ok, now that I've shown you how the ++ operator works, let's examine why it doesn't work for j+3 ... Remember how I called it a "shorthand" earlier? That's just it, see the second example, because that's effectively what the compiler does before using the command (it's more complicated than that, but that's not for first explanations). So you'll see that the "expanded shorthand" has i = AND i + 1 which is all that your request has.

This goes back to math. A function is defined where f(x) = mx + b or an equation y = mx + b so what do we call mx + b ... it's certainly not a function or equation. At most it is an expression. Which is all j+3 is, an expression. An expression without assignment does us no good, but it does take up CPU time (assuming the compiler doesn't optimize it out).


I hope that clarifies things for you and gives you some room to ask new questions. Cheers!

Java: how to convert HashMap<String, Object> to array

@SuppressWarnings("unchecked")
    public static <E,T> E[] hashMapKeysToArray(HashMap<E,T> map)
    {
        int s;
        if(map == null || (s = map.size())<1)
            return null;

        E[] temp;
        E typeHelper;
        try
        {
            Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
            Entry<E, T> iK = iterator.next();
            typeHelper = iK.getKey();

            Object o = Array.newInstance(typeHelper.getClass(), s);
            temp = (E[]) o;

            int index = 0;
            for (Map.Entry<E,T> mapEntry : map.entrySet())
            {
                temp[index++] = mapEntry.getKey();
            }
        }
        catch (Exception e)
        {
            return null;
        }
        return temp;
    }
//--------------------------------------------------------
    @SuppressWarnings("unchecked")
    public static <E,T> T[] hashMapValuesToArray(HashMap<E,T> map)
    {
        int s;
        if(map == null || (s = map.size())<1)
            return null;

        T[] temp;
        T typeHelper;
        try
        {
            Iterator<Entry<E, T>> iterator = map.entrySet().iterator();
            Entry<E, T> iK = iterator.next();
            typeHelper = iK.getValue();

            Object o = Array.newInstance(typeHelper.getClass(), s);
            temp = (T[]) o;

            int index = 0;
            for (Map.Entry<E,T> mapEntry : map.entrySet())
            {
                temp[index++] = mapEntry.getValue();
            }
        }
        catch (Exception e)
        {return null;}

        return temp;
    }

Incomplete type is not allowed: stringstream

An incomplete type error is when the compiler encounters the use of an identifier that it knows is a type, for instance because it has seen a forward-declaration of it (e.g. class stringstream;), but it hasn't seen a full definition for it (class stringstream { ... };).

This could happen for a type that you haven't used in your own code but is only present through included header files -- when you've included header files that use the type, but not the header file where the type is defined. It's unusual for a header to not itself include all the headers it needs, but not impossible.

For things from the standard library, such as the stringstream class, use the language standard or other reference documentation for the class or the individual functions (e.g. Unix man pages, MSDN library, etc.) to figure out what you need to #include to use it and what namespace to find it in if any. You may need to search for pages where the class name appears (e.g. man -k stringstream).

Form Google Maps URL that searches for a specific places near specific coordinates

additional info:

http://maps.google.com/maps?q=loc: put in latitude and longitude after, example:

http://maps.google.com/maps?q=loc:51.03841,-114.01679

this will show pointer on map, but will suppress geocoding of the address, best for a location without an address, or for a location where google maps shows the incorrect address.

Replace all spaces in a string with '+'

You need the /g (global) option, like this:

var replaced = str.replace(/ /g, '+');

You can give it a try here. Unlike most other languages, JavaScript, by default, only replaces the first occurrence.

BackgroundWorker vs background Thread

Pretty much what Matt Davis said, with the following additional points:

For me the main differentiator with BackgroundWorker is the automatic marshalling of the completed event via the SynchronizationContext. In a UI context this means the completed event fires on the UI thread, and so can be used to update UI. This is a major differentiator if you are using the BackgroundWorker in a UI context.

Tasks executed via the ThreadPool cannot be easily cancelled (this includes ThreadPool. QueueUserWorkItem and delegates execute asyncronously). So whilst it avoids the overhead of thread spinup, if you need cancellation either use a BackgroundWorker or (more likely outside of the UI) spin up a thread and keep a reference to it so you can call Abort().

Is there a way to perform "if" in python's lambda

I think this is what you were looking for

>>> f = lambda x : print(x) if x==2 else print("ERROR")
>>> f(23)
ERROR
>>> f(2)
2
>>> 

Nginx fails to load css files

I found an workaround on the web. I added to /etc/nginx/conf.d/default.conf the following:

location ~ \.css {
    add_header  Content-Type    text/css;
}
location ~ \.js {
    add_header  Content-Type    application/x-javascript;
}

The problem now is that a request to my css file isn't redirected well, as if root is not correctly set. In error.log I see

2012/04/11 14:01:23 [error] 7260#0: *2 open() "/etc/nginx//html/style.css"

So as a second workaround I added the root to each defined location. Now it works, but seems a little redundant. Isn't root inherited from / location ?

To enable extensions, verify that they are enabled in those .ini files - Vagrant/Ubuntu/Magento 2.0.2

When I went to create a laravel project, I got this problem.

After googling, I got this solution.

I followed these steps:

Step 1: sudo apt-get install -y php7.2-gd

Step 2: sudo apt-get install php7.2-intl

Step 3: sudo apt-get install php7.2-xsl

Step 4: sudo apt-get install php7.2-mbstring

Multi-threading in VBA

As you probably learned VBA does not natively support multithreading but. There are 3 methods to achieve multithreading:

  1. COM/dlls - e.g. C# and the Parallel class to run in separate threads
  2. Using VBscript worker threads - run your VBA code in separate VBscript threads
  3. Using VBA worker threads executed e.g. via VBscript - copy the Excel workbook and run your macro in parallel.

I compared all thread approaches here: http://analystcave.com/excel-multithreading-vba-vs-vbscript-vs-c-net/

Considering approach #3 I also made a VBA Multithreading Tool that allows you to easily add multithreading to VBA: http://analystcave.com/excel-vba-multithreading-tool/

See the examples below:

Multithreading a For Loop

Sub RunForVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAMultiThread()
    Dim parallelClass As Parallel 

    Set parallelClass = New Parallel 

    parallelClass.SetThreads 4 

    Call parallelClass.ParallelFor("RunForVBA", 1, 1000) 
End Sub

Run an Excel macro asynchronously

Sub RunAsyncVBA(workbookName As String, seqFrom As Long, seqTo As Long)
    For i = seqFrom To seqTo
        x = seqFrom / seqTo
    Next i
End Sub

Sub RunForVBAAndWait()
    Dim parallelClass As Parallel

    Set parallelClass  = New Parallel

    Call parallelClass.ParallelAsyncInvoke("RunAsyncVBA", ActiveWorkbook.Name, 1, 1000) 
    'Do other operations here
    '....

    parallelClass.AsyncThreadJoin 
End Sub

Java: method to get position of a match in a String?

If you're going to scan for 'n' matches of the search string, I'd recommend using regular expressions. They have a steep learning curve, but they'll save you hours when it comes to complex searches.

Angularjs ng-model doesn't work inside ng-if

You can use $parent to refer to the model defined in the parent scope like this

<input type="checkbox" ng-model="$parent.testb" />

"Data too long for column" - why?

For me, I defined column type as BIT (e.g. "boolean")

When I tried to set column value "1" via UI (Workbench), I was getting a "Data too long for column" error.

Turns out that there is a special syntax for setting BIT values, which is:

b'1'

Does Python have “private” variables in classes?

Sorry guys for "resurrecting" the thread, but, I hope this will help someone:

In Python3 if you just want to "encapsulate" the class attributes, like in Java, you can just do the same thing like this:

class Simple:
    def __init__(self, str):
        print("inside the simple constructor")
        self.__s = str

    def show(self):
        print(self.__s)

    def showMsg(self, msg):
        print(msg + ':', self.show())

To instantiate this do:

ss = Simple("lol")
ss.show()

Note that: print(ss.__s) will throw an error.

In practice, Python3 will obfuscate the global attribute name. Turning this like a "private" attribute, like in Java. The attribute's name is still global, but in an inaccessible way, like a private attribute in other languages.

But don't be afraid of it. It doesn't matter. It does the job too. ;)

How can I print literal curly-brace characters in a string and also use .format on it?

If you want to only print one curly brace (for example {) you can use {{, and you can add more braces later in the string if you want. For example:

>>> f'{{ there is a curly brace on the left. Oh, and 1 + 1 is {1 + 1}'
'{ there is a curly brace on the left. Oh, and 1 + 1 is 2'

Regular expression to limit number of characters to 10

pattern: /[\w\W]{1,10}/g

I used this expression for my case, it includes all the characters available in the text.

How to delete and recreate from scratch an existing EF Code First database

If I'm understanding it right...

If you want to start clean:

1) Manually delete your DB - wherever it is (I'm assuming you have your connection sorted), or empty it, but easier/safer is to delete it all together - as there is system __MigrationHistory table - you need that removed too.

2) Remove all migration files - which are under Migrations - and named like numbers etc. - remove them all,

3) Rebuild your project containing migrations (and the rest) - and make sure your project is set up (configuration) to build automatically (that sometimes may cause problems - but not likely for you),

4) Run Add-Migration Initial again - then Update-Database

Using Pipes within ngModel on INPUT Elements in Angular

because of two way binding, To prevent error of:

ExpressionChangedAfterItHasBeenCheckedError: Expression has changed after it was 
checked.

you can call a function to change model like this:

<input [ngModel]="item.value" 
  (ngModelChange)="getNewValue($event)" name="inputField" type="text" />


import { UseMyPipeToFormatThatValuePipe } from './path';

constructor({
    private UseMyPipeToFormatThatValue: UseMyPipeToFormatThatValuePipe,
})

getNewValue(ev: any): any {
    item.value= this.useMyPipeToFormatThatValue.transform(ev);
}

it'll be good if there is a better solution to prevent this error.

What is the simplest jQuery way to have a 'position:fixed' (always at top) div?

Using this HTML:

<div id="myElement" style="position: absolute">This stays at the top</div>

This is the javascript you want to use. It attaches an event to the window's scroll and moves the element down as far as you've scrolled.

$(window).scroll(function() {
    $('#myElement').css('top', $(this).scrollTop() + "px");
});

As pointed out in the comments below, it's not recommended to attach events to the scroll event - as the user scrolls, it fires A LOT, and can cause performance issues. Consider using it with Ben Alman's debounce/throttle plugin to reduce overhead.

Combining Two Images with OpenCV

in OpenCV 3.0 you can use it easily as follow:

#combine 2 images same as to concatenate images with two different sizes
h1, w1 = img1.shape[:2]
h2, w2 = img2.shape[:2]
#create empty martrix (Mat)
res = np.zeros(shape=(max(h1, h2), w1 + w2, 3), dtype=np.uint8)
# assign BGR values to concatenate images
for i in range(res.shape[2]):
    # assign img1 colors
    res[:h1, :w1, i] = np.ones([img1.shape[0], img1.shape[1]]) * img1[:, :, i]
    # assign img2 colors
    res[:h2, w1:w1 + w2, i] = np.ones([img2.shape[0], img2.shape[1]]) * img2[:, :, i]

output_img = res.astype('uint8')

Android and setting width and height programmatically in dp units

simplest way(and even works from api 1) that tested is:

getResources().getDimensionPixelSize(R.dimen.example_dimen);

From documentations:

Retrieve a dimensional for a particular resource ID for use as a size in raw pixels. This is the same as getDimension(int), except the returned value is converted to integer pixels for use as a size. A size conversion involves rounding the base value, and ensuring that a non-zero base value is at least one pixel in size.

Yes it rounding the value but it's not very bad(just in odd values on hdpi and ldpi devices need to add a little value when ldpi is not very common) I tested in a xxhdpi device that converts 4dp to 16(pixels) and that is true.

Label python data points on plot

How about print (x, y) at once.

from matplotlib import pyplot as plt

fig = plt.figure()
ax = fig.add_subplot(111)

A = -0.75, -0.25, 0, 0.25, 0.5, 0.75, 1.0
B = 0.73, 0.97, 1.0, 0.97, 0.88, 0.73, 0.54

plt.plot(A,B)
for xy in zip(A, B):                                       # <--
    ax.annotate('(%s, %s)' % xy, xy=xy, textcoords='data') # <--

plt.grid()
plt.show()

enter image description here

Getting the Username from the HKEY_USERS values

Done it, by a bit of creative programming,

  1. Enum the Keys in HKEY_USERS for those funny number keys...

  2. Enum the keys in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList\

and you will find the same numbers.... Now in those keys look at the String value: ProfileImagePath = "SomeValue" where the values are either:

"%systemroot%\system32\config\systemprofile"... not interested in this one... as its not a directory path...

%SystemDrive%\Documents and Settings\LocalService - "Local Services" %SystemDrive%\Documents and Settings\NetworkService "NETWORK SERVICE"

or

%SystemDrive%\Documents and Settings\USER_NAME, which translates directly to the "USERNAME" values in most un-tampered systems, ie. where the user has not changed the their user name after a few weeks or altered the paths explicitly...

SPAN vs DIV (inline-block)

As others have answered… div is a “block element” (now redefined as Flow Content) and span is an “inline element” (Phrasing Content). Yes, you may change the default presentation of these elements, but there is a difference between “flow” versus “block”, and “phrasing” versus “inline”.

An element classified as flow content can only be used where flow content is expected, and an element classified as phrasing content can be used where phrasing content is expected. Since all phrasing content is flow content, a phrasing element can also be used anywhere flow content is expected. The specs provide more detailed info.

All phrasing elements, such as strong and em, can only contain other phrasing elements: you can’t put a table inside a cite for instance. Most flow content such as div and li can contain all types of flow content (as well as phrasing content), but there are a few exceptions: p, pre, and th are examples of non-phrasing flow content (“block elements”) that can only contain phrasing content (“inline elements”). And of course there are the normal element restrictions such as dl and table only being allowed to contain certain elements.

While both div and p are non-phrasing flow content, the div can contain other flow content children (including more divs and ps). On the other hand, p may only contain phrasing content children. That means you can’t put a div inside a p, even though both are non-phrasing flow elements.

Now here’s the kicker. These semantic specifications are unrelated to how the element is displayed. Thus, if you have a div inside a span, you will get a validation error even if you have span {display: block;} and div {display: inline;} in your CSS.

Selenium webdriver click google search

There would be multiple ways to find an element (in your case the third Google Search result).

One of the ways would be using Xpath

#For the 3rd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[3]/div/h3/a")).click();
#For the 1st Link
driver.findElement(By.xpath(".//*[@id='rso']/li[2]/div/h3/a")).click();
#For the 2nd Link
driver.findElement(By.xpath(".//*[@id='rso']/li[1]/div/h3/a")).click();

The other options are

By.ByClassName 
By.ByCssSelector 
By.ById
By.ByLinkText
By.ByName
By.ByPartialLinkText 
By.ByTagName 

To better understand each one of them, you should try learning Selenium on something simpler than the Google Search Result page.

Example - http://www.google.com/intl/gu/contact/

To Interact with the Text input field with the placeholder "How can we help? Ask here." You could do it this way -

# By.ByClassName 
driver.findElement(By.ClassName("searchbox")).sendKeys("Hey!");
# By.ByCssSelector 
driver.findElement(By.CssSelector(".searchbox")).sendKeys("Hey!");
# By.ById
driver.findElement(By.Id("query")).sendKeys("Hey!");
# By.ByName
driver.findElement(By.Name("query")).sendKeys("Hey!");
# By.ByXpath
driver.findElement(By.xpath(".//*[@id='query']")).sendKeys("Hey!");

Download/Stream file from URL - asp.net

If you are looking for a .NET Core version of @Dallas's answer, use the below.

        Stream stream = null;

        //This controls how many bytes to read at a time and send to the client
        int bytesToRead = 10000;

        // Buffer to read bytes in chunk size specified above
        byte[] buffer = new Byte[bytesToRead];

        // The number of bytes read
        try
        {
            //Create a WebRequest to get the file
            HttpWebRequest fileReq = (HttpWebRequest)HttpWebRequest.Create(@"file url");

            //Create a response for this request
            HttpWebResponse fileResp = (HttpWebResponse)fileReq.GetResponse();

            if (fileReq.ContentLength > 0)
                fileResp.ContentLength = fileReq.ContentLength;

            //Get the Stream returned from the response
            stream = fileResp.GetResponseStream();

            // prepare the response to the client. resp is the client Response
            var resp = HttpContext.Response;

            //Indicate the type of data being sent
            resp.ContentType = "application/octet-stream";

            //Name the file 
            resp.Headers.Add("Content-Disposition", "attachment; filename=test.zip");
            resp.Headers.Add("Content-Length", fileResp.ContentLength.ToString());

            int length;
            do
            {
                // Verify that the client is connected.
                if (!HttpContext.RequestAborted.IsCancellationRequested)
                {
                    // Read data into the buffer.
                    length = stream.Read(buffer, 0, bytesToRead);

                    // and write it out to the response's output stream
                    resp.Body.Write(buffer, 0, length);


                    //Clear the buffer
                    buffer = new Byte[bytesToRead];
                }
                else
                {
                    // cancel the download if client has disconnected
                    length = -1;
                }
            } while (length > 0); //Repeat until no data is read
        }
        finally
        {
            if (stream != null)
            {
                //Close the input stream
                stream.Close();
            }
        }

SQL query with avg and group by

If I understand what you need, try this:

SELECT id, pass, AVG(val) AS val_1 
FROM data_r1 
GROUP BY id, pass;

Or, if you want just one row for every id, this:

SELECT d1.id,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 1) as val_1,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 2) as val_2,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 3) as val_3,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 4) as val_4,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 5) as val_5,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 6) as val_6,
    (SELECT IFNULL(ROUND(AVG(d2.val), 4) ,0) FROM data_r1 d2 
     WHERE d2.id = d1.id AND pass = 7) as val_7
from data_r1 d1
GROUP BY d1.id

@AspectJ pointcut for all methods of a class with specific annotation

Use

@Before("execution(* (@YourAnnotationAtClassLevel *).*(..))")
    public void beforeYourAnnotation(JoinPoint proceedingJoinPoint) throws Throwable {
}

What is the best way to detect a mobile device?

Here's a function you can use to get a true/false answer as to whether you're running on a mobile browser. Yes, it is browser-sniffing, but sometimes that is exactly what you need.

function is_mobile() {
    var agents = ['android', 'webos', 'iphone', 'ipad', 'blackberry'];
    for(i in agents) {
        if(navigator.userAgent.match('/'+agents[i]+'/i')) {
            return true;
        }
    }
    return false;
}

How can I quickly sum all numbers in a file?

This is straight Bash:

sum=0
while read -r line
do
    (( sum += line ))
done < file
echo $sum

How to "Open" and "Save" using java

You can find an introduction to file dialogs in the Java Tutorials. Java2s also has some example code.

How to get item's position in a list?

If your list got large enough and you only expected to find the value in a sparse number of indices, consider that this code could execute much faster because you don't have to iterate every value in the list.

lookingFor = 1
i = 0
index = 0
try:
  while i < len(testlist):
    index = testlist.index(lookingFor,i)
    i = index + 1
    print index
except ValueError: #testlist.index() cannot find lookingFor
  pass

If you expect to find the value a lot you should probably just append "index" to a list and print the list at the end to save time per iteration.

Alternative for <blink>

No there is not. Wikipedia has a nice article about this and provides an alternative using JavaScript and CSS: http://en.wikipedia.org/wiki/Blink_element

Automatically scroll down chat div

_x000D_
_x000D_
const messages = document.getElementById('messages');_x000D_
_x000D_
function appendMessage() {_x000D_
 const message = document.getElementsByClassName('message')[0];_x000D_
  const newMessage = message.cloneNode(true);_x000D_
  messages.appendChild(newMessage);_x000D_
}_x000D_
_x000D_
function getMessages() {_x000D_
 // Prior to getting your messages._x000D_
  shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;_x000D_
  /*_x000D_
   * Get your messages, we'll just simulate it by appending a new one syncronously._x000D_
   */_x000D_
  appendMessage();_x000D_
  // After getting your messages._x000D_
  if (!shouldScroll) {_x000D_
    scrollToBottom();_x000D_
  }_x000D_
}_x000D_
_x000D_
function scrollToBottom() {_x000D_
  messages.scrollTop = messages.scrollHeight;_x000D_
}_x000D_
_x000D_
scrollToBottom();_x000D_
_x000D_
setInterval(getMessages, 100);
_x000D_
#messages {_x000D_
  height: 200px;_x000D_
  overflow-y: auto;_x000D_
}
_x000D_
<div id="messages">_x000D_
  <div class="message">_x000D_
    Hello world_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How do I save a String to a text file using Java?

I think the best way is using Files.write(Path path, Iterable<? extends CharSequence> lines, OpenOption... options):

String text = "content";
Path path = Paths.get("path", "to", "file");
Files.write(path, Arrays.asList(text));

See javadoc:

Write lines of text to a file. Each line is a char sequence and is written to the file in sequence with each line terminated by the platform's line separator, as defined by the system property line.separator. Characters are encoded into bytes using the specified charset.

The options parameter specifies how the the file is created or opened. If no options are present then this method works as if the CREATE, TRUNCATE_EXISTING, and WRITE options are present. In other words, it opens the file for writing, creating the file if it doesn't exist, or initially truncating an existing regular-file to a size of 0. The method ensures that the file is closed when all lines have been written (or an I/O error or other runtime exception is thrown). If an I/O error occurs then it may do so after the file has created or truncated, or after some bytes have been written to the file.

Please note. I see people have already answered with Java's built-in Files.write, but what's special in my answer which nobody seems to mention is the overloaded version of the method which takes an Iterable of CharSequence (i.e. String), instead of a byte[] array, thus text.getBytes() is not required, which is a bit cleaner I think.

How to install requests module in Python 3.4, instead of 2.7

i just reinstalled the pip and it works, but I still wanna know why it happened...

i used the apt-get remove --purge python-pip after I just apt-get install pyhton-pip and it works, but don't ask me why...

Generate 'n' unique random numbers within a range

You could use the random.sample function from the standard library to select k elements from a population:

import random
random.sample(range(low, high), n)

In case of a rather large range of possible numbers, you could use itertools.islice with an infinite random generator:

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)
items = list(itertools.islice(gen, 10))  # Take first 10 random elements

After the question update it is now clear that you need n distinct (unique) numbers.

import itertools
import random

def random_gen(low, high):
    while True:
        yield random.randrange(low, high)

gen = random_gen(1, 100)

items = set()

# Try to add elem to set until set length is less than 10
for x in itertools.takewhile(lambda x: len(items) < 10, gen):
    items.add(x)

ADB - Android - Getting the name of the current activity

In windows, this command works for me to show current activity name

adb shell dumpsys window windows | find "mCurrentFocus"

Output:

mCurrentFocus=Window{a43a55b u0 com.android.contacts/com.android.contacts.activities.TwelveKeyDialer}

Other solutions with "grab" produce error in my windows pc

'grep' is not recognized as an internal or external command, operable program or batch file.

So, using "find" solve the error in my case.

Angular 6: saving data to local storage

First you should understand how localStorage works. you are doing wrong way to set/get values in local storage. Please read this for more information : How to Use Local Storage with JavaScript

Where does the iPhone Simulator store its data?

Found it:

~/Library/Application Support/iPhone Simulator/User/

Change the "No file chosen":

But if you try to remove this tooltip

<input type='file' title=""/>

This wont work. Here is my little trick to work this, try title with a space. It will work.:)

<input type='file' title=" "/>

ctypes - Beginner

The answer by Chinmay Kanchi is excellent but I wanted an example of a function which passes and returns a variables/arrays to a C++ code. I though I'd include it here in case it is useful to others.

Passing and returning an integer

The C++ code for a function which takes an integer and adds one to the returned value,

extern "C" int add_one(int i)
{
    return i+1;
}

Saved as file test.cpp, note the required extern "C" (this can be removed for C code). This is compiled using g++, with arguments similar to Chinmay Kanchi answer,

g++ -shared -o testlib.so -fPIC test.cpp

The Python code uses load_library from the numpy.ctypeslib assuming the path to the shared library in the same directory as the Python script,

import numpy.ctypeslib as ctl
import ctypes

libname = 'testlib.so'
libdir = './'
lib=ctl.load_library(libname, libdir)

py_add_one = lib.add_one
py_add_one.argtypes = [ctypes.c_int]
value = 5
results = py_add_one(value)
print(results)

This prints 6 as expected.

Passing and printing an array

You can also pass arrays as follows, for a C code to print the element of an array,

extern "C" void print_array(double* array, int N)
{
    for (int i=0; i<N; i++) 
        cout << i << " " << array[i] << endl;
}

which is compiled as before and the imported in the same way. The extra Python code to use this function would then be,

import numpy as np

py_print_array = lib.print_array
py_print_array.argtypes = [ctl.ndpointer(np.float64, 
                                         flags='aligned, c_contiguous'), 
                           ctypes.c_int]
A = np.array([1.4,2.6,3.0], dtype=np.float64)
py_print_array(A, 3)

where we specify the array, the first argument to print_array, as a pointer to a Numpy array of aligned, c_contiguous 64 bit floats and the second argument as an integer which tells the C code the number of elements in the Numpy array. This then printed by the C code as follows,

1.4
2.6
3.0

Xcode Error: "The app ID cannot be registered to your development team."

This happened to me, even though I had already registered the Bundle Id with my account. It turns out that the capitalisation differed, so I had to change the bundle id in Xcode to lowercase, and it all worked. Hope that helps someone else :)

Deserialize a json string to an object in python

In recent versions of python, you can use marshmallow-dataclass:

from marshmallow_dataclass import dataclass

@dataclass
class Payload
    action:str
    method:str
    data:str

Payload.Schema().load({"action":"print","method":"onData","data":"Madan Mohan"})

How can I get the current contents of an element in webdriver

My answer is based on this answer: How can I get the current contents of an element in webdriver just more like copy-paste.

from selenium import webdriver

driver = webdriver.Firefox()
driver.get('http://www.w3c.org')
element = driver.find_element_by_name('q')
element.send_keys('hi mom')

element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))


element = driver.find_element_by_css_selector('.description.expand_description > p')
element_text = element.text
element_attribute_value = element.get_attribute('value')

print (element)
print ('element.text: {0}'.format(element_text))
print ('element.get_attribute(\'value\'): {0}'.format(element_attribute_value))
driver.quit()

Java - Using Accessor and Mutator methods

Let's go over the basics: "Accessor" and "Mutator" are just fancy names fot a getter and a setter. A getter, "Accessor", returns a class's variable or its value. A setter, "Mutator", sets a class variable pointer or its value.

So first you need to set up a class with some variables to get/set:

public class IDCard
{
    private String mName;
    private String mFileName;
    private int mID;

}

But oh no! If you instantiate this class the default values for these variables will be meaningless. B.T.W. "instantiate" is a fancy word for doing:

IDCard test = new IDCard();

So - let's set up a default constructor, this is the method being called when you "instantiate" a class.

public IDCard()
{
    mName = "";
    mFileName = "";
    mID = -1;
}

But what if we do know the values we wanna give our variables? So let's make another constructor, one that takes parameters:

public IDCard(String name, int ID, String filename)
{
    mName = name;
    mID = ID;
    mFileName = filename;
}

Wow - this is nice. But stupid. Because we have no way of accessing (=reading) the values of our variables. So let's add a getter, and while we're at it, add a setter as well:

public String getName()
{
    return mName;
}

public void setName( String name )
{
    mName = name;
}

Nice. Now we can access mName. Add the rest of the accessors and mutators and you're now a certified Java newbie. Good luck.

How can I get the size of an std::vector as an int?

In the first two cases, you simply forgot to actually call the member function (!, it's not a value) std::vector<int>::size like this:

#include <vector>

int main () {
    std::vector<int> v;
    auto size = v.size();
}

Your third call

int size = v.size();

triggers a warning, as not every return value of that function (usually a 64 bit unsigned int) can be represented as a 32 bit signed int.

int size = static_cast<int>(v.size());

would always compile cleanly and also explicitly states that your conversion from std::vector::size_type to int was intended.

Note that if the size of the vector is greater than the biggest number an int can represent, size will contain an implementation defined (de facto garbage) value.

Given a DateTime object, how do I get an ISO 8601 date in string format?

To format like 2018-06-22T13:04:16 which can be passed in the URI of an API use:

public static string FormatDateTime(DateTime dateTime)
{
    return dateTime.ToString("s", System.Globalization.CultureInfo.InvariantCulture);
}

How can I pass a file argument to my bash script using a Terminal command in Linux?

Bash supports a concept called "Positional Parameters". These positional parameters represent arguments that are specified on the command line when a Bash script is invoked.

Positional parameters are referred to by the names $0, $1, $2 ... and so on. $0 is the name of the script itself, $1 is the first argument to the script, $2 the second, etc. $* represents all of the positional parameters, except for $0 (i.e. starting with $1).

An example:

#!/bin/bash
FILE="$1"
externalprogram "$FILE" <other-parameters>

Visual Studio 64 bit?

Is there any 64 bit Visual Studio at all?

Yes literally there is one called "Visual Studio" and is 64bit, but well,, on Mac not on Windows

Why not?

Decision making is electro-chemical reaction made in our brain and that have an activation point (Nerdest answer I can come up with, but follow). Same situation happened in history: Windows 64!...

So in order to answer this fully I want you to remember old days. Imagine reasons for "why not we see 64bit Windows" are there at the time. I think at the time for Windows64 they had exact same reasons others have enlisted here about "reasons why not 64bit VS on windows" were on "reasons why not 64bit Windows" too. Then why they did start development for Windows 64bit? Simple! If they didn't succeed in making 64bit Windows I bet M$ would have been a history nowadays. If same reasons forcing M$ making 64bit Windows starts to appear on need for 64Bit VS then I bet we will see 64bit VS, even though very same reasons everyone else here enlisted will stay same! In time the limitations of 32bit may hit VS as well, so most likely something like below start to happen:

  • Visual Studio will drop 32bit support and become 64bit,
  • Visual Studio Code will take it's place instead,
  • Visual Studio will have similar functionality like WOW64 for old extensions which is I believe unlikely to happen.

I put my bets on Visual Studio Code taking the place in time; I guess bifurcation point for it will be some CPU manufacturer X starts to compete x86_64 architecture taking its place on mainstream market for laptop and/or workstation,

Inserting Data into Hive Table

Hive apparently supports INSERT...VALUES starting in Hive 0.14.

Please see the section 'Inserting into tables from SQL' at: https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML

JavaScript loop through json array?

Your JSON should look like this:

var json = [{
    "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]"
}];

You can loop over the Array like this:

for(var i = 0; i < json.length; i++) {
    var obj = json[i];

    console.log(obj.id);
}

Or like this (suggested from Eric) be careful with IE support

json.forEach(function(obj) { console.log(obj.id); });

How do I copy SQL Azure database to my local development server?

I just wanted to add a simplified version of dumbledad's answer, since it is the correct one.

  1. Export the Azure SQL Database to a BACPAC file on blob storage.
  2. From inside SQL Management studio, right-click your database, click "import data-tier application".
  3. You'll be prompted to enter the information to get to the BACPAC file on your Azure blob storage.
  4. Hit next a couple times and... Done!

.attr('checked','checked') does not work

With jQuery, never use inline onclick javascript. Keep it unobtrusive. Do this instead, and remove the onclick completely.

Also, note the use of the :checked pseudo selector in the last line. The reason for this is because once the page is loaded, the html and the actual state of the form element can be different. Open a web inspector and you can click on the other radio button and the HTML will still show the first one is checked. The :checked selector instead filters elements that are actually checked, regardless of what the html started as.

$('button').click(function() {
    alert($('input[name="myname"][value="b"]').length);
    $('input[name="myname"][value="b"]').attr('checked','checked');
    $('#b').attr('checked',true);
    alert($('input[name="myname"]:checked').val());
});

http://jsfiddle.net/uL545/1/

How do I stop a web page from scrolling to the top when a link is clicked that triggers JavaScript?

You can simply write like this also:-

<a href="#!" onclick="function()">Delete User</a>

How to initialize an array of custom objects

I'd do something along these lines:

$myitems =
@([pscustomobject]@{name="Joe";age=32;info="something about him"},
[pscustomobject]@{name="Sue";age=29;info="something about her"},
[pscustomobject]@{name="Cat";age=12;info="something else"})

Note that this only works in PowerShell 3, but since you did not mention the version in your question I'm assuming this does not matter for you.

Update

It has been mentioned in comments that if you do the following:

$younger = $myitems | Where-Object { $_.age -lt 20 } 
Write-Host "people younger than 20: $($younger.Length)" 

You won't get 1 as you might expect. This happens when a single pscustomobject is returned. Now this is not a problem for most of other objects in PowerShell, because they have surrogate properties for Length and Count. Unfortunately pscustomobject does not. This is fixed in PowerShell 6.1.0. You can work around this by using operator @():

$younger = @($myitems | Where-Object { $_.age -lt 20 })

For more background see here and here.

Update 2

In PowerShell 5 one can use Classes to acheive similar functionality. For example you can define a class like this:

class Person {
    [string]$name
    [int]$age
    [string]$info; `
`
    Person(
    [string]$name,
    [int]$age,
    [string]$info
    ){
        $this.name = $name
        $this.age = $age
        $this.info = $info
    }
}

Backticks here are so that you could copy and paste it to the command line, they are not required in a script. Once the class is defined you can the create an array the usual way:

$myitems =@([Person]::new("Joe",32,"something about him"),
[Person]::new("Sue",29,"something about her"),
[Person]::new("Cat",12,"something else"))

Note that this way does not have the drawback mentioned in the previous update, even in PowerShell 5.

Update 3

You can also intialize a class object with a hashtable, similar to the first example. For that you need to make sure that a default contructor defined. If you do not provide any constructors, one will be created for you, but if you provide a non-default one, default constructor won't be there and you will need to define it explicitly. Here is an example with default constructor that is auto-created:

class Person {
    [string]$name
    [int]$age
    [string]$info;
}

With that you can:

$person = @([Person]@{name='Kevin';age=36;info="something about him"}
[Person]@{name='Sue';age=29;info="something about her"}
[Person]@{name='Cat';age=12;info="something else"})

This is a bit more verbose, but also a bit more explicit. Thanks to @js2010 for pointing this out.

Best way to change font colour halfway through paragraph?

wrap a <span> around those words and style with the appropriate color

now is the time for <span style='color:orange'>all good men</span> to come to the

How to convert comma-separated String to List?

You can do it as follows.

This removes white space and split by comma where you do not need to worry about white spaces.

    String myString= "A, B, C, D";

    //Remove whitespace and split by comma 
    List<String> finalString= Arrays.asList(myString.split("\\s*,\\s*"));

    System.out.println(finalString);

python pip on Windows - command 'cl.exe' failed

If you want it really easy and a joy to automate, check out Chocolatey.org/install and you can basically copy and paste these commands and tweak it based on what versions of VC++ you need.

This command is taken from https://chocolatey.org/install

Set-ExecutionPolicy Bypass -Scope Process -Force; [System.Net.ServicePointManager]::SecurityProtocol = [System.Net.ServicePointManager]::SecurityProtocol -bor 3072; iex ((New-Object System.Net.WebClient).DownloadString('https://chocolatey.org/install.ps1'))

Once you have chocolatey installed you can either close and reopen your Powershell terminal or run this command:

Import-Module "$env:ChocolateyInstall\helpers\chocolateyInstaller.psm1" ; Update-SessionEnvironment

Now you can use Chocolatey to install Python (latest version of 3.x is default).

choco install python

# This next command installs the latest VisualStudio installer that lets you get specific versions of the build
# Microsoft has replaced the 2015 and 2017 installer links with this one, and we can still use it to install the 2015 and 2017 components

choco install visualstudio2019buildtools --package-parameters "--add Microsoft.VisualStudio.Component.VC.140 --passive --locale en-US --add Microsoft.VisualStudio.Component.Windows10SDK.$($PSVersionTable.BuildVersion.Build) --no-includeRecommended" -y --timeout 0

# Usually need the "unlimited" timeout aka "0" because Visual Studio Installer takes forever

# Tool portion
# Microsoft.VisualStudio.Product.BuildTools
# Component portion(s)
# Microsoft.VisualStudio.Component.VC.140
# Win10SDK needs to match your current Win10 build version
# $($PSVersionTable.BuildVersion.Build)
# Microsoft.VisualStudio.Component.Windows10SDK.$($PSVersionTable.BuildVersion.Build)

# Because VS2019 Build Tools are dumb, need to manually link a couple files between the SDK and the VC++ dirs
# You may need to tweak the version here, but it has been updated to be as dynamic as possible 
# Use an elevated Powershell or elevated cmd prompt (if using cmd.exe just use the bits after /c)
cmd /c mklink "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\rc.exe" "C:\Program Files (x86)\Windows Kits\10\bin\$($PSVersionTable.BuildVersion.Major).$($PSVersionTable.BuildVersion.Minor).$($PSVersionTable.BuildVersion.Build).0\x64\rc.exe"

cmd /c mklink "C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\BIN\x86_amd64\rcdll.dll" "C:\Program Files (x86)\Windows Kits\10\bin\$($PSVersionTable.BuildVersion.Major).$($PSVersionTable.BuildVersion.Minor).$($PSVersionTable.BuildVersion.Build).0\x64\rcdll.dll"

Once you have this installed, you should reboot. I've occasionally had things work without a reboot, but your pip install commands will work best if you reboot first.

Now you can pip install pipenv or pip install complex-package and should be good to go.

Matplotlib different size subplots

Another way is to use the subplots function and pass the width ratio with gridspec_kw:

import numpy as np
import matplotlib.pyplot as plt 

# generate some data
x = np.arange(0, 10, 0.2)
y = np.sin(x)

# plot it
f, (a0, a1) = plt.subplots(1, 2, gridspec_kw={'width_ratios': [3, 1]})
a0.plot(x, y)
a1.plot(y, x)

f.tight_layout()
f.savefig('grid_figure.pdf')

Select From all tables - MySQL

why you dont just dump the mysql database but with extension when you run without --single-transaction you will interrupt the connection to other clients:

mysqldump --host=hostname.de --port=0000 --user=username --password=password --single-transaction --skip-add-locks --skip-lock-tables --default-character-set=utf8 datenbankname > mysqlDBBackup.sql 

after that read out the file and search for what you want.... in Strings.....

Center Div inside another (100% width) div

The below style to the inner div will center it.

margin: 0 auto;

Parameter binding on left joins with array in Laravel Query Builder

You don't have to bind parameters if you use query builder or eloquent ORM. However, if you use DB::raw(), ensure that you binding the parameters.

Try the following:

$array = array(1,2,3);       $query = DB::table('offers');             $query->select('id', 'business_id', 'address_id', 'title', 'details', 'value', 'total_available', 'start_date', 'end_date', 'terms', 'type', 'coupon_code', 'is_barcode_available', 'is_exclusive', 'userinformations_id', 'is_used');             $query->leftJoin('user_offer_collection', function ($join) use ($array)             {                 $join->on('user_offer_collection.offers_id', '=', 'offers.id')                       ->whereIn('user_offer_collection.user_id', $array);             });       $query->get(); 

Switch statement for greater-than/less-than

switch (Math.floor(scrollLeft/1000)) {
  case 0: // (<1000)
   //do stuff
   break;
  case 1: // (>=1000 && <2000)
   //do stuff;
   break;
}

Only works if you have regular steps...

EDIT: since this solution keeps getting upvotes, I must advice that mofolo's solution is a way better

React JS get current date

You can use the react-moment package

-> https://www.npmjs.com/package/react-moment

Put in your file the next line:

import moment from "moment";

date_create: moment().format("DD-MM-YYYY hh:mm:ss")

Inserting data into a temporary table

insert into #temptable (col1, col2, col3)
select col1, col2, col3 from othertable

Note that this is considered poor practice:

insert into #temptable 
select col1, col2, col3 from othertable

If the definition of the temp table were to change, the code could fail at runtime.

How to clear Route Caching on server: Laravel 5.2.37

For your case solution is :

php artisan cache:clear
php artisan route:cache

Optimizing Route Loading is a must on production :

If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:

php artisan route:cache

This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.

Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.

Laravel 5 clear cache from route, view, config and all cache data from application

I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.

Reoptimized class loader:

php artisan optimize

Clear Cache facade value:

php artisan cache:clear

Clear Route cache:

php artisan route:cache

Clear View cache:

php artisan view:clear

Clear Config cache:

php artisan config:cache

How to call two methods on button's onclick method in HTML or JavaScript?

  1. Try this:

    <input type="button" onclick="function1();function2();" value="Call2Functions" />
    
  2. Or, call second function at the end of first function:

       function func1(){
         //--- some logic
         func2();
       }
    
       function func2(){
        //--- some logic
       }
    

    ...and call func1() onclick of button:

    <input type="button" onclick="func1();" value="Call2Functions" />
    

How is the default max Java heap size determined?

default value is chosen at runtime based on system configuration

Have a look at the documentation page

Default Heap Size

Unless the initial and maximum heap sizes are specified on the command line, they are calculated based on the amount of memory on the machine.

  1. Client JVM Default Initial and Maximum Heap Sizes:

    The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes (MB) and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte (GB).

  2. Server JVM Default Initial and Maximum Heap Sizes:

    On 32-bit JVMs, the default maximum heap size can be up to 1 GB if there is 4 GB or more of physical memory. On 64-bit JVMs, the default maximum heap size can be up to 32 GB if there is 128 GB or more of physical memory

What system configuration settings influence the default value?

You can specify the initial and maximum heap sizes using the flags -Xms (initial heap size) and -Xmx (maximum heap size). If you know how much heap your application needs to work well, you can set -Xms and -Xmx to the same value

Difference between "char" and "String" in Java

char is a primitive type, and it can hold a single character. String is instead a reference type, thus a full-blown object.

How to create a fixed sidebar layout with Bootstrap 4?

I'm using the J.S. to fix a sidebar menu. I've tried a lot of solutions with CSS but it's the simplest way to solve it, just add J.S. adding and removing a native BootStrap class: "position-fixed".

The J.S.:

var lateral = false;
function fixar() {

            var element, name, arr;
            element = document.getElementById("minhasidebar");

            if (lateral) {
                element.className = element.className.replace(
                        /\bposition-fixed\b/g, "");
                lateral = false;
            } else {

                name = "position-fixed";
                arr = element.className.split(" ");
                if (arr.indexOf(name) == -1) {
                    element.className += " " + name;
                }
                lateral = true;
            }

        }

The HTML:

Sidebar:

<aside>
        <nav class="sidebar ">
             <div id="minhasidebar">
                 <ul class="nav nav-pills">
                     <li class="nav-item"><a class="nav-link active" 
                     th:href="@{/hoje/inicial}"> <i class="oi oi-clipboard"></i> 
                     <span>Hoje</span>
                     </a></li>
                 </ul>
             </div>
        </nav>            
</aside>

T-SQL loop over query results

My prefer solution is Microsoft KB 111401 http://support.microsoft.com/kb/111401.

The link refers to 3 examples:

This article describes various methods that you can use to simulate a cursor-like FETCH-NEXT logic in a stored procedure, trigger, or Transact-SQL batch.

/*********** example 1 ***********/ 

declare @au_id char( 11 )

set rowcount 0
select * into #mytemp from authors

set rowcount 1

select @au_id = au_id from #mytemp

while @@rowcount <> 0
begin
    set rowcount 0
    select * from #mytemp where au_id = @au_id
    delete #mytemp where au_id = @au_id

    set rowcount 1
    select @au_id = au_id from #mytemp
end
set rowcount 0



/********** example 2 **********/ 

declare @au_id char( 11 )

select @au_id = min( au_id ) from authors

while @au_id is not null
begin
    select * from authors where au_id = @au_id
    select @au_id = min( au_id ) from authors where au_id > @au_id
end



/********** example 3 **********/ 

set rowcount 0
select NULL mykey, * into #mytemp from authors

set rowcount 1
update #mytemp set mykey = 1

while @@rowcount > 0
begin
    set rowcount 0
    select * from #mytemp where mykey = 1
    delete #mytemp where mykey = 1
    set rowcount 1
    update #mytemp set mykey = 1
end
set rowcount 0

How to use color picker (eye dropper)?

To open the Eye Dropper simply:

  1. Open DevTools F12
  2. Go to Elements tab
  3. Under Styles side bar click on any color preview box

enter image description here

Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.

What are major differences between C# and Java?

The following is a great in depth reference by Dare Obasanjo on the differences between C# and Java. I always find myself referring to this article when switching between the two.

http://www.25hoursaday.com/CsharpVsJava.html

Is there a CSS selector for text nodes?

You cannot target text nodes with CSS. I'm with you; I wish you could... but you can't :(

If you don't wrap the text node in a <span> like @Jacob suggests, you could instead give the surrounding element padding as opposed to margin:

HTML

<p id="theParagraph">The text node!</p>

CSS

p#theParagraph
{
    border: 1px solid red;
    padding-bottom: 10px;
}

Bootstrap table without stripe / borders

The border styling is set on the td elements.

html:

<table class='table borderless'>

css:

.borderless td, .borderless th {
    border: none;
}

Update: Since Bootstrap 4.1 you can use .table-borderless to remove the border.

https://getbootstrap.com/docs/4.1/content/tables/#borderless-table

SameSite warning Chrome 77

To elaborate on Rahul Mahadik's answer, this works for MVC5 C#.NET:

AllowSameSiteAttribute.cs

public class AllowSameSiteAttribute : ActionFilterAttribute
{
    public override void OnActionExecuting(ActionExecutingContext filterContext)
    {
        var response = filterContext.RequestContext.HttpContext.Response;

        if(response != null)
        {
            response.AddHeader("Set-Cookie", "HttpOnly;Secure;SameSite=Strict");
            //Add more headers...
        }

        base.OnActionExecuting(filterContext);
    }
}

HomeController.cs

    [AllowSameSite] //For the whole controller
    public class UserController : Controller
    {
    }

or

    public class UserController : Controller
    {
        [AllowSameSite] //For the method
        public ActionResult Index()
        {
            return View();
        }
    }

Defining a percentage width for a LinearLayout?

You have to set the weight property of your elements. Create three RelativeLayouts as children to your LinearLayout and set weights 0.15, 0.70, 0.15. Then add your buttons to the second RelativeLayout(the one with weight 0.70).

Like this:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent" android:layout_height="fill_parent"
    android:id="@+id/layoutContainer" android:orientation="horizontal">
    <RelativeLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="0.15">
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="0.7">
        
        <!-- This is the part that's 70% of the total width. I'm inserting a LinearLayout and buttons.-->   
            <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_centerInParent="true"
            android:orientation="vertical">
                
                <Button 
                    android:text="Button1"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </Button>
                <Button
                    android:text="Button2"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </Button>
                <Button
                    android:text="Button3"
                    android:layout_width="fill_parent"
                    android:layout_height="wrap_content">
                </Button>
                
            </LinearLayout>
        <!-- 70% Width End-->
        
    </RelativeLayout>
    <RelativeLayout
        android:layout_width="0dip"
        android:layout_height="fill_parent"
        android:layout_weight="0.15">
    </RelativeLayout>
</LinearLayout>

Why are the weights 0.15, 0.7 and 0.15? Because the total weight is 1 and 0.7 is 70% of the total.

Result:

enter image description here

Edit: Thanks to @SimonVeloper for pointing out that the orientation should be horizontal and not vertical and to @Andrew for pointing out that weights can be decimals instead of integers.

How to create an executable .exe file from a .m file

If you have MATLAB Compiler installed, there's a GUI option for compiling. Try entering

deploytool

in the command line. Mathworks does a pretty good job documenting how to use it in this video tutorial: http://www.mathworks.com/products/demos/compiler/deploytool/index.html

Also, if you want to include user input such as choosing a file or directory, look into

uigetfile % or uigetdir if you need every file in a directory

for use in conjunction with

guide

Redirect to a page/URL after alert button is pressed

window.location = mypage.href is a direct command for the browser to dump it's contents and start loading up some more. So for better clarification, here's what's happening in your PHP script:

echo '<script type="text/javascript">'; 
echo 'alert("review your answer");'; 
echo 'window.location = "index.php";';
echo '</script>';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (albeit an older method of loading a new URL (AND NOTICE that there are no "\n" (new line) indicators between the lines and is therefore causing some havoc in the JS decoder.

Let me suggest that you do this another way..

echo '<script type="text/javascript">\n'; 
echo 'alert("review your answer");\n'; 
echo 'document.location.href = "index.php";\n';
echo '</script>\n';

1) prepare to accept a modification or addition to the current Javascript cache. 2) show the alert 3) dump everything in browser memory and get ready for some more (in a better fashion than before) And WOW - it all works because the JS decoder can see that each command is anow a new line.

Best of luck!

UL or DIV vertical scrollbar

Sometimes it is not eligible to set height to pixel values. However, it is possible to show vertical scrollbar through setting height of div to 100% and overflow to auto.

Let me show an example:

<div id="content" style="height: 100%; overflow: auto">
  <p>some text</p>
  <ul>
    <li>text</li>
    .....
    <li>text</li>
</div>

javax.xml.bind.UnmarshalException: unexpected element. Expected elements are (none)

Alternatively if you want to persist in using the DocumentType class. Then you could just add the following annotation on top of your DocumentType class.

    @XmlRootElement(name="document")

Note: the String value "document" refers to the name of the root tag of the xml message.

Oracle DB: How can I write query ignoring case?

In version 12.2 and above, the simplest way to make the query case insensitive is this:

SELECT * FROM TABLE WHERE TABLE.NAME COLLATE BINARY_CI Like 'IgNoReCaSe'

How to remove a web site from google analytics

You can also do in this way : select your profile then go to admin => in admin second column "Property" select the site you want to remove => go to third column "view settings" clic => on the right bottom you ll see delete the view => confirm and it s done , have a nice day all

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

You can add function to:

c:\Users\David\Documents\WindowsPowerShell\profile.ps1

An the function will be available.

Can (domain name) subdomains have an underscore "_" in it?

Just created local project (with vagrant) and it was working perfectly when accessed over ip address. Then I added some_name.test to hosts file and tried accessing it that way, but I was getting "bad request - 400" all the time. Wasted hours until I figured out that just changing domain name to some-name.test solves the problem. So at least locally on Mac OS it's not working.

Send value of submit button when form gets posted

You could use something like this to give your button a value:

<?php
if (isset($_POST['submit'])) {
  $aSubmitVal = array_keys($_POST['submit'])[0];
  echo 'The button value is: ' . $aSubmitVal;
}
?>
<form action="/" method="post">
  <input id="someId" type="submit" name="submit[SomeValue]" value="Button name">
</form>

This will give you the string "SomeValue" as a result

https://i.imgur.com/28gr7Uy.gif

Rename a dictionary key

@helloswift123 I like your function. Here is a modification to rename multiple keys in a single call:

def rename(d, keymap):
    """
    :param d: old dict
    :type d: dict
    :param keymap: [{:keys from-keys :values to-keys} keymap]
    :returns: new dict
    :rtype: dict
    """
    new_dict = {}
    for key, value in zip(d.keys(), d.values()):
        new_key = keymap.get(key, key)
        new_dict[new_key] = d[key]
    return new_dict

Get docker container id from container name

  1. Get container Ids of running containers ::

    $docker ps -qf "name=IMAGE_NAME"
    
        -f: Filter output based on conditions provided
        -q: Only display numeric container IDs
    
  2. Get container Ids of all containers ::

    $docker ps -aqf "name=IMAGE_NAME"
    
        -a: all containers
    

Transpose a matrix in Python

If we wanted to return the same matrix we would write:

return [[ m[row][col] for col in range(0,width) ] for row in range(0,height) ]

What this does is it iterates over a matrix m by going through each row and returning each element in each column. So the order would be like:

[[1,2,3],
[4,5,6],
[7,8,9]]

Now for question 3, we instead want to go column by column, returning each element in each row. So the order would be like:

[[1,4,7],
[2,5,8],
[3,6,9]]

Therefore just switch the order in which we iterate:

return [[ m[row][col] for row in range(0,height) ] for col in range(0,width) ]

JAXB Exception: Class not known to this context

I had this error because I registered the wrong class in this line of code:

JAXBContext context = JAXBContext.newInstance(MyRootXmlClass.class);

How can I compare time in SQL Server?

You can create a two variables of datetime, and set only hour of date that your need to compare.

declare  @date1 datetime;
declare  @date2 datetime;

select   @date1 = CONVERT(varchar(20),CONVERT(datetime, '2011-02-11 08:00:00'), 114)
select   @date2 = CONVERT(varchar(20),GETDATE(), 114)

The date will be "1900-01-01" you can compare it

if @date1 <= @date2
   print '@date1 less then @date2'
else
   print '@date1 more then @date2'

AlertDialog styling - how to change style (color) of title, message, etc

You have to add the style to the constructor of the dialog

builder = new AlertDialog.Builder(this, R.style.DialogStyle);

What is the easiest way to clear a database from the CLI with manage.py in Django?

I think Django docs explicitly mention that if the intent is to start from an empty DB again (which seems to be OP's intent), then just drop and re-create the database and re-run migrate (instead of using flush):

If you would rather start from an empty database and re-run all migrations, you should drop and recreate the database and then run migrate instead.

So for OP's case, we just need to:

  1. Drop the database from MySQL
  2. Recreate the database
  3. Run python manage.py migrate

In Perl, what is the difference between a .pm (Perl module) and .pl (Perl script) file?

A .pl is a single script.

In .pm (Perl Module) you have functions that you can use from other Perl scripts:

A Perl module is a self-contained piece of Perl code that can be used by a Perl program or by other Perl modules. It is conceptually similar to a C link library, or a C++ class.