Programs & Examples On #Dynamicquery

How to set table name in dynamic SQL query?

Try this:

/* Variable Declaration */
DECLARE @EmpID AS SMALLINT
DECLARE @SQLQuery AS NVARCHAR(500)
DECLARE @ParameterDefinition AS NVARCHAR(100)
DECLARE @TableName AS NVARCHAR(100)
/* set the parameter value */
SET @EmpID = 1001
SET @TableName = 'tblEmployees'
/* Build Transact-SQL String by including the parameter */
SET @SQLQuery = 'SELECT * FROM ' + @TableName + ' WHERE EmployeeID = @EmpID' 
/* Specify Parameter Format */
SET @ParameterDefinition =  '@EmpID SMALLINT'
/* Execute Transact-SQL String */
EXECUTE sp_executesql @SQLQuery, @ParameterDefinition, @EmpID

What does numpy.random.seed(0) do?

Imagine you are showing someone how to code something with a bunch of "random" numbers. By using numpy seed they can use the same seed number and get the same set of "random" numbers.

So it's not exactly random because an algorithm spits out the numbers but it looks like a randomly generated bunch.

Sorting arrays in NumPy by column

A little more complicated lexsort example - descending on the 1st column, secondarily ascending on the 2nd. The tricks with lexsort are that it sorts on rows (hence the .T), and gives priority to the last.

In [120]: b=np.array([[1,2,1],[3,1,2],[1,1,3],[2,3,4],[3,2,5],[2,1,6]])
In [121]: b
Out[121]: 
array([[1, 2, 1],
       [3, 1, 2],
       [1, 1, 3],
       [2, 3, 4],
       [3, 2, 5],
       [2, 1, 6]])
In [122]: b[np.lexsort(([1,-1]*b[:,[1,0]]).T)]
Out[122]: 
array([[3, 1, 2],
       [3, 2, 5],
       [2, 1, 6],
       [2, 3, 4],
       [1, 1, 3],
       [1, 2, 1]])

How do I pull my project from github?

First, you'll need to tell git about yourself. Get your username and token together from your settings page.

Then run:

git config --global github.user YOUR_USERNAME
git config --global github.token YOURTOKEN

You will need to generate a new key if you don't have a back-up of your key.

Then you should be able to run:

git clone [email protected]:YOUR_USERNAME/YOUR_PROJECT.git

Copy Data from a table in one Database to another separate database

It's db1.dbo.TempTable and db2.dbo.TempTable

The four-part naming scheme goes:

ServerName.DatabaseName.Schema.Object

How to print out all the elements of a List in Java?

I happen to be working on this now...

List<Integer> a = Arrays.asList(1, 2, 3);
List<Integer> b = Arrays.asList(3, 4);
List<int[]> pairs = a.stream()
  .flatMap(x -> b.stream().map(y -> new int[]{x, y}))
  .collect(Collectors.toList());

Consumer<int[]> pretty = xs -> System.out.printf("\n(%d,%d)", xs[0], xs[1]);
pairs.forEach(pretty);

How to export non-exportable private key from store

Gentil Kiwi's answer is correct. He developed this mimikatz tool that is able to retrieve non-exportable private keys.

However, his instructions are outdated. You need:

  1. Download the lastest release from https://github.com/gentilkiwi/mimikatz/releases

  2. Run the cmd with admin rights in the same machine where the certificate was requested

  3. Change to the mimikatz bin directory (Win32 or x64 version)

  4. Run mimikatz

  5. Follow the wiki instructions and the .pfx file (protected with password mimikatz) will be placed in the same folder of the mimikatz bin

mimikatz # crypto::capi
Local CryptoAPI patched

mimikatz # privilege::debug
Privilege '20' OK

mimikatz # crypto::cng
"KeyIso" service patched

mimikatz # crypto::certificates /systemstore:local_machine /store:my /export
* System Store : 'local_machine' (0x00020000)
* Store : 'my'

  1. example.domain.local
         Key Container : example.domain.local
         Provider : Microsoft Software Key Storage Provider
         Type : CNG Key (0xffffffff)
         Exportable key : NO
         Key size : 2048
         Public export : OK - 'local_machine_my_0_example.domain.local.der'
         Private export : OK - 'local_machine_my_0_example.domain.local.pfx'

What happens if you don't commit a transaction to a database (say, SQL Server)?

Example for Transaction

begin tran tt

Your sql statements

if error occurred rollback tran tt else commit tran tt

As long as you have not executed commit tran tt , data will not be changed

Undocumented NSURLErrorDomain error codes (-1001, -1003 and -1004) using StoreKit

I found a new error code which is not documented above: CFNetworkErrorCode -1022

Error Domain=NSURLErrorDomain Code=-1022 "The resource could not be loaded because the App Transport Security policy requires the use of a secure connection."

The import org.junit cannot be resolved

In starting code line copy past 'Junit' or 'TestNG' elements will show with Error till you import library with the Project File.

To import Libraries in to project:

Right Click on the Project --> Properties --> Java Build Path --> Libraries -> Add Library -> 'Junit' or 'TestNG'

Add Junit Libraries

How to create cron job using PHP?

_x000D_
_x000D_
$command = "php ".CRON_PATH.php ";_x000D_
if(substr(php_uname(), 0, 7) == "Windows"){_x000D_
pclose(popen("start /B ". $command, "r"));_x000D_
}else{_x000D_
shell_exec($command ." > /dev/null &");_x000D_
}
_x000D_
_x000D_
_x000D_

Using ResourceManager

The quick and dirty way to check what string you need it to look at the generated .resources files.

Your .resources are generated in the resources projects obj/Debug directory. (if not right click on .resx file in solution explorer and hit 'Run Custom Tool' to generate the .resources files)

Navigate to this directory and have a look at the filenames. You should see a file ending in XYZ.resources. Copy that filename and remove the trailing .resources and that is the file you should be loading.

For example in my obj/Bin directory I have the file:

MyLocalisation.Properties.Resources.resources

If the resource files are in the same Class library/Application I would use the following C#

ResourceManager RM = new ResourceManager("MyLocalisation.Properties.Resources", Assembly.GetExecutingAssembly());

However, as it sounds like you are using the resources file from a separate Class library/Application you probably want

Assembly localisationAssembly = Assembly.Load("MyLocalisation");
ResourceManager RM =  new ResourceManager("MyLocalisation.Properties.Resources", localisationAssembly);

Div with margin-left and width:100% overflowing on the right side

If some other portion of your layout is influencing the div width you can set width:auto and the div (which is a block element) will fill the space

<div style="width:auto">
    <div style="margin-left:45px;width:auto">
        <asp:TextBox ID="txtTitle" runat="server" Width="100%"></asp:TextBox><br />
    </div>
</div>

If that's still not working we may need to see more of your layout HTML/CSS

How to display JavaScript variables in a HTML page without document.write

Element.innerHTML is pretty much the way to go. Here are a few ways to use it:

HTML

<div class="results"></div>

JavaScript

// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.results').innerHTML = 'Hello World!';

// Using the jQuery library
$('.results').html('Hello World!');

If you just want to update a portion of a <div> I usually just add an empty element with a class like value or one I want to replace the contents of to the main <div>. e.g.

<div class="content">Hello <span class='value'></span></div>

Then I'd use some code like this:

// 'Modern' browsers (IE8+, use CSS-style selectors)
document.querySelector('.content .value').innerHTML = 'World!';

// Using the jQuery library
$(".content .value").html("World!");

Then the HTML/DOM would now contain:

<div class="content">Hello <span class='value'>World!</span></div>

Full example. Click run snippet to try it out.

_x000D_
_x000D_
// Plain Javascript Example_x000D_
var $jsName = document.querySelector('.name');_x000D_
var $jsValue = document.querySelector('.jsValue');_x000D_
_x000D_
$jsName.addEventListener('input', function(event){_x000D_
  $jsValue.innerHTML = $jsName.value;_x000D_
}, false);_x000D_
_x000D_
_x000D_
// JQuery example_x000D_
var $jqName = $('.name');_x000D_
var $jqValue = $('.jqValue');_x000D_
_x000D_
$jqName.on('input', function(event){_x000D_
  $jqValue.html($jqName.val());_x000D_
});
_x000D_
html {_x000D_
  font-family: sans-serif;_x000D_
  font-size: 16px;_x000D_
}_x000D_
_x000D_
h1 {_x000D_
  margin: 1em 0 0.25em 0;_x000D_
}_x000D_
_x000D_
input[type=text] {_x000D_
  padding: 0.5em;_x000D_
}_x000D_
_x000D_
.jsValue, .jqValue {_x000D_
  color: red;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>_x000D_
  <meta charset="utf-8">_x000D_
  <meta name="viewport" content="width=device-width">_x000D_
  <title>Setting HTML content example</title>_x000D_
</head>_x000D_
<body>_x000D_
  <!-- This <input> field is where I'm getting the name from -->_x000D_
  <label>Enter your name: <input class="name" type="text" value="World"/></label>_x000D_
  _x000D_
  <!-- Plain Javascript Example -->_x000D_
  <h1>Plain Javascript Example</h1>Hello <span class="jsValue">World</span>_x000D_
  _x000D_
  <!-- jQuery Example -->_x000D_
  <h1>jQuery Example</h1>Hello <span class="jqValue">World</span>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed

Typically you see this error after you have already done a redirect and then try to output some more data to the output stream. In the cases where I have seen this in the past, it is often one of the filters that is trying to redirect the page, and then still forwards through to the servlet. I cannot see anything immediately wrong with the servlet, so you might want to try having a look at any filters that you have in place as well.

Edit: Some more help in diagnosing the problem…

The first step to diagnosing this problem is to ascertain exactly where the exception is being thrown. We are assuming that it is being thrown by the line

getServletConfig().getServletContext()
                  .getRequestDispatcher("/GroupCopiedUpdt.jsp")
                  .forward(request, response);

But you might find that it is being thrown later in the code, where you are trying to output to the output stream after you have tried to do the forward. If it is coming from the above line, then it means that somewhere before this line you have either:

  1. output data to the output stream, or
  2. done another redirect beforehand.

Good luck!

How to get the latest record in each group using GROUP BY?

Just complementing what Devart said, the below code is not ordering according to the question:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages GROUP BY from_id) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp;

The "GROUP BY" clause must be in the main query since that we need first reorder the "SOURCE" to get the needed "grouping" so:

SELECT t1.* FROM messages t1
  JOIN (SELECT from_id, MAX(timestamp) timestamp FROM messages ORDER BY timestamp DESC) t2
    ON t1.from_id = t2.from_id AND t1.timestamp = t2.timestamp GROUP BY t2.timestamp;

Regards,

How to delete images from a private docker registry?

Here is a script based on Yavuz Sert's answer. It deletes all tags that are not the latest version, and their tag is greater than 950.

#!/usr/bin/env bash


CheckTag(){
    Name=$1
    Tag=$2

    Skip=0
    if [[ "${Tag}" == "latest" ]]; then
        Skip=1
    fi
    if [[ "${Tag}" -ge "950" ]]; then
        Skip=1
    fi
    if [[ "${Skip}" == "1" ]]; then
        echo "skip ${Name} ${Tag}"
    else
        echo "delete ${Name} ${Tag}"
        Sha=$(curl -v -s -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X GET http://127.0.0.1:5000/v2/${Name}/manifests/${Tag} 2>&1 | grep Docker-Content-Digest | awk '{print ($3)}')
        Sha="${Sha/$'\r'/}"
        curl -H "Accept: application/vnd.docker.distribution.manifest.v2+json" -X DELETE "http://127.0.0.1:5000/v2/${Name}/manifests/${Sha}"
    fi
}

ScanRepository(){
    Name=$1
    echo "Repository ${Name}"
    curl -s http://127.0.0.1:5000/v2/${Name}/tags/list | jq '.tags[]' |
    while IFS=$"\n" read -r line; do
        line="${line%\"}"
        line="${line#\"}"
        CheckTag $Name $line
    done
}


JqPath=$(which jq)
if [[ "x${JqPath}" == "x" ]]; then
  echo "Couldn't find jq executable."
  exit 2
fi

curl -s http://127.0.0.1:5000/v2/_catalog | jq '.repositories[]' |
while IFS=$"\n" read -r line; do
    line="${line%\"}"
    line="${line#\"}"
    ScanRepository $line
done

Change the Theme in Jupyter Notebook?

After I changed the theme it behaved strangely. The font size was small, cannot see the toolbar and I really didn't like the new look.

For those who want to restore the original theme, you can do it as follows:

jt -r

You need to restart Jupyter the first time you do it and later refresh is enough to enable the new theme.

or directly from inside the notebook

!jt -r

How do I search an SQL Server database for a string?

This will search for a string over every database:

declare @search_term varchar(max)
set @search_term = 'something'

select @search_term = 'use ? SET QUOTED_IDENTIFIER ON
select
    ''[''+db_name()+''].[''+c.name+''].[''+b.name+'']'' as [object],
    b.type_desc as [type],
    d.obj_def.value(''.'',''varchar(max)'') as [definition]
from (
    select distinct
        a.id
    from sys.syscomments a
    where a.[text] like ''%'+@search_term+'%''
) a
inner join sys.all_objects b
    on b.[object_id] = a.id
inner join sys.schemas c
    on c.[schema_id] = b.[schema_id]
cross apply (
    select
        [text()] = a1.[text]
    from sys.syscomments a1
    where a1.id = a.id
    order by a1.colid
    for xml path(''''), type
) d(obj_def)
where c.schema_id not in (3,4) -- avoid searching in sys and INFORMATION_SCHEMA schemas
    and db_id() not in (1,2,3,4) -- avoid sys databases'

if object_id('tempdb..#textsearch') is not null drop table #textsearch
create table #textsearch
(
    [object] varchar(300),
    [type] varchar(300),
    [definition] varchar(max)
)

insert #textsearch
exec sp_MSforeachdb @search_term

select *
from #textsearch
order by [object]

Fatal error: Call to undefined function pg_connect()

You need to install the php-pgsql package or whatever it's called for your platform. Which I don't think you said by the way.

On Ubuntu and Debian:

sudo apt-get install php5-pgsql

Add a new item to recyclerview programmatically?

if you are adding multiple items to the list use this:

mAdapter.notifyItemRangeInserted(startPosition, itemcount);

This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount

existing item in the dataset still considered up to date.

Adding an onclicklistener to listview (android)

listView.setOnItemClickListener(new OnItemClickListener() {

    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        Object o = prestListView.getItemAtPosition(position);
        prestationEco str = (prestationEco)o; //As you are using Default String Adapter
        Toast.makeText(getBaseContext(),str.getTitle(),Toast.LENGTH_SHORT).show();
    }
});

Is "else if" faster than "switch() case"?

For just a few items, the difference is small. If you have many items you should definitely use a switch.

If a switch contains more than five items, it's implemented using a lookup table or a hash list. This means that all items get the same access time, compared to a list of if:s where the last item takes much more time to reach as it has to evaluate every previous condition first.

How to configure robots.txt to allow everything?

That file will allow all crawlers access

User-agent: *
Allow: /

This basically allows all user agents (the *) to all parts of the site (the /).

Regex in JavaScript for validating decimal numbers

Does this work?

[0-9]{2}.[0-9]{2}

Create dataframe from a matrix

Using dplyr and tidyr:

library(dplyr)
library(tidyr)

df <- as_data_frame(mat) %>%      # convert the matrix to a data frame
  gather(name, val, C_0:C_1) %>%  # convert the data frame from wide to long
  select(name, time, val)         # reorder the columns

df
# A tibble: 6 x 3
   name  time   val
  <chr> <dbl> <dbl>
1   C_0   0.0   0.1
2   C_0   0.5   0.2
3   C_0   1.0   0.3
4   C_1   0.0   0.3
5   C_1   0.5   0.4
6   C_1   1.0   0.5

How to get the browser to navigate to URL in JavaScript

This works in all browsers:

window.location.href = '...';

If you wanted to change the page without it reflecting in the browser back history, you can do:

window.location.replace('...');

How to code a BAT file to always run as admin mode?

If you can use a third party utility, here is an elevate command line utility.

This is the usage description:

Usage: Elevate [-?|-wait|-k] prog [args]
-?    - Shows this help
-wait - Waits until prog terminates
-k    - Starts the the %COMSPEC% environment variable value and
                executes prog in it (CMD.EXE, 4NT.EXE, etc.)
prog  - The program to execute
args  - Optional command line arguments to prog

Command-line svn for Windows?

Install MSYS2, it has svn in its repository (besides lots of other Unix goodies). MSYS2 installs without Windows Admin rights.

$ pacman -S svn

The tools can be used from cmd, too:

C:\>C:\msys64\usr\bin\svn.exe co http://somehost/somerepo/

How to append contents of multiple files into one file

Another option is sed:

sed r 1.txt 2.txt 3.txt > merge.txt 

Or...

sed h 1.txt 2.txt 3.txt > merge.txt 

Or...

sed -n p 1.txt 2.txt 3.txt > merge.txt # -n is mandatory here

Or without redirection ...

sed wmerge.txt 1.txt 2.txt 3.txt

Note that last line write also merge.txt (not wmerge.txt!). You can use w"merge.txt" to avoid confusion with the file name, and -n for silent output.

Of course, you can also shorten the file list with wildcards. For instance, in case of numbered files as in the above examples, you can specify the range with braces in this way:

sed -n w"merge.txt" {1..3}.txt

How can I set a cookie in react?

Use vanilla js, example

document.cookie = `referral_key=hello;max-age=604800;domain=example.com`

Read more at: https://developer.mozilla.org/en-US/docs/Web/API/Document/cookie

How to make a flex item not fill the height of the flex container?

When you create a flex container various default flex rules come into play.

Two of these default rules are flex-direction: row and align-items: stretch. This means that flex items will automatically align in a single row, and each item will fill the height of the container.

If you don't want flex items to stretch – i.e., like you wrote:

make its height the minimum required for holding its content

... then simply override the default with align-items: flex-start.

_x000D_
_x000D_
#a {_x000D_
  display: flex;_x000D_
  align-items: flex-start; /* NEW */_x000D_
}_x000D_
#a > div {_x000D_
  background-color: red;_x000D_
  padding: 5px;_x000D_
  margin: 2px;_x000D_
}_x000D_
#b {_x000D_
  height: auto;_x000D_
}
_x000D_
<div id="a">_x000D_
  <div id="b">left</div>_x000D_
  <div>_x000D_
    right<br>right<br>right<br>right<br>right<br>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Here's an illustration from the flexbox spec that highlights the five values for align-items and how they position flex items within the container. As mentioned before, stretch is the default value.

enter image description here Source: W3C

Formatting code snippets for blogging on Blogger

I have created a tool that gets the job done. You can find it on my blog:

Free Online C# Code Colorizer

Besides colorizing your C# code, the tool also takes care of all the '<' and '>' symbols convering them to '&lt;' and '&gt;'. Tabs are converted to spaces in order to look the same in different browsers. You can even make the colorizer inline the CSS styles, in case you cannot or you do not want to insert a CSS style sheet in you blog or website.

iPhone: Setting Navigation Bar Title

if you are doing it all by code in the viewDidLoad method of the UIViewController you should only add self.title = @"title text";

something like this:

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"title";
}

you could also try self.navigationItem.title = @"title";

also check if your navigationItem is not null and if you have set a custom background to the navigationbar check if the title is set without it.

Java Thread Example?

There is no guarantee that your threads are executing simultaneously regardless of any trivial example anyone else posts. If your OS only gives the java process one processor to work on, your java threads will still be scheduled for each time slice in a round robin fashion. Meaning, no two will ever be executing simultaneously, but the work they do will be interleaved. You can use monitoring tools like Java's Visual VM (standard in the JDK) to observe the threads executing in a Java process.

Is it possible to run .php files on my local computer?

Sure you just need to setup a local web server. Check out XAMPP: http://www.apachefriends.org/en/xampp.html

That will get you up and running in about 10 minutes.

There is now a way to run php locally without installing a server: https://stackoverflow.com/a/21872484/672229


Yes but the files need to be processed. For example you can install test servers like mamp / lamp / wamp depending on your plateform.

Basically you need apache / php running.

How to write URLs in Latex?

A minimalist implementation of the \url macro that uses only Tex primitives:

\def\url#1{\expandafter\string\csname #1\endcsname}

This url absolutely won't break over lines, though; the hypperef package is better for that.

What's the difference between “mod” and “remainder”?

In C and C++ and many languages, % is the remainder NOT the modulus operator.

For example in the operation -21 / 4 the integer part is -5 and the decimal part is -.25. The remainder is the fractional part times the divisor, so our remainder is -1. JavaScript uses the remainder operator and confirms this

_x000D_
_x000D_
console.log(-21 % 4 == -1);
_x000D_
_x000D_
_x000D_

The modulus operator is like you had a "clock". Imagine a circle with the values 0, 1, 2, and 3 at the 12 o'clock, 3 o'clock, 6 o'clock, and 9 o'clock positions respectively. Stepping quotient times around the clock clock-wise lands us on the result of our modulus operation, or, in our example with a negative quotient, counter-clockwise, yielding 3.

Note: Modulus is always the same sign as the divisor and remainder the same sign as the quotient. Adding the divisor and the remainder when at least one is negative yields the modulus.

How to make the python interpreter correctly handle non-ASCII characters in string operations?

This is a dirty hack, but may work.

s2 = ""
for i in s:
    if ord(i) < 128:
        s2 += i

How do I install chkconfig on Ubuntu?

Install this package in Ubuntu:

apt install sysv-rc-conf

its a substitute for chkconfig cmd.

After install run this cmd:

sysv-rc-conf --list

It'll show all services in all the runlevels. You can also run this:

sysv-rc-conf --level (runlevel number ex:1 2 3 4 5 6 )

Now you can choose which service should be active in boot time.

How do I change Bootstrap 3's glyphicons to white?

You can just create your own .white class and add it to the glyphicon element.

.white, .white a {
  color: #fff;
}
<i class="glyphicon glyphicon-home white"></i>

How to make a Bootstrap accordion collapse when clicking the header div?

Simple solution would be to remove padding from .panel-heading and add to .panel-title a.

.panel-heading {
    padding: 0;
}
.panel-title a {
    display: block;
    padding: 10px 15px;
}

This solution is similar to the above one posted by calfzhou, slightly different.

How to override application.properties during production in Spring-Boot?

I know you asked how to do this, but the answer is you should not do this.

Instead, have a application.properties, application-default.properties application-dev.properties etc., and switch profiles via args to the JVM: e.g. -Dspring.profiles.active=dev

You can also override some things at test time using @TestPropertySource

Ideally everything should be in source control so that there are no surprises e.g. How do you know what properties are sitting there in your server location, and which ones are missing? What happens if developers introduce new things?

Spring Boot is already giving you enough ways to do this right.

https://docs.spring.io/spring-boot/docs/current/reference/html/boot-features-external-config.html

Freely convert between List<T> and IEnumerable<T>

Converting List<T> to IEnumerable<T>

List<T> implements IEnumerable<T> (and many other such as IList<T>, ICollection<T>) therefore there is no need to convert a List back to IEnumerable since it already a IEnumerable<T>.

Example:

public class Person
{
    public int Id { get; set; }
    public string Name { get; set; }
}

Person person1 = new Person() { Id = 1, Name = "Person 1" };
Person person2 = new Person() { Id = 2, Name = "Person 2" };
Person person3 = new Person() { Id = 3, Name = "Person 3" };

List<Person> people = new List<Person>() { person1, person2, person3 };

//Converting to an IEnumerable
IEnumerable<Person> IEnumerableList = people;

You can also use Enumerable.AsEnumerable() method

IEnumerable<Person> iPersonList = people.AsEnumerable();

Converting IEnumerable<T> to List<T>

IEnumerable<Person> OriginallyIEnumerable = new List<Person>() { person1, person2 };
List<Person> convertToList = OriginallyIEnumerable.ToList();

This is useful in Entity Framework.

How to write string literals in python without having to escape them?

You will find Python's string literal documentation here:

http://docs.python.org/tutorial/introduction.html#strings

and here:

http://docs.python.org/reference/lexical_analysis.html#literals

The simplest example would be using the 'r' prefix:

ss = r'Hello\nWorld'
print(ss)
Hello\nWorld

Custom checkbox image android

If you use androidx.appcompat:appcompat and want a custom drawable (of type selector with android:state_checked) to work on old platform versions in addition to new platform versions, you need to use

    <CheckBox
        app:buttonCompat="@drawable/..."

instead of

    <CheckBox
        android:button="@drawable/..."

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

The particular exception message is telling you that the mentioned class is missing in the classpath. As the org.apache.commons.io package name hints, the mentioned class is part of the http://commons.apache.org/io project.

And indeed, Commons FileUpload has Commons IO as a dependency. You need to download and drop commons-io.jar in the /WEB-INF/lib as well.

See also:

Sorting a Python list by two fields

No need to import anything when using lambda functions.
The following sorts list by the first element, then by the second element.

sorted(list, key=lambda x: (x[0], -x[1]))

How to choose an AWS profile when using boto3 to connect to CloudFront

I think the docs aren't wonderful at exposing how to do this. It has been a supported feature for some time, however, and there are some details in this pull request.

So there are three different ways to do this:

Option A) Create a new session with the profile

    dev = boto3.session.Session(profile_name='dev')

Option B) Change the profile of the default session in code

    boto3.setup_default_session(profile_name='dev')

Option C) Change the profile of the default session with an environment variable

    $ AWS_PROFILE=dev ipython
    >>> import boto3
    >>> s3dev = boto3.resource('s3')

Loop through all the resources in a .resx file

Use ResXResourceReader Class

ResXResourceReader rsxr = new ResXResourceReader("your resource file path");

// Iterate through the resources and display the contents to the console.
foreach (DictionaryEntry d in rsxr)
{
    Console.WriteLine(d.Key.ToString() + ":\t" + d.Value.ToString());
}

How to implement "confirmation" dialog in Jquery UI dialog?

How about this:

$("ul li a").click(function() {

el = $(this);
$("#confirmDialog").dialog({ autoOpen: false, resizable:false,
                             draggable:true,
                             modal: true,
                             buttons: { "Ok": function() {
                                el.parent().remove();
                                $(this).dialog("close"); } }
                           });
$("#confirmDialog").dialog("open");

return false;
});

I have tested it at this html:

<ul>
<li><a href="#">Hi 1</a></li>
<li><a href="#">Hi 2</a></li>
<li><a href="#">Hi 3</a></li>
<li><a href="#">Hi 4</a></li>
</ul>

It removes the whole li element, you can adapt it at your needs.

form_for with nested resources

You don't need to do special things in the form. You just build the comment correctly in the show action:

class ArticlesController < ActionController::Base
  ....
  def show
    @article = Article.find(params[:id])
    @new_comment = @article.comments.build
  end
  ....
end

and then make a form for it in the article view:

<% form_for @new_comment do |f| %>
   <%= f.text_area :text %>
   <%= f.submit "Post Comment" %>
<% end %>

by default, this comment will go to the create action of CommentsController, which you will then probably want to put redirect :back into so you're routed back to the Article page.

How do you programmatically set an attribute?

setattr(x, attr, 'magic')

For help on it:

>>> help(setattr)
Help on built-in function setattr in module __builtin__:

setattr(...)
    setattr(object, name, value)

    Set a named attribute on an object; setattr(x, 'y', v) is equivalent to
    ``x.y = v''.

Edit: However, you should note (as pointed out in a comment) that you can't do that to a "pure" instance of object. But it is likely you have a simple subclass of object where it will work fine. I would strongly urge the O.P. to never make instances of object like that.

Can I pass an argument to a VBScript (vbs file launched with cscript)?

Each argument passed via command line can be accessed with: Wscript.Arguments.Item(0) Where the zero is the argument number: ie, 0, 1, 2, 3 etc.

So in your code you could have:

strFolder = Wscript.Arguments.Item(0) 

Set FSO = CreateObject("Scripting.FileSystemObject")
Set File = FSO.OpenTextFile(strFolder, 2, True)
File.Write "testing"
File.Close
Set File = Nothing
Set FSO = Nothing
Set workFolder = Nothing

Using wscript.arguments.count, you can error trap in case someone doesn't enter the proper value, etc.

MS Technet examples

How do I delete rows in a data frame?

The key idea is you form a set of the rows you want to remove, and keep the complement of that set.

In R, the complement of a set is given by the '-' operator.

So, assuming the data.frame is called myData:

myData[-c(2, 4, 6), ]   # notice the -

Of course, don't forget to "reassign" myData if you wanted to drop those rows entirely---otherwise, R just prints the results.

myData <- myData[-c(2, 4, 6), ]

Connecting to MySQL from Android with JDBC

try changing in the gradle file the targetSdkVersion to 8

targetSdkVersion 8

CSS selector (id contains part of text)

The only selector I see is a[id$="name"] (all links with id finishing by "name") but it's not as restrictive as it should.

How to compare numbers in bash?

There is also one nice thing some people might not know about:

echo $(( a < b ? a : b ))

This code will print the smallest number out of a and b

Delete all files in directory (but not directory) - one liner solution

For deleting all files from directory say "C:\Example"

File file = new File("C:\\Example");      
String[] myFiles;    
if (file.isDirectory()) {
    myFiles = file.list();
    for (int i = 0; i < myFiles.length; i++) {
        File myFile = new File(file, myFiles[i]); 
        myFile.delete();
    }
}

How do I manage MongoDB connections in a Node.js web application?

Manage mongo connection pools in a single self contained module. This approach provides two benefits. Firstly it keeps your code modular and easier to test. Secondly your not forced to mix your database connection up in your request object which is NOT the place for a database connection object. (Given the nature of JavaScript I would consider it highly dangerous to mix in anything to an object constructed by library code). So with that you only need to Consider a module that exports two methods. connect = () => Promise and get = () => dbConnectionObject.

With such a module you can firstly connect to the database

// runs in boot.js or what ever file your application starts with
const db = require('./myAwesomeDbModule');
db.connect()
    .then(() => console.log('database connected'))
    .then(() => bootMyApplication())
    .catch((e) => {
        console.error(e);
        // Always hard exit on a database connection error
        process.exit(1);
    });

When in flight your app can simply call get() when it needs a DB connection.

const db = require('./myAwesomeDbModule');
db.get().find(...)... // I have excluded code here to keep the example  simple

If you set up your db module in the same way as the following not only will you have a way to ensure that your application will not boot unless you have a database connection you also have a global way of accessing your database connection pool that will error if you have not got a connection.

// myAwesomeDbModule.js
let connection = null;

module.exports.connect = () => new Promise((resolve, reject) => {
    MongoClient.connect(url, option, function(err, db) {
        if (err) { reject(err); return; };
        resolve(db);
        connection = db;
    });
});

module.exports.get = () => {
    if(!connection) {
        throw new Error('Call connect first!');
    }

    return connection;
}

str.startswith with a list of strings to test for

You can also use any(), map() like so:

if any(map(l.startswith, x)):
    pass # Do something

Or alternatively, using a generator expression:

if any(l.startswith(s) for s in x)
    pass # Do something

Working with INTERVAL and CURDATE in MySQL

I usually use

DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)

Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...

How does one generate a random number in Apple's Swift language?

I use this code to generate a random number:

//
//  FactModel.swift
//  Collection
//
//  Created by Ahmadreza Shamimi on 6/11/16.
//  Copyright © 2016 Ahmadreza Shamimi. All rights reserved.
//

import GameKit

struct FactModel {

    let fun  = ["I love swift","My name is Ahmadreza","I love coding" ,"I love PHP","My name is ALireza","I love Coding too"]


    func getRandomNumber() -> String {

        let randomNumber  = GKRandomSource.sharedRandom().nextIntWithUpperBound(fun.count)

        return fun[randomNumber]
    }
}

Detect iPhone/iPad purely by css

I use these:

/* Non-Retina */
@media screen and (-webkit-max-device-pixel-ratio: 1) {
}

/* Retina */
@media only screen and (-webkit-min-device-pixel-ratio: 1.5),
only screen and (-o-min-device-pixel-ratio: 3/2),
only screen and (min--moz-device-pixel-ratio: 1.5),
only screen and (min-device-pixel-ratio: 1.5) {
}

/* iPhone Portrait */
@media screen and (max-device-width: 480px) and (orientation:portrait) {
} 

/* iPhone Landscape */
@media screen and (max-device-width: 480px) and (orientation:landscape) {
}

/* iPad Portrait */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:portrait) {
}

/* iPad Landscape */
@media screen and (min-device-width: 481px) and (max-device-width: 1024px) and (orientation:landscape) {
}

http://zsprawl.com/iOS/2012/03/css-for-iphone-ipad-and-retina-displays/

Can I edit an iPad's host file?

You need access to /private/etc/ so, no. you cant.

Which icon sizes should my Windows application's icon include?

From Microsoft MSDN recommendations:

Application icons and Control Panel items: The full set includes 16x16, 32x32, 48x48, and 256x256 (code scales between 32 and 256). The .ico file format is required. For Classic Mode, the full set is 16x16, 24x24, 32x32, 48x48 and 64x64.

So we have already standard recommended sizes of:

  • 16 x 16,
  • 24 x 24,
  • 32 x 32,
  • 48 x 48,
  • 64 x 64,
  • 256 x 256.

If we would like to support high DPI settings, the complete list will include the following sizes as well:

  • 20 x 20,
  • 30 x 30,
  • 36 x 36,
  • 40 x 40,
  • 60 x 60,
  • 72 x 72,
  • 80 x 80,
  • 96 x 96,
  • 128 x 128,
  • 320 x 320,
  • 384 x 384,
  • 512 x 512.

How to get the selected value from drop down list in jsp?

I've got one more additional option to get value by id:

var idElement = document.getElementById("idName");
var selectedValue = idElement.options[idElement.selectedIndex].value;

It's a simple JavaScript solution.

How can I copy network files using Robocopy?

I use the following format and works well.

robocopy \\SourceServer\Path \\TargetServer\Path filename.txt

to copy everything you can replace filename.txt with *.* and there are plenty of other switches to copy subfolders etc... see here: http://ss64.com/nt/robocopy.html

What difference between the DATE, TIME, DATETIME, and TIMESTAMP Types

I have a slightly different perspective on the difference between a DATETIME and a TIMESTAMP. A DATETIME stores a literal value of a date and time with no reference to any particular timezone. So, I can set a DATETIME column to a value such as '2019-01-16 12:15:00' to indicate precisely when my last birthday occurred. Was this Eastern Standard Time? Pacific Standard Time? Who knows? Where the current session time zone of the server comes into play occurs when you set a DATETIME column to some value such as NOW(). The value stored will be the current date and time using the current session time zone in effect. But once a DATETIME column has been set, it will display the same regardless of what the current session time zone is.

A TIMESTAMP column on the other hand takes the '2019-01-16 12:15:00' value you are setting into it and interprets it in the current session time zone to compute an internal representation relative to 1/1/1970 00:00:00 UTC. When the column is displayed, it will be converted back for display based on whatever the current session time zone is. It's a useful fiction to think of a TIMESTAMP as taking the value you are setting and converting it from the current session time zone to UTC for storing and then converting it back to the current session time zone for displaying.

If my server is in San Francisco but I am running an event in New York that starts on 9/1/1029 at 20:00, I would use a TIMESTAMP column for holding the start time, set the session time zone to 'America/New York' and set the start time to '2009-09-01 20:00:00'. If I want to know whether the event has occurred or not, regardless of the current session time zone setting I can compare the start time with NOW(). Of course, for displaying in a meaningful way to a perspective customer, I would need to set the correct session time zone. If I did not need to do time comparisons, then I would probably be better off just using a DATETIME column, which will display correctly (with an implied EST time zone) regardless of what the current session time zone is.

TIMESTAMP LIMITATION

The TIMESTAMP type has a range of '1970-01-01 00:00:01' UTC to '2038-01-19 03:14:07' UTC and so it may not usable for your particular application. In that case you will have to use a DATETIME type. You will, of course, always have to be concerned that the current session time zone is set properly whenever you are using this type with date functions such as NOW().

How can I convert an image into a Base64 string?

Use this code:

byte[] decodedString = Base64.decode(Base64String.getBytes(), Base64.DEFAULT);

Bitmap decodedByte = BitmapFactory.decodeByteArray(decodedString, 0, decodedString.length);

installing vmware tools: location of GCC binary?

sudo apt-get install build-essential is enough to get it working.

How to start a stopped Docker container with a different command?

This is not exactly what you're asking for, but you can use docker export on a stopped container if all you want is to inspect the files.

mkdir $TARGET_DIR
docker export $CONTAINER_ID | tar -x -C $TARGET_DIR

Make an image responsive - the simplest way

Instead of adding CSS to make the image responsive, adding different resolution images w.r.t. different screen resolution would make the application more efficient.

Mobile browsers don't need to have the same high resolution image that the desktop browsers need.

Using SASS it's easy to use different versions of the image for different resolutions using a media query.

Undefined reference to pow( ) in C, despite including math.h

You need to link with the math library:

gcc -o sphere sphere.c -lm

The error you are seeing: error: ld returned 1 exit status is from the linker ld (part of gcc that combines the object files) because it is unable to find where the function pow is defined.

Including math.h brings in the declaration of the various functions and not their definition. The def is present in the math library libm.a. You need to link your program with this library so that the calls to functions like pow() are resolved.

Using Powershell to stop a service remotely without WMI or remoting

The output of Get-Service is a System.ServiceProcess.ServiceController .NET class that can operate on remote computers. How it accomplishes that, I don't know - probably DCOM or WMI. Once you've gotten one of these from Get-Service, it can be passed into Stop-Service which most likely just calls the Stop() method on this object. That stops the service on the remote machine. In fact, you could probably do this as well:

(get-service -ComputerName remotePC -Name Spooler).Stop()

File opens instead of downloading in internet explorer in a href link

It should be fixed on server side. Your server should return this headers for this file types:

Content-Type: application/octet-stream
Content-Disposition: attachment;filename=\"filename.xxx\"

Override and reset CSS style: auto or none don't work

I ended up using Javascript to perfect everything.

My JS fiddle: https://jsfiddle.net/QEpJH/612/

HTML:

<div class="container">
    <img src="http://placekitten.com/240/300">
</div>

<h3 style="clear: both;">Full Size Image - For Reference</h3>
<img src="http://placekitten.com/240/300">

CSS:

.container {
    background-color:#000;
    width:100px;
    height:200px;

    display:flex;
    justify-content:center;
    align-items:center;
    overflow:hidden;

}

JS:

$(".container").each(function(){
    var divH = $(this).height()
    var divW = $(this).width()
    var imgH = $(this).children("img").height();
    var imgW = $(this).children("img").width();

    if ( (imgW/imgH) < (divW/divH)) { 
        $(this).addClass("1");
        var newW = $(this).width();
        var newH = (newW/imgW) * imgH;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    } else {
        $(this).addClass("2");
        var newH = $(this).height();
        var newW = (newH/imgH) * imgW;
        $(this).children("img").width(newW); 
        $(this).children("img").height(newH); 
    }
})

How to set True as default value for BooleanField on Django?

In DJango 3.0 the default value of a BooleanField in model.py is set like this:

class model_name(models.Model):
example_name = models.BooleanField(default=False)

How to fix PHP Warning: PHP Startup: Unable to load dynamic library 'ext\\php_curl.dll'?

As Darren commented, Apache don't understand php.ini relative paths in Windows.

To fix it, change the relative paths in your php.ini to absolute paths.

extension_dir="C:\full\path\to\php\ext\dir"

How can I find which tables reference a given table in Oracle SQL Developer?

How about something like this:

SELECT c.constraint_name, c.constraint_type, c2.constraint_name, c2.constraint_type, c2.table_name
  FROM dba_constraints c JOIN dba_constraints c2 ON (c.r_constraint_name = c2.constraint_name)
 WHERE c.table_name = <TABLE_OF_INTEREST>
   AND c.constraint_TYPE = 'R';

Android: converting String to int

You just need to write the line of code to convert your string to int.

 int convertedVal = Integer.parseInt(YOUR STR);

DataTrigger where value is NOT null?

This is a bit of a cheat but I just set a default style and then overrode it using a DataTrigger if the value is null...

  <Style> 
      <!-- Highlight for Reviewed (Default) -->
      <Setter Property="Control.Background" Value="PaleGreen" /> 
      <Style.Triggers>
        <!-- Highlight for Not Reviewed -->
        <DataTrigger Binding="{Binding Path=REVIEWEDBY}" Value="{x:Null}">
          <Setter Property="Control.Background" Value="LightIndianRed" />
        </DataTrigger>
      </Style.Triggers>
  </Style>

How do I fix certificate errors when running wget on an HTTPS URL in Cygwin?

If you are using windows just go to control panel, click on automatic updates then click on Windows Update Web Site link. Just follow the step. At least this works for me, no more certificates issue i.e whenever I go to https://www.dropbox.com as before.

Java NIO FileChannel versus FileOutputstream performance / usefulness

My experience with larger files sizes has been that java.nio is faster than java.io. Solidly faster. Like in the >250% range. That said, I am eliminating obvious bottlenecks, which I suggest your micro-benchmark might suffer from. Potential areas for investigating:

The buffer size. The algorithm you basically have is

  • copy from disk to buffer
  • copy from buffer to disk

My own experience has been that this buffer size is ripe for tuning. I've settled on 4KB for one part of my application, 256KB for another. I suspect your code is suffering with such a large buffer. Run some benchmarks with buffers of 1KB, 2KB, 4KB, 8KB, 16KB, 32KB and 64KB to prove it to yourself.

Don't perform java benchmarks that read and write to the same disk.

If you do, then you are really benchmarking the disk, and not Java. I would also suggest that if your CPU is not busy, then you are probably experiencing some other bottleneck.

Don't use a buffer if you don't need to.

Why copy to memory if your target is another disk or a NIC? With larger files, the latency incured is non-trivial.

Like other have said, use FileChannel.transferTo() or FileChannel.transferFrom(). The key advantage here is that the JVM uses the OS's access to DMA (Direct Memory Access), if present. (This is implementation dependent, but modern Sun and IBM versions on general purpose CPUs are good to go.) What happens is the data goes straight to/from disc, to the bus, and then to the destination... bypassing any circuit through RAM or the CPU.

The web app I spent my days and night working on is very IO heavy. I've done micro benchmarks and real-world benchmarks too. And the results are up on my blog, have a look-see:

Use production data and environments

Micro-benchmarks are prone to distortion. If you can, make the effort to gather data from exactly what you plan to do, with the load you expect, on the hardware you expect.

My benchmarks are solid and reliable because they took place on a production system, a beefy system, a system under load, gathered in logs. Not my notebook's 7200 RPM 2.5" SATA drive while I watched intensely as the JVM work my hard disc.

What are you running on? It matters.

Get screen width and height in Android

Try this code for Kotlin

 val display = windowManager.defaultDisplay
 val size = Point()
 display.getSize(size)
 var DEVICE_WIDTH = size.x
 var DEVICE_HEIGHT = size.y

Installation of SQL Server Business Intelligence Development Studio

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

Business Intelligence Development Studio is Microsoft Visual Studio 2008 with additional project types that are specific to SQL Server business intelligence. Business Intelligence Development Studio is the primary environment that you will use to develop business solutions that include Analysis Services, Integration Services, and Reporting Services projects. Each project type supplies templates for creating the objects required for business intelligence solutions, and provides a variety of designers, tools, and wizards to work with the objects.

If you already have Visual Studio installed, the new project types will be installed along with SQL Server.

More Information

How to convert XML to JSON in Python?

I wrote a small command-line based Python script based on pesterfesh that does exactly this:

https://github.com/hay/xml2json

Android list view inside a scroll view

best Code

 <android.support.v4.widget.NestedScrollView
    android:id="@+id/scrollView1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_above="@+id/btmlyt"
    android:layout_below="@+id/deshead_tv">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
       android:orientation="vertical"
       >

    <TextView
        android:id="@+id/des_tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_above="@+id/btmlyt"
        android:background="@android:color/white"
        android:paddingLeft="3dp"
        android:paddingRight="3dp"
        android:scrollbars="vertical"
        android:paddingTop="3dp"
        android:text="description"
        android:textColor="@android:color/black"
        android:textSize="18sp" />
    </LinearLayout>

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

Pointers in JavaScript?

I have found a slightly different way implement pointers that is perhaps more general and easier to understand from a C perspective (and thus fits more into the format of the users example).

In JavaScript, like in C, array variables are actually just pointers to the array, so you can use an array as exactly the same as declaring a pointer. This way, all pointers in your code can be used the same way, despite what you named the variable in the original object.

It also allows one to use two different notations referring to the address of the pointer and what is at the address of the pointer.

Here is an example (I use the underscore to denote a pointer):

var _x = [ 10 ];

function foo(_a){
    _a[0] += 10;
}

foo(_x);

console.log(_x[0]);

Yields

output: 20

Check if two lists are equal

Enumerable.SequenceEqual(FirstList.OrderBy(fElement => fElement), 
                         SecondList.OrderBy(sElement => sElement))

Sum of Numbers C++

int result = 0;


 for (int i=0; i < positiveInteger; i++)
    {
        result = startingNumber + 1;
        cout << result;
    }

Possible heap pollution via varargs parameter

It's rather safe to add @SafeVarargs annotation to the method when you can control the way it's called (e.g. a private method of a class). You must make sure that only the instances of the declared generic type are passed to the method.

If the method exposed externally as a library, it becomes hard to catch such mistakes. In this case it's best to avoid this annotation and rewrite the solution with a collection type (e.g. Collection<Type1<Type2>>) input instead of varargs (Type1<Type2>...).

As for the naming, the term heap pollution phenomenon is quite misleading in my opinion. In the documentation the actual JVM heap is not event mentioned. There is a question at Software Engineering that contains some interesting thoughts on the naming of this phenomenon.

Select folder dialog WPF

Based on Oyun's answer, it's better to use a dependency property for the FolderName. This allows (for example) binding to sub-properties, which doesn't work in the original. Also, in my adjusted version, the dialog shows selects the initial folder.

Usage in XAML:

<Button Content="...">
   <i:Interaction.Behaviors>
      <Behavior:FolderDialogBehavior FolderName="{Binding FolderPathPropertyName, Mode=TwoWay}"/>
    </i:Interaction.Behaviors>
</Button>

Code:

using System.Windows;
using System.Windows.Forms;
using System.Windows.Interactivity;
using Button = System.Windows.Controls.Button;

public class FolderDialogBehavior : Behavior<Button>
{
    #region Attached Behavior wiring
    protected override void OnAttached()
    {
        base.OnAttached();
        AssociatedObject.Click += OnClick;
    }

    protected override void OnDetaching()
    {
        AssociatedObject.Click -= OnClick;
        base.OnDetaching();
    }
    #endregion

    #region FolderName Dependency Property
    public static readonly DependencyProperty FolderName =
            DependencyProperty.RegisterAttached("FolderName",
            typeof(string), typeof(FolderDialogBehavior));

    public static string GetFolderName(DependencyObject obj)
    {
        return (string)obj.GetValue(FolderName);
    }

    public static void SetFolderName(DependencyObject obj, string value)
    {
        obj.SetValue(FolderName, value);
    }
    #endregion

    private void OnClick(object sender, RoutedEventArgs e)
    {
        var dialog = new FolderBrowserDialog();
        var currentPath = GetValue(FolderName) as string;
        dialog.SelectedPath = currentPath;
        var result = dialog.ShowDialog();
        if (result == DialogResult.OK)
        {
            SetValue(FolderName, dialog.SelectedPath);
        }
    }
}

Difference between r+ and w+ in fopen()

w+

#include <stdio.h>
int main()
{
   FILE *fp;
   fp = fopen("test.txt", "w+");  //write and read mode
   fprintf(fp, "This is testing for fprintf...\n"); 

   rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
   char ch;
   while((ch=getc(fp))!=EOF)
   putchar(ch);

   fclose(fp);
}  

output

This is testing for fprintf...

test.txt

This is testing for fprintf...

w and r to form w+

#include <stdio.h>
int main()
{
   FILE *fp;

   fp = fopen("test.txt", "w"); //only write mode
   fprintf(fp, "This is testing for fprintf...\n"); 
   fclose(fp);
   fp = fopen("test.txt", "r");
   char ch;
   while((ch=getc(fp))!=EOF)
   putchar(ch);
   fclose(fp);
}  

output

This is testing for fprintf...

test.txt

This is testing for fprintf...

r+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "r+");  //read and write mode
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf again...

r and w to form r+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "r"); 
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    fclose(fp);

    fp=fopen("test.txt","w");
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf again...

a+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "a+");  //append and read mode
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    rewind(fp); //rewind () function moves file pointer position to the beginning of the file.
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf...
This is testing for fprintf again...

a and r to form a+

test.txt

This is testing for fprintf...
#include<stdio.h>
int main()
{
    FILE *fp;
    fp = fopen("test.txt", "a");  //append and read mode
    char ch;
    while((ch=getc(fp))!=EOF)
    putchar(ch);
    fclose(fp);
    fp=fopen("test.txt","r");
    fprintf(fp, "This is testing for fprintf again...\n");
    fclose(fp);
    return 0;
}

output

This is testing for fprintf...

test.txt

This is testing for fprintf...
This is testing for fprintf again...

MySQL remove all whitespaces from the entire column

Using below query you can remove leading and trailing whitespace in a MySQL.

UPDATE `table_name`
SET `col_name` = TRIM(`col_name`);

adding child nodes in treeview

Example of adding child nodes:

private void AddExampleNodes()
        {
            TreeNode node;

            node = treeView1.Nodes.Add("Master node");
            node.Nodes.Add("Child node");
            node.Nodes.Add("Child node 2");

            node = treeView1.Nodes.Add("Master node 2");
            node.Nodes.Add("mychild");
            node.Nodes.Add("mychild");
        }

How to detect my browser version and operating system using JavaScript?

To get the new Microsoft Edge based on a Mozilla core add:

else if ((verOffset=nAgt.indexOf("Edg"))!=-1) {
 browserName = "Microsoft Edge";
 fullVersion = nAgt.substring(verOffset+5);
}

before

// In Chrome, the true version is after "Chrome" 
else if ((verOffset=nAgt.indexOf("Chrome"))!=-1) {
 browserName = "Chrome";
 fullVersion = nAgt.substring(verOffset+7);
}

What is the 'pythonic' equivalent to the 'fold' function from functional programming?

In Python 3, the reduce has been removed: Release notes. Nevertheless you can use the functools module

import operator, functools
def product(xs):
    return functools.reduce(operator.mul, xs, 1)

On the other hand, the documentation expresses preference towards for-loop instead of reduce, hence:

def product(xs):
    result = 1
    for i in xs:
        result *= i
    return result

Is it possible to use vh minus pixels in a CSS calc()?

It does work indeed. Issue was with my less compiler. It was compiled in to:

.container {
  min-height: calc(-51vh);
}

Fixed with the following code in less file:

.container {
  min-height: calc(~"100vh - 150px");
}

Thanks to this link: Less Aggressive Compilation with CSS3 calc

How to navigate a few folders up?

The following method searches a file beginning with the application startup path (*.exe folder). If the file is not found there, the parent folders are searched until either the file is found or the root folder has been reached. null is returned if the file was not found.

public static FileInfo FindApplicationFile(string fileName)
{
    string startPath = Path.Combine(Application.StartupPath, fileName);
    FileInfo file = new FileInfo(startPath);
    while (!file.Exists) {
        if (file.Directory.Parent == null) {
            return null;
        }
        DirectoryInfo parentDir = file.Directory.Parent;
        file = new FileInfo(Path.Combine(parentDir.FullName, file.Name));
    }
    return file;
}

Note: Application.StartupPath is usually used in WinForms applications, but it works in console applications as well; however, you will have to set a reference to the System.Windows.Forms assembly. You can replace Application.StartupPath by
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location) if you prefer.

How do I install and use curl on Windows?

As you already know, you can find several packages of binaries on the official curl website.

Once you download a package, unzip it wherever you want. I recommend adding its location to your path, so you can call curl from batch or powershell scripts. To add a directory to your path type "environment variables" in the start menu, and select "edit user environment variables". Select Path, and add to the end of the "value" box: ;C:\curl\directory (with the directory changed to where you saved curl.)

If you want to use SSL you need a certificate bundle. Run either mk-ca-bundle.pl (perl) or mk-ca-bundle.vbs (VBScript). Some of the packages of binaries include one or both of them. If your download doesn't include one, download one here: https://github.com/bagder/curl/tree/master/lib. I recommend mk-ca-bundle.vbs, as on windows you simply double click it to run it. It will produce a file called ca-bundle.crt. Rename it curl-ca-bundle.crt and save it in the directory with curl.exe.

Alternatively, I recently developed an msi installer that sets up a full featured build of curl with just a few clicks. It automatically ads curl to your path, includes a ready-to-use ssl certificate bundle, and makes the curl manual and documentation accessible from the start menu. You can download it at www.confusedbycode.com/curl/.

"installation of package 'FILE_PATH' had non-zero exit status" in R

Simple install following libs on your linux.
curl: sudo apt-get install curl
libssl-dev: sudo apt-get install libssl-dev
libcurl: sudo apt-get install libcurl4-openssl-dev
xml2: sudo apt-get install libxml2-dev

Tkinter module not found on Ubuntu

Adding the solution that I faced with python 3.4 on Fedora 21. Hope this will help those facing a similar issue.

Any of these commands will install tkinter:

sudo yum install python3-tkinter
OR
sudo dnf install python3-tkinter

How can I convert a cv::Mat to a gray scale in OpenCv?

Using the C++ API, the function name has slightly changed and it writes now:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, CV_BGR2GRAY);

The main difficulties are that the function is in the imgproc module (not in the core), and by default cv::Mat are in the Blue Green Red (BGR) order instead of the more common RGB.

OpenCV 3

Starting with OpenCV 3.0, there is yet another convention. Conversion codes are embedded in the namespace cv:: and are prefixed with COLOR. So, the example becomes then:

#include <opencv2/imgproc/imgproc.hpp>

cv::Mat greyMat, colorMat;
cv::cvtColor(colorMat, greyMat, cv::COLOR_BGR2GRAY);

As far as I have seen, the included file path hasn't changed (this is not a typo).

Zoom to fit: PDF Embedded in HTML

Bit late response to this question, however I do have something to add that might be useful for others.

If you make use of an iFrame and set the pdf file path to the src, it will load zoomed out to 100%, which the equivalence of FitH

Compiling php with curl, where is curl installed?

If you're going to compile a 64bit version(x86_64) of php use: /usr/lib64/

For architectures (i386 ... i686) use /usr/lib/

I recommend compiling php to the same architecture as apache. As you're using a 64bit linux i asume your apache is also compiled for x86_64.

Dependency Walker reports IESHIMS.DLL and WER.DLL missing?

1· Do I need these DLL's?

It depends since Dependency Walker is a little bit out of date and may report the wrong dependency.

  1. Where can I get them?

most dlls can be found at https://www.dll-files.com

I believe they are supposed to located in C:\Windows\System32\Wer.dll and C:\Program Files\Internet Explorer\Ieshims.dll

For me leshims.dll can be placed at C:\Windows\System32\. Context: windows 7 64bit.

How should I tackle --secure-file-priv in MySQL?

I had all sorts of problems with this. I was changing my.cnf and all sorts of crazy things that other versions of this problem tried to show.

What worked for me:

The error I was getting

The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I was able to fix it by opening /usr/local/mysql/support-files/mysql.server and changing the following line:

$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" -- $other_args >/dev/null &
  wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

to

$bindir/mysqld_safe --datadir="$datadir" --pid-file="$mysqld_pid_file_path" --secure-file-priv="" $other_args >/dev/null &
  wait_for_pid created "$!" "$mysqld_pid_file_path"; return_value=$?

How to remove all CSS classes using jQuery/JavaScript?

The shortest method

$('#item').removeAttr('class').attr('class', '');

Nested lists python

If you really need the indices you can just do what you said again for the inner list:

l = [[2,2,2],[3,3,3],[4,4,4]]
for index1 in xrange(len(l)):
    for index2 in xrange(len(l[index1])):
        print index1, index2, l[index1][index2]

But it is more pythonic to iterate through the list itself:

for inner_l in l:
    for item in inner_l:
        print item

If you really need the indices you can also use enumerate:

for index1, inner_l in enumerate(l):
    for index2, item in enumerate(inner_l):
        print index1, index2, item, l[index1][index2]

Chain-calling parent initialisers in python

Python 3 includes an improved super() which allows use like this:

super().__init__(args)

How do you select a particular option in a SELECT element in jQuery?

if you want to not use jQuery, you can use below code:

document.getElementById("mySelect").selectedIndex = "2";

Difference between subprocess.Popen and os.system

If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system() with subprocess.Popen():

sts = os.system("mycmd" + " myarg")

...does the same thing as...

sts = Popen("mycmd" + " myarg", shell=True).wait()

The "improved" code looks more complicated, but it's better because once you know subprocess.Popen(), you don't need anything else. subprocess.Popen() replaces several other tools (os.system() is just one of those) that were scattered throughout three other Python modules.

If it helps, think of subprocess.Popen() as a very flexible os.system().

Could not resolve placeholder in string value

With Spring Boot :

In the pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

How to split a string after specific character in SQL Server and update this value to specific column

I know this question is specific to sql server, but I'm using postgresql and came across this question, so for anybody else in a similar situation, there is the split_part(string text, delimiter text, field int) function.

Setting up enviromental variables in Windows 10 to use java and javac

Its still the same concept, you'll need to setup path variable so that windows is aware of the java executable and u can run it from command prompt conveniently

Details from the java's own page: https://java.com/en/download/help/path.xml That article applies to: •Platform(s): Solaris SPARC, Solaris x86, Red Hat Linux, SUSE Linux, Windows 8, Windows 7, Vista, Windows XP, Windows 10

Where to download visual studio express 2005?

As of late April 2009, Microsoft has discontinued all previous versions of Visual Studio Express, including 2005. It is no longer possible to obtain these previous versions from the Microsoft website.

From Here

Execute Immediate within a stored procedure keeps giving insufficient priviliges error

you could use "AUTHID CURRENT_USER" in body of your procedure definition for your requirements.

What's the best way to parse a JSON response from the requests library?

You can use json.loads:

import json
import requests

response = requests.get(...)
json_data = json.loads(response.text)

This converts a given string into a dictionary which allows you to access your JSON data easily within your code.

Or you can use @Martijn's helpful suggestion, and the higher voted answer, response.json().

Java: set timeout on a certain block of code?

Yes, but its generally a very bad idea to force another thread to interrupt on a random line of code. You would only do this if you intend to shutdown the process.

What you can do is to use Thread.interrupt() for a task after a certain amount of time. However, unless the code checks for this it won't work. An ExecutorService can make this easier with Future.cancel(true)

Its much better for the code to time itself and stop when it needs to.

How to list all the files in a commit?

Display the log.

COMMIT can be blank ("") or the sha-1 or the sha-1 shortened.

git log COMMIT -1 --name-only

This will list just the files, very useful for further processing.

git log COMMIT -1 --name-only --pretty=format:"" | grep "[^\s]"

Node.js quick file server (static files over HTTP)

Searching in NPM registry https://npmjs.org/search?q=server, I have found static-server https://github.com/maelstrom/static-server

Ever needed to send a colleague a file, but can't be bothered emailing the 100MB beast? Wanted to run a simple example JavaScript application, but had problems with running it through the file:/// protocol? Wanted to share your media directory at a LAN without setting up Samba, or FTP, or anything else requiring you to edit configuration files? Then this file server will make your life that little bit easier.

To install the simple static stuff server, use npm:

npm install -g static-server

Then to serve a file or a directory, simply run

$ serve path/to/stuff
Serving path/to/stuff on port 8001

That could even list folder content.

Unfortunately, it couldn't serve files :)

How to store phone numbers on MySQL databases?

I would definitely split them. It would be easy to sort the numbers by area code and contry code. But even if you're not going to split, just insert the numbers into the DB in one certain format. e.g. 1-555-555-1212 Your client side will be thankfull for not making it reformat your numbers.

Set the default value in dropdownlist using jQuery

You can just do this:

$('#myCombobox').val(1)

How to skip over an element in .map()?

You can do this

_x000D_
_x000D_
var sources = [];
images.map(function (img) {
    if(img.src.split('.').pop() !== "json"){ // if extension is not .json
        sources.push(img.src); // just push valid value
    }
});
_x000D_
_x000D_
_x000D_

How to run Java program in terminal with external library JAR

You can do :

1) javac -cp /path/to/jar/file Myprogram.java

2) java -cp .:/path/to/jar/file Myprogram

So, lets suppose your current working directory in terminal is src/Report/

javac -cp src/external/myfile.jar Reporter.java

java -cp .:src/external/myfile.jar Reporter

Take a look here to setup Classpath

How to set transparent background for Image Button in code?

This is the simple only you have to set background color as transparent

    ImageButton btn=(ImageButton)findViewById(R.id.ImageButton01);
    btn.setBackgroundColor(Color.TRANSPARENT);

What is a stack pointer used for in microprocessors?

For 8085: Stack pointer is a special purpose 16-bit register in the Microprocessor, which holds the address of the top of the stack.

The stack pointer register in a computer is made available for general purpose use by programs executing at lower privilege levels than interrupt handlers. A set of instructions in such programs, excluding stack operations, stores data other than the stack pointer, such as operands, and the like, in the stack pointer register. When switching execution to an interrupt handler on an interrupt, return address data for the currently executing program is pushed onto a stack at the interrupt handler's privilege level. Thus, storing other data in the stack pointer register does not result in stack corruption. Also, these instructions can store data in a scratch portion of a stack segment beyond the current stack pointer.

Read this one for more info.

General purpose use of a stack pointer register

Foreach in a Foreach in MVC View

Assuming your controller's action method is something like this:

public ActionResult AllCategories(int id = 0)
{
    return View(db.Categories.Include(p => p.Products).ToList());
}

Modify your models to be something like this:

public class Product
{
    [Key]
    public int ID { get; set; }
    public int CategoryID { get; set; }
    //new code
    public virtual Category Category { get; set; }
    public string Title { get; set; }
    public string Description { get; set; }
    public string Path { get; set; }

    //remove code below
    //public virtual ICollection<Category> Categories { get; set; }
}

public class Category
{
    [Key]
    public int CategoryID { get; set; }
    public string Name { get; set; }
    //new code
    public virtual ICollection<Product> Products{ get; set; }
}

Then your since now the controller takes in a Category as Model (instead of a Product):

foreach (var category in Model)
{
    <h3><u>@category.Name</u></h3>
    <div>
        <ul>    
            @foreach (var product in Model.Products)
            {
                // cut for brevity, need to add back more code from original
                <li>@product.Title</li>
            }
        </ul>
    </div>
}

UPDATED: Add ToList() to the controller return statement.

Hive insert query like SQL

You could definitely append data into an existing table. (But it is actually not an append at the HDFS level). It's just that whenever you do a LOAD or INSERT operation on an existing Hive table without OVERWRITE clause the new data will be put without replacing the old data. A new file will be created for this newly inserted data inside the directory corresponding to that table. For example :

I have a file named demo.txt which has 2 lines :

ABC
XYZ

Create a table and load this file into it

hive> create table demo(foo string);
hive> load data inpath '/demo.txt' into table demo;

Now,if I do a SELECT on this table it'll give me :

hive> select * from demo;                        
OK    
ABC    
XYZ

Suppose, I have one more file named demo2.txt which has :

PQR

And I do a LOAD again on this table without using overwrite,

hive> load data inpath '/demo2.txt' into table demo;

Now, if I do a SELECT now, it'll give me,

hive> select * from demo;                       
OK
ABC
XYZ
PQR

HTH

How do I filter date range in DataTables?

Here is my solution, cobbled together from the range filter example in the datatables docs, and letting moment.js do the dirty work of comparing the dates.

HTML

<input 
    type="text" 
    id="min-date"
    class="date-range-filter"
    placeholder="From: yyyy-mm-dd">

<input 
    type="text" 
    id="max-date" 
    class="date-range-filter"
    placeholder="To: yyyy-mm-dd">

<table id="my-table">
    <thead>
        <tr>
            <th>ID</th>
            <th>Name</th>
            <th>Created At</th>
        </tr>
    </thead>
</table>

JS

Install Moment: npm install moment

// Assign moment to global namespace
window.moment = require('moment');

// Set up your table
table = $('#my-table').DataTable({
    // ... do your thing here.
});

// Extend dataTables search
$.fn.dataTable.ext.search.push(
    function( settings, data, dataIndex ) {
        var min  = $('#min-date').val();
        var max  = $('#max-date').val();
        var createdAt = data[2] || 0; // Our date column in the table

        if  ( 
                ( min == "" || max == "" )
                || 
                ( moment(createdAt).isSameOrAfter(min) && moment(createdAt).isSameOrBefore(max) ) 
            )
        {
            return true;
        }
        return false;
    }
);

// Re-draw the table when the a date range filter changes
$('.date-range-filter').change( function() {
    table.draw();
} );

JSFiddle Here

Notes

  • Using moment decouples the date comparison logic, and makes it easy to work with different formats. In my table, I used yyyy-mm-dd, but you could use mm/dd/yyyy as well. Be sure to reference moment's docs when parsing other formats, as you may need to modify what method you use.

Determine distance from the top of a div to top of window with javascript

I used this function to detect if the element is visible in view port

Code:

const vh = Math.max(document.documentElement.clientHeight || 0, window.innerHeight || 0);
$(window).scroll(function(){
var scrollTop     = $(window).scrollTop(),
elementOffset = $('.for-scroll').offset().top,
distance      = (elementOffset - scrollTop);
if(distance < vh){
    console.log('in view');
}
else{
    console.log('not in view');
}
});

SQL Server Case Statement when IS NULL

You can use IIF (I think from SQL Server 2012)

SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]

How to hide Bootstrap previous modal when you opening new one?

You hide Bootstrap modals with:

$('#modal').modal('hide');

Saying $().hide() makes the matched element invisible, but as far as the modal-related code is concerned, it's still there. See the Methods section in the Modals documentation.

How do I convert two lists into a dictionary?

You may also try with one list which is a combination of two lists ;)

a = [1,2,3,4]
n = [5,6,7,8]

x = []
for i in a,n:
    x.append(i)

print(dict(zip(x[0], x[1])))

How can I set a custom date time format in Oracle SQL Developer?

You can change this in preferences:

  1. From Oracle SQL Developer's menu go to: Tools > Preferences.
  2. From the Preferences dialog, select Database > NLS from the left panel.
  3. From the list of NLS parameters, enter DD-MON-RR HH24:MI:SS into the Date Format field.
  4. Save and close the dialog, done!

Here is a screenshot:

Changing Date Format preferences in Oracle SQL Developer

GroupBy pandas DataFrame and select most common value

If you don't want to include NaN values, using Counter is much much faster than pd.Series.mode or pd.Series.value_counts()[0]:

def get_most_common(srs):
    x = list(srs)
    my_counter = Counter(x)
    return my_counter.most_common(1)[0][0]

df.groupby(col).agg(get_most_common)

should work. This will fail when you have NaN values, as each NaN will be counted separately.

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

Under Windows, you can use

C:>dir /b /s java.exe

to print the full path of each and every "java.exe" on your C: drive, regardless of whether they are on your PATH environment variable.

Mac OS X - EnvironmentError: mysql_config not found

If you have installed mysql using Homebrew by specifying a version then mysql_config would be present here. - /usr/local/Cellar/[email protected]/5.6.47/bin

you can find the path of the sql bin by using ls command in /usr/local/ directory

/usr/local/Cellar/[email protected]/5.6.47/bin

Add the path to bash profile like this.

nano ~/.bash_profile

export PATH="/usr/local/Cellar/[email protected]/5.6.47/bin:$PATH"

How to disable mouse scroll wheel scaling with Google Maps API

In my case the crucial thing was to set in 'scrollwheel':false in init. Notice: I am using jQuery UI Map. Below is my CoffeeScript init function heading:

 $("#map_canvas").gmap({'scrollwheel':false}).bind "init", (evt, map) ->

Batchfile to create backup and rename with timestamp

Yes, to make it run in the background create a shortcut to the batch file and go into the properties. I'm on a Linux machine ATM but I believe the option you are wanting is in the advanced tab.

You can also run your batch script through a vbs script like this:

'HideBat.vbs
CreateObject("Wscript.Shell").Run "your_batch_file.bat", 0, True

This will execute your batch file with no cmd window shown.

Preventing form resubmission

Try tris:

function prevent_multi_submit($excl = "validator") {
    $string = "";
    foreach ($_POST as $key => $val) {
    // this test is to exclude a single variable, f.e. a captcha value
    if ($key != $excl) {
        $string .= $key . $val;
    }
    }
    if (isset($_SESSION['last'])) {
    if ($_SESSION['last'] === md5($string)) {
        return false;
    } else {
        $_SESSION['last'] = md5($string);
        return true;
    }
    } else {
    $_SESSION['last'] = md5($string);
    return true;
    }
}

How to use / example:

if (isset($_POST)) {
    if ($_POST['field'] != "") { // place here the form validation and other controls
    if (prevent_multi_submit()) { // use the function before you call the database or etc
        mysql_query("INSERT INTO table..."); // or send a mail like...
        mail($mailto, $sub, $body); // etc
    } else {
        echo "The form is already processed";
    }
    } else {
    // your error about invalid fields
    }
}

Font: https://www.tutdepot.com/prevent-multiple-form-submission/

Retrieve the maximum length of a VARCHAR column in SQL Server

Many times you want to identify the row that has that column with the longest length, especially if you are troubleshooting to find out why the length of a column on a row in a table is so much longer than any other row, for instance. This query will give you the option to list an identifier on the row in order to identify which row it is.

select ID, [description], len([description]) as descriptionlength
FROM [database1].[dbo].[table1]
where len([description]) = 
 (select max(len([description]))
  FROM [database1].[dbo].[table1]

Is there a float input type in HTML5?

The number type has a step value controlling which numbers are valid (along with max and min), which defaults to 1. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step).

Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:

<input type="number" step="0.01">

(I'd also set min=0 if it can only be positive)

If you'd prefer to allow any number of decimal places, you can use step="any" (though for currencies, I'd recommend sticking to 0.01). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any. (thanks to Michal Stefanow's answer for pointing out any, and see the relevant spec here)

Here's a playground showing how various steps affect various input types:

_x000D_
_x000D_
<form>_x000D_
  <input type=number step=1 /> Step 1 (default)<br />_x000D_
  <input type=number step=0.01 /> Step 0.01<br />_x000D_
  <input type=number step=any /> Step any<br />_x000D_
  <input type=range step=20 /> Step 20<br />_x000D_
  <input type=datetime-local step=60 /> Step 60 (default)<br />_x000D_
  <input type=datetime-local step=1 /> Step 1<br />_x000D_
  <input type=datetime-local step=any /> Step any<br />_x000D_
  <input type=datetime-local step=0.001 /> Step 0.001<br />_x000D_
  <input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />_x000D_
  <input type=datetime-local step=86400 /> Step 86400 (1 day)<br />_x000D_
  <input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />_x000D_
</form>
_x000D_
_x000D_
_x000D_


As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!

How can I merge the columns from two tables into one output?

Specifying the columns on your query should do the trick:

select a.col1, b.col2, a.col3, b.col4, a.category_id 
from items_a a, items_b b 
where a.category_id = b.category_id

should do the trick with regards to picking the columns you want.

To get around the fact that some data is only in items_a and some data is only in items_b, you would be able to do:

select 
  coalesce(a.col1, b.col1) as col1, 
  coalesce(a.col2, b.col2) as col2,
  coalesce(a.col3, b.col3) as col3,
  a.category_id
from items_a a, items_b b
where a.category_id = b.category_id

The coalesce function will return the first non-null value, so for each row if col1 is non null, it'll use that, otherwise it'll get the value from col2, etc.

Difference between onStart() and onResume()

Hopefully a simple explanation : -

onStart() -> called when the activity becomes visible, but might not be in the foreground (e.g. an AlertFragment is on top or any other possible use case).

onResume() -> called when the activity is in the foreground, or the user can interact with the Activity.

How to modify WooCommerce cart, checkout pages (main theme portion)

I've found this works well as a conditional within page.php that includes the WooCommerce cart and checkout screens.

!is_page(array('cart', 'checkout'))

Google Chrome default opening position and size

Maybe a little late, but I found an easier way to set the defaults! You have to right-click on the right of your tab and choose "size", then click on your window, and it should keep it as the default size.

What does collation mean?

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

Collation is the assembly of written information into a standard order. (...) A collation algorithm such as the Unicode collation algorithm defines an order through the process of comparing two given character strings and deciding which should come before the other.

How do I open multiple instances of Visual Studio Code?

To open a new instance with your project loaded from terminal, just type code <directory-path>

Garbage collector in Android

Quick note for Xamarin developers.

If you would like to call System.gc() in Xamarin.Android apps you should call Java.Lang.JavaSystem.Gc()

Logging with Retrofit 2

this will create a retrofit object with Logging. without creating separate objects.

 private static final Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(BASE_URL)
            .client(new OkHttpClient().newBuilder()
                    .addInterceptor(new HttpLoggingInterceptor().setLevel(HttpLoggingInterceptor.Level.BODY))
                    .readTimeout(READ_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                    .writeTimeout(WRITE_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                    .connectTimeout(CONNECTION_TIMEOUT_SECONDS, TimeUnit.SECONDS)
                    .build())
            .addConverterFactory(GsonConverterFactory.create())
            .build();

Normalize numpy array columns in python

You can use sklearn.preprocessing:

from sklearn.preprocessing import normalize
data = np.array([
    [1000, 10, 0.5],
    [765, 5, 0.35],
    [800, 7, 0.09], ])
data = normalize(data, axis=0, norm='max')
print(data)
>>[[ 1.     1.     1.   ]
[ 0.765  0.5    0.7  ]
[ 0.8    0.7    0.18 ]]

Python Serial: How to use the read or readline function to read more than 1 character at a time

I use this small method to read Arduino serial monitor with Python

import serial
ser = serial.Serial("COM11", 9600)
while True:
     cc=str(ser.readline())
     print(cc[2:][:-5])

Calculate the number of business days between two dates?

I know this question is already solved, but I thought I could provide a more straightforward-looking answer that may help other visitors in the future.

Here's my take at it:

public int GetWorkingDays(DateTime from, DateTime to)
{
    var dayDifference = (int)to.Subtract(from).TotalDays;
    return Enumerable
        .Range(1, dayDifference)
        .Select(x => from.AddDays(x))
        .Count(x => x.DayOfWeek != DayOfWeek.Saturday && x.DayOfWeek != DayOfWeek.Sunday);
}

This was my original submission:

public int GetWorkingDays(DateTime from, DateTime to)
{
    var totalDays = 0;
    for (var date = from; date < to; date = date.AddDays(1))
    {
        if (date.DayOfWeek != DayOfWeek.Saturday
            && date.DayOfWeek != DayOfWeek.Sunday)
            totalDays++;
    }

    return totalDays;
}

Source file 'Properties\AssemblyInfo.cs' could not be found

This solved my problem. You should select Properties, Right-Click, Source Control and Get Specific Version.

How can I convert a .py to .exe for Python?

I can't tell you what's best, but a tool I have used with success in the past was cx_Freeze. They recently updated (on Jan. 7, '17) to version 5.0.1 and it supports Python 3.6.

Here's the pypi https://pypi.python.org/pypi/cx_Freeze

The documentation shows that there is more than one way to do it, depending on your needs. http://cx-freeze.readthedocs.io/en/latest/overview.html

I have not tried it out yet, so I'm going to point to a post where the simple way of doing it was discussed. Some things may or may not have changed though.

How do I use cx_freeze?

How to delete the last row of data of a pandas dataframe

To drop last n rows:

df.drop(df.tail(n).index,inplace=True) # drop last n rows

By the same vein, you can drop first n rows:

df.drop(df.head(n).index,inplace=True) # drop first n rows

OSError: [Errno 2] No such file or directory while using python subprocess in Django

Can't upvote so I'll repost @jfs comment cause I think it should be more visible.

@AnneTheAgile: shell=True is not required. Moreover you should not use it unless it is necessary (see @ valid's comment). You should pass each command-line argument as a separate list item instead e.g., use ['command', 'arg 1', 'arg 2'] instead of "command 'arg 1' 'arg 2'". – jfs Mar 3 '15 at 10:02

relative path in BAT script

either bin\Iris.exe (no leading slash - because that means start right from the root)
or \Program\bin\Iris.exe (full path)

MySQL show status - active or total connections?

In order to check the maximum allowed connections, you can run the following query:

SHOW VARIABLES LIKE "max_connections";

To check the number of active connections, you can run the following query:

SHOW VARIABLES LIKE "max_used_connections";

Hope it helps.

How to compute the sum and average of elements in an array?

One sneaky way you could do it although it does require the use of (the much hated) eval().

var sum = eval(elmt.join('+')), avg = sum / elmt.length;
document.write("The sum of all the elements is: " + sum + " The average of all the elements is: " + avg + "<br/>");

Just thought I'd post this as one of those 'outside the box' options. You never know, the slyness might grant you (or taketh away) a point.

Border Height on CSS

No, there isn't. The border will always be as tall as the element.

You can achieve the same effect by wrapping the contents of the cell in a <span>, and applying height/border styles to that. Or by drawing a short vertical line in an 1 pixel wide PNG which is the correct height, and applying it as a background to the cell:

background:url(line.png) bottom right no-repeat;

basic authorization command for curl

Background

You can use the base64 CLI tool to generate the base64 encoded version of your username + password like this:

$ echo -n "joeuser:secretpass" | base64
am9ldXNlcjpzZWNyZXRwYXNz

-or-

$ base64 <<<"joeuser:secretpass"
am9ldXNlcjpzZWNyZXRwYXNzCg==

Base64 is reversible so you can also decode it to confirm like this:

$ echo -n "joeuser:secretpass" | base64 | base64 -D
joeuser:secretpass

-or-

$ base64 <<<"joeuser:secretpass" | base64 -D
joeuser:secretpass

NOTE: username = joeuser, password = secretpass

Example #1 - using -H

You can put this together into curl like this:

$ curl -H "Authorization: Basic $(base64 <<<"joeuser:secretpass")" http://example.com

Example #2 - using -u

Most will likely agree that if you're going to bother doing this, then you might as well just use curl's -u option.

$ curl --help |grep -- "--user "
 -u, --user USER[:PASSWORD]  Server user and password

For example:

$ curl -u someuser:secretpass http://example.com

But you can do this in a semi-safer manner if you keep your credentials in a encrypted vault service such as LastPass or Pass.

For example, here I'm using the LastPass' CLI tool, lpass, to retrieve my credentials:

$ curl -u $(lpass show --username example.com):$(lpass show --password example.com) \
     http://example.com

Example #3 - using curl config

There's an even safer way to hand your credentials off to curl though. This method makes use of the -K switch.

$ curl -X GET -K \
    <(cat <<<"user = \"$(lpass show --username example.com):$(lpass show --password example.com)\"") \
    http://example.com

When used, your details remain hidden, since they're passed to curl via a temporary file descriptor, for example:

+ curl -skK /dev/fd/63 -XGET -H 'Content-Type: application/json' https://es-data-01a.example.com:9200/_cat/health
++ cat
+++ lpass show --username example.com
+++ lpass show --password example.com
1561075296 00:01:36 rdu-es-01 green 9 6 2171 1085 0 0 0 0 - 100.0%       

NOTE: Above I'm communicating with one of our Elasticsearch nodes, inquiring about the cluster's health.

This method is dynamically creating a file with the contents user = "<username>:<password>" and giving that to curl.

HTTP Basic Authorization

The methods shown above are facilitating a feature known as Basic Authorization that's part of the HTTP standard.

When the user agent wants to send authentication credentials to the server, it may use the Authorization field.

The Authorization field is constructed as follows:

  1. The username and password are combined with a single colon (:). This means that the username itself cannot contain a colon.
  2. The resulting string is encoded into an octet sequence. The character set to use for this encoding is by default unspecified, as long as it is compatible with US-ASCII, but the server may suggest use of UTF-8 by sending the charset parameter.
  3. The resulting string is encoded using a variant of Base64.
  4. The authorization method and a space (e.g. "Basic ") is then prepended to the encoded string.

For example, if the browser uses Aladdin as the username and OpenSesame as the password, then the field's value is the base64-encoding of Aladdin:OpenSesame, or QWxhZGRpbjpPcGVuU2VzYW1l. Then the Authorization header will appear as:

Authorization: Basic QWxhZGRpbjpPcGVuU2VzYW1l

Source: Basic access authentication

How do I clone a github project to run locally?

To clone a repository and place it in a specified directory use "git clone [url] [directory]". For example

git clone https://github.com/ryanb/railscasts-episodes.git Rails

will create a directory named "Rails" and place it in the new directory. Click here for more information.

Grep regex NOT containing string

(?<!1\.2\.3\.4).*Has exploded

You need to run this with -P to have negative lookbehind (Perl regular expression), so the command is:

grep -P '(?<!1\.2\.3\.4).*Has exploded' test.log

Try this. It uses negative lookbehind to ignore the line if it is preceeded by 1.2.3.4. Hope that helps!

Eclipse does not highlight matching variables

I just unchecked all, applied, checked all again, applied and it worked :) hopefully helps others.

How do I delete multiple rows in Entity Framework (without foreach)

using (var context = new DatabaseEntities())
{
    context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId);
}

How do I get the total Json record count using JQuery?

If you have something like this:

var json = [ {a:b, c:d}, {e:f, g:h, ...}, {..}, ... ]

then, you can do:

alert(json.length)

How to sort multidimensional array by column?

sorted(list, key=lambda x: x[1])

Note: this works on time variable too.

How to fix "set SameSite cookie to none" warning?

As the new feature comes, SameSite=None cookies must also be marked as Secure or they will be rejected.

One can find more information about the change on chromium updates and on this blog post

Note: not quite related directly to the question, but might be useful for others who landed here as it was my concern at first during development of my website:

if you are seeing the warning from question that lists some 3rd party sites (in my case it was google.com, huh) - that means they need to fix it and it's nothing to do with your site. Of course unless the warning mentions your site, in which case adding Secure should fix it.

How to uninstall a windows service and delete its files without rebooting

sc delete "service name"

will delete a service. I find that the sc utility is much easier to locate than digging around for installutil. Remember to stop the service if you have not already.

Convert double to Int, rounded down

double myDouble = 420.5;
//Type cast double to int
int i = (int)myDouble;
System.out.println(i);

The double value is 420.5 and the application prints out the integer value of 420

Fixed point vs Floating point number

A fixed point number has a specific number of bits (or digits) reserved for the integer part (the part to the left of the decimal point) and a specific number of bits reserved for the fractional part (the part to the right of the decimal point). No matter how large or small your number is, it will always use the same number of bits for each portion. For example, if your fixed point format was in decimal IIIII.FFFFF then the largest number you could represent would be 99999.99999 and the smallest non-zero number would be 00000.00001. Every bit of code that processes such numbers has to have built-in knowledge of where the decimal point is.

A floating point number does not reserve a specific number of bits for the integer part or the fractional part. Instead it reserves a certain number of bits for the number (called the mantissa or significand) and a certain number of bits to say where within that number the decimal place sits (called the exponent). So a floating point number that took up 10 digits with 2 digits reserved for the exponent might represent a largest value of 9.9999999e+50 and a smallest non-zero value of 0.0000001e-49.

Make div fill remaining space along the main axis in flexbox

Use the flex-grow property to make a flex item consume free space on the main axis.

This property will expand the item as much as possible, adjusting the length to dynamic environments, such as screen re-sizing or the addition / removal of other items.

A common example is flex-grow: 1 or, using the shorthand property, flex: 1.

Hence, instead of width: 96% on your div, use flex: 1.


You wrote:

So at the moment, it's set to 96% which looks OK until you really squash the screen - then the right hand div gets a bit starved of the space it needs.

The squashing of the fixed-width div is related to another flex property: flex-shrink

By default, flex items are set to flex-shrink: 1 which enables them to shrink in order to prevent overflow of the container.

To disable this feature use flex-shrink: 0.

For more details see The flex-shrink factor section in the answer here:


Learn more about flex alignment along the main axis here:

Learn more about flex alignment along the cross axis here:

Importing PNG files into Numpy?

This can also be done with the Image class of the PIL library:

from PIL import Image
import numpy as np

im_frame = Image.open(path_to_file + 'file.png')
np_frame = np.array(im_frame.getdata())

Note: The .getdata() might not be needed - np.array(im_frame) should also work

How to use ArrayList's get() method

You use List#get(int index) to get an object with the index index in the list. You use it like that:

List<ExampleClass> list = new ArrayList<ExampleClass>();
list.add(new ExampleClass());
list.add(new ExampleClass());
list.add(new ExampleClass());
ExampleClass exampleObj = list.get(2); // will get the 3rd element in the list (index 2);

Force index use in Oracle

There could be many reasons for Index not being used. Even after you specify hints, there are chances Oracle optimizer thinks otherwise and decide not to use Index. You need to go through the EXPLAIN PLAN part and see what is the cost of the statement with INDEX and without INDEX.

Assuming the Oracle uses CBO. Most often, if the optimizer thinks the cost is high with INDEX, even though you specify it in hints, the optimizer will ignore and continue for full table scan. Your first action should be checking DBA_INDEXES to know when the statistics are LAST_ANALYZED. If not analyzed, you can set table, index for analyze.

begin 
   DBMS_STATS.GATHER_INDEX_STATS ( OWNNAME=>user
                                 , INDNAME=>IndexName);
end;

For table.

begin 
   DBMS_STATS.GATHER_TABLE_STATS ( OWNNAME=>user
                                 , TABNAME=>TableName);
end;

In extreme cases, you can try setting up the statistics on your own.

python: create list of tuples from lists

You're after the zip function.

Taken directly from the question: How to merge lists into a list of tuples in Python?

>>> list_a = [1, 2, 3, 4]
>>> list_b = [5, 6, 7, 8]
>>> zip(list_a,list_b)
[(1, 5), (2, 6), (3, 7), (4, 8)]

MongoDB - admin user not authorized

It's a bit confusing - I believe you will need to grant yourself readWrite to query a database. A user with dbadmin or useradmin can admin the database (including granting yourself additional rights) but cannot perform queries or write data.

so grant yourself readWrite and you should be fine -

http://docs.mongodb.org/manual/reference/built-in-roles/#readWrite

ADB Driver and Windows 8.1

In Windows 7, 8 or 8.1, in Devices Manager:

  1. Select tree 'Android Device': remove 'Android Composite ADB Interface' [?]
  2. Press on main root of devices tree and call context menu (by right mouse click) and click on 'Update configuration'
  3. After updating your device should appear in 'Other devices'
  4. Select your device, call context menu from it and choose 'Update driver' and perform this updating

PHP-FPM doesn't write to error log

In my case php-fpm outputs 500 error without any logging because of missing php-mysql module. I moved joomla installation to another server and forgot about it. So apt-get install php-mysql and service restart solved it.

I started with trying to fix broken logging without success. Finally with strace i found fail message after db-related system calls. Though my case is not directly related to op's question, I hope it could be useful.

How can I get the root domain URI in ASP.NET?

Match match = Regex.Match(host, "([^.]+\\.[^.]{1,3}(\\.[^.]{1,3})?)$");
string domain = match.Groups[1].Success ? match.Groups[1].Value : null;

host.com => return host.com
s.host.com => return host.com

host.co.uk => return host.co.uk
www.host.co.uk => return host.co.uk
s1.www.host.co.uk => return host.co.uk

How do you change the text in the Titlebar in Windows Forms?

If you want to update it later, once "this" no longer references it, I had some luck with assigning a variable to point to the main form.

  static Form f0;
  public OrdUpdate()
  {
   InitializeComponent();
   f0=this;
  }
  // then later you can say
  f0.Text="New text";

Append values to query string

This is even more frustrating because now (.net 5) MS have marked many (all) of their methods that take a string instead of a Uri as obsolete.

Anyway, probably a better way to manipulate relative Uris is to give it what it wants:

var requestUri = new Uri("x://x").MakeRelativeUri(
   new UriBuilder("x://x") { Path = path, Query = query }.Uri);

You can use the other answers to actually build the query string.

How can I get double quotes into a string literal?

Thankfully, with C++11 there is also the more pleasing approach of using raw string literals.

printf("She said \"time flies like an arrow, but fruit flies like a banana\".");

Becomes:

printf(R"(She said "time flies like an arrow, but fruit flies like a banana".)");

With respect to the addition of brackets after the opening quote, and before the closing quote, note that they can be almost any combination of up to 16 characters, helping avoid the situation where the combination is present in the string itself. Specifically:

any member of the basic source character set except: space, the left parenthesis (, the right parenthesis ), the backslash , and the control characters representing horizontal tab, vertical tab, form feed, and newline" (N3936 §2.14.5 [lex.string] grammar) and "at most 16 characters" (§2.14.5/2)

How much clearer it makes this short strings might be debatable, but when used on longer formatted strings like HTML or JSON, it's unquestionably far clearer.

How do I convert 2018-04-10T04:00:00.000Z string to DateTime?

Using Date pattern yyyy-MM-dd'T'HH:mm:ss.SSS'Z' and Java 8 you could do

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'", Locale.ENGLISH);
LocalDate date = LocalDate.parse(string, formatter);
System.out.println(date);

Update: For pre 26 use Joda time

String string = "2018-04-10T04:00:00.000Z";
DateTimeFormatter formatter = DateTimeFormat.forPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'");
LocalDate date = org.joda.time.LocalDate.parse(string, formatter);

In app/build.gradle file, add like this-

dependencies {    
    compile 'joda-time:joda-time:2.9.4'
}

Why does JSHint throw a warning if I am using const?

If you're using VSCode:

1.

  • Go to preferences -> settings (cmd + ,)
  • Type jshint.options into the search bar
  • Hover over it and click on the pencil icon
  • Its now appended on the right side.
  • Add "esversion": 6 to the options object.

2.

Or simply add this to your user settings:

"jshint.options": {
    "esversion": 6
}

[UPDATE] new vscode settings

  • Go to preferences -> settings (cmd + ,)
  • type jshint into search

VSCode Settings

  • continue with step 2.

Converting to upper and lower case in Java

String a = "ABCD"

using this

a.toLowerCase();

all letters will convert to simple, "abcd"
using this

a.toUpperCase()

all letters will convert to Capital, "ABCD"

this conver first letter to capital:

a.substring(0,1).toUpperCase()

this conver other letter Simple

a.substring(1).toLowerCase();

we can get sum of these two

a.substring(0,1).toUpperCase() + a.substring(1).toLowerCase();

result = "Abcd"

Maximum request length exceeded.

I was tripped up by the fact that our web.config file has multiple system.web sections: it worked when I added < httpRuntime maxRequestLength="1048576" /> to the system.web section that at the configuration level.

Passing multiple variables in @RequestBody to a Spring MVC controller using Ajax

The easy solution is to create a payload class that has the str1 and the str2 as attributes:

@Getter
@Setter
public class ObjHolder{

String str1;
String str2;

}

And after you can pass

@RequestMapping(value = "/Test", method = RequestMethod.POST)
@ResponseBody
public boolean getTest(@RequestBody ObjHolder Str) {}

and the body of your request is:

{
    "str1": "test one",
    "str2": "two test"
}

Replace first occurrence of pattern in a string

There are a number of ways that you could do this, but the fastest might be to use IndexOf to find the index position of the letter you want to replace and then substring out the text before and after what you want to replace.

Updating the list view when the adapter data changes

I found a solution that is more efficient than currently accepted answer, because current answer forces all list elements to be refreshed. My solution will refresh only one element (that was touched) by calling adapters getView and recycling current view which adds even more efficiency.

mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
      // Edit object data that is represented in Viewat at list's "position"
      view = mAdapter.getView(position, view, parent);
    }
});

Python Progress Bar

A simple solution here !

void = '-'
fill = '#'
count = 100/length
increaseCount = 0
for i in range(length):
    print('['+(fill*i)+(void*(length-i))+'] '+str(int(increaseCount))+'%',end='\r')
    increaseCount += count
    time.sleep(0.1)
print('['+(fill*(i+1))+(void*(length-(i+1)))+'] '+str(int(increaseCount))+'%',end='\n')

Note : You can modify the fill and the "void" character if you want.

The loading bar (picture)

error: invalid initialization of non-const reference of type ‘int&’ from an rvalue of type ‘int’

C++03 3.10/1 says: "Every expression is either an lvalue or an rvalue." It's important to remember that lvalueness versus rvalueness is a property of expressions, not of objects.

Lvalues name objects that persist beyond a single expression. For example, obj , *ptr , ptr[index] , and ++x are all lvalues.

Rvalues are temporaries that evaporate at the end of the full-expression in which they live ("at the semicolon"). For example, 1729 , x + y , std::string("meow") , and x++ are all rvalues.

The address-of operator requires that its "operand shall be an lvalue". if we could take the address of one expression, the expression is an lvalue, otherwise it's an rvalue.

 &obj; //  valid
 &12;  //invalid

How to paste yanked text into the Vim command line

"I'd like to paste yanked text into Vim command line."

While the top voted answer is very complete, I prefer editing the command history.

In normal mode, type: q:. This will give you a list of recent commands, editable and searchable with normal vim commands. You'll start on a blank command line at the bottom.

For the exact thing that the article asks, pasting a yanked line (or yanked anything) into a command line, yank your text and then: q:p (get into command history edit mode, and then (p)ut your yanked text into a new command line. Edit at will, enter to execute.

To get out of command history mode, it's the opposite. In normal mode in command history, type: :q + enter

%matplotlib line magic causes SyntaxError in Python script

If you include the following code at the top of your script, matplotlib will run inline when in an IPython environment (like jupyter, hydrogen atom plugin...), and it will still work if you launch the script directly via command line (matplotlib won't run inline, and the charts will open in a pop-ups as usual).

from IPython import get_ipython
ipy = get_ipython()
if ipy is not None:
    ipy.run_line_magic('matplotlib', 'inline')