An easy way to do this is using the pandas
library like this.
import pandas as pd
fields = ['star_name', 'ra']
df = pd.read_csv('data.csv', skipinitialspace=True, usecols=fields)
# See the keys
print df.keys()
# See content in 'star_name'
print df.star_name
The problem here was the skipinitialspace
which remove the spaces in the header. So ' star_name' becomes 'star_name'
I had the same problem. My solution was to make all vectors numeric.
The way to determine the coordinates depends on what element you're working with. For circle
s for example, the cx
and cy
attributes determine the center position. In addition, you may have a translation
applied through the transform
attribute which changes the reference point of any coordinates.
Most of the ways used in general to get screen coordinates won't work for SVGs. In addition, you may not want absolute coordinates if the line you want to draw is in the same container as the elements it connects.
Edit:
In your particular code, it's quite difficult to get the position of the node because its determined by a translation of the parent element. So you need to get the transform attribute of the parent node and extract the translation from that.
d3.transform(d3.select(this.parentNode).attr("transform")).translate
Working jsfiddle here.
Try placing it on your body
body {
height: 100%;
background-image: url(../img/bg.svg);
background-size:100% 100%;
-o-background-size: 100% 100%;
-webkit-background-size: 100% 100%;
background-size:cover;
}
I wanted to have a div appear like a 3D sphere and transition through colors. I discovered that gradient background colors don't transition (yet). I placed a radial gradient background in front of the element (using z-index) with a transitioning solid background.
/* overlay */
z-index : 1;
background : radial-gradient( ellipse at 25% 25%, rgba( 255, 255, 255, 0 ) 0%, rgba( 0, 0, 0, 1 ) 100% );
then the div.ball
underneath:
transition : all 1s cubic-bezier(0.25, 0.46, 0.45, 0.94);
then changed the background color of the div.ball
and voila!
The goal is to make the <body> element take up the available height of the screen.
If you don't expect your content to take up more than the height of the screen, or you plan to make an inner scrollable element, set
body {
height: 100vh;
}
otherwise, you want <body> to become scrollable when there is more content than the screen can hold, so set
body {
min-height: 100vh;
}
this alone achieves the goal, albeit with a possible, and probably desirable, refinement.
Removing the margin of <body>.
body {
margin: 0;
}
there are two main reasons for doing so.
P.S. if you want the background to be a radial gradient with its center in the center of the screen and not in the bottom right corner as with your example, consider using something like
body {
min-height: 100vh;
margin: 0;
background: radial-gradient(circle, rgba(255,255,255,1) 0%, rgba(0,0,0,1) 100%);
}
_x000D_
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=">
<title>test</title>
</head>
<body>
</body>
</html>
_x000D_
Try this style instead, it modifies the template itself. In there you can change everything you need to transparent:
<Style TargetType="{x:Type TabItem}">
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type TabItem}">
<Grid>
<Border Name="Border" Margin="0,0,0,0" Background="Transparent"
BorderBrush="Black" BorderThickness="1,1,1,1" CornerRadius="5">
<ContentPresenter x:Name="ContentSite" VerticalAlignment="Center"
HorizontalAlignment="Center"
ContentSource="Header" Margin="12,2,12,2"
RecognizesAccessKey="True">
<ContentPresenter.LayoutTransform>
<RotateTransform Angle="270" />
</ContentPresenter.LayoutTransform>
</ContentPresenter>
</Border>
</Grid>
<ControlTemplate.Triggers>
<Trigger Property="IsSelected" Value="True">
<Setter Property="Panel.ZIndex" Value="100" />
<Setter TargetName="Border" Property="Background" Value="Red" />
<Setter TargetName="Border" Property="BorderThickness" Value="1,1,1,0" />
</Trigger>
<Trigger Property="IsEnabled" Value="False">
<Setter TargetName="Border" Property="Background" Value="DarkRed" />
<Setter TargetName="Border" Property="BorderBrush" Value="Black" />
<Setter Property="Foreground" Value="DarkGray" />
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
If you don't want scikit-learn to do the work for you...
import numpy
actual = numpy.array(actual)
predicted = numpy.array(predicted)
# calculate the confusion matrix; labels is numpy array of classification labels
cm = numpy.zeros((len(labels), len(labels)))
for a, p in zip(actual, predicted):
cm[a][p] += 1
# also get the accuracy easily with numpy
accuracy = (actual == predicted).sum() / float(len(actual))
Or take a look at a more complete implementation here in NLTK.
If you want to take n lines of input where each line contains m space separated integers like:
1 2 3
4 5 6
7 8 9
Then you can use:
a=[] // declaration
for i in range(0,n): //where n is the no. of lines you want
a.append([int(j) for j in input().split()]) // for taking m space separated integers as input
Then print whatever you want like for the above input:
print(a[1][1])
O/P would be 5 for 0 based indexing
Solution:
ul {
font-size: 0;
}
ul li {
font-size: 14px;
display: inline-block;
}
You must set parent font size to 0
I didn't think your question was very clear, but if all you need is a unique file name...
import uuid
unique_filename = str(uuid.uuid4())
You have to call close()
on the GZIPOutputStream
before you attempt to read it. The final bytes of the file will only be written when the file is actually closed. (This is irrespective of any explicit buffering in the output stack. The stream only knows to compress and write the last bytes when you tell it to close. A flush()
probably won't help ... though calling finish()
instead of close()
should work. Look at the javadocs.)
Here's the correct code (in Java);
package test;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
public class GZipTest {
public static void main(String[] args) throws
FileNotFoundException, IOException {
String name = "/tmp/test";
GZIPOutputStream gz = new GZIPOutputStream(new FileOutputStream(name));
gz.write(10);
gz.close(); // Remove this to reproduce the reported bug
System.out.println(new GZIPInputStream(new FileInputStream(name)).read());
}
}
(I've not implemented resource management or exception handling / reporting properly as they are not relevant to the purpose of this code. Don't treat this as an example of "good code".)
You can comment something out using ::
or REM
:
your commands here
:: commenttttttttttt
or
your commands here
REM commenttttttttttt
To do it on the same line as a command, you must add an ampersand:
your commands here & :: commenttttttttttt
or
your commands here & REM commenttttttttttt
::
in nested logic (IF-ELSE
, FOR
loops, etc...) will cause an error. In those cases, use REM
instead.I've improved Josh's answer. I've noticed that dig
only shows entries already present in the queried nameserver's cache, so it's better to pull an authoritative nameserver from the SOA (rather than rely on the default nameserver). I've also disabled the filtering of wildcard IPs because usually I'm usually more interested in the correctness of the setup.
The new script takes a -x
argument for expanded output and a -s NS
argument to choose a specific nameserver: dig -x example.com
#!/bin/bash
set -e; set -u
COMMON_SUBDOMAINS="www mail mx a.mx smtp pop imap blog en ftp ssh login"
EXTENDED=""
while :; do case "$1" in
--) shift; break ;;
-x) EXTENDED=y; shift ;;
-s) NS="$2"; shift 2 ;;
*) break ;;
esac; done
DOM="$1"; shift
TYPE="${1:-any}"
test "${NS:-}" || NS=$(dig +short SOA "$DOM" | awk '{print $1}')
test "$NS" && NS="@$NS"
if test "$EXTENDED"; then
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
wild_ips=$(dig +short "$NS" "*.$DOM" "$TYPE" | tr '\n' '|')
wild_ips="${wild_ips%|}"
for sub in $COMMON_SUBDOMAINS; do
dig +nocmd $NS "$sub.$DOM" +noall +answer "$TYPE"
done | cat #grep -vE "${wild_ips}"
dig +nocmd $NS "*.$DOM" +noall +answer "$TYPE"
else
dig +nocmd $NS "$DOM" +noall +answer "$TYPE"
fi
You can use a custom serializer at your money field. Here's an example with a MoneyBean. The field amount gets annotated with @JsonSerialize(using=...).
public class MoneyBean {
//...
@JsonProperty("amountOfMoney")
@JsonSerialize(using = MoneySerializer.class)
private BigDecimal amount;
//getters/setters...
}
public class MoneySerializer extends JsonSerializer<BigDecimal> {
@Override
public void serialize(BigDecimal value, JsonGenerator jgen, SerializerProvider provider) throws IOException,
JsonProcessingException {
// put your desired money style here
jgen.writeString(value.setScale(2, BigDecimal.ROUND_HALF_UP).toString());
}
}
That's it. A BigDecimal is now printed in the right way. I used a simple testcase to show it:
@Test
public void jsonSerializationTest() throws Exception {
MoneyBean m = new MoneyBean();
m.setAmount(new BigDecimal("20.3"));
ObjectMapper mapper = new ObjectMapper();
assertEquals("{\"amountOfMoney\":\"20.30\"}", mapper.writeValueAsString(m));
}
This full example includes passing data back to the Activity.
A layout with an EditText
is used for this simple example, but you can replace it with anything you like.
custom_layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:paddingLeft="20dp"
android:paddingRight="20dp"
android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:id="@+id/editText"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>
The key parts are
setView
to assign the custom layout to the AlertDialog.Builder
This is the full code from the example project shown in the image above:
MainActivity.java
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void showAlertDialogButtonClicked(View view) {
// create an alert builder
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Name");
// set the custom layout
final View customLayout = getLayoutInflater().inflate(R.layout.custom_layout, null);
builder.setView(customLayout);
// add a button
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// send data from the AlertDialog to the Activity
EditText editText = customLayout.findViewById(R.id.editText);
sendDialogDataToActivity(editText.getText().toString());
}
});
// create and show the alert dialog
AlertDialog dialog = builder.create();
dialog.show();
}
// do something with the data coming from the AlertDialog
private void sendDialogDataToActivity(String data) {
Toast.makeText(this, data, Toast.LENGTH_SHORT).show();
}
}
DialogFragment
subclass as is described in the documentation.If DFS finds an edge that points to an already-visited vertex, you have a cycle there.
I have been working with IBM DB2 database for more then decade and now trying to learn PostgreSQL.
It works on PostgreSQL 9.3.4, but does not work on DB2 10.5:
UPDATE B SET
COLUMN1 = A.COLUMN1,
COLUMN2 = A.COLUMN2,
COLUMN3 = A.COLUMN3
FROM A
WHERE A.ID = B.ID
Note: Main problem is FROM cause that is not supported in DB2 and also not in ANSI SQL.
It works on DB2 10.5, but does NOT work on PostgreSQL 9.3.4:
UPDATE B SET
(COLUMN1, COLUMN2, COLUMN3) =
(SELECT COLUMN1, COLUMN2, COLUMN3 FROM A WHERE ID = B.ID)
FINALLY! It works on both PostgreSQL 9.3.4 and DB2 10.5:
UPDATE B SET
COLUMN1 = (SELECT COLUMN1 FROM A WHERE ID = B.ID),
COLUMN2 = (SELECT COLUMN2 FROM A WHERE ID = B.ID),
COLUMN3 = (SELECT COLUMN3 FROM A WHERE ID = B.ID)
You could try to extract columns as list, massage this as you want, and reindex your dataframe:
>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...
>>> df.reindex(columns=['n']+df.columns[:-1].tolist())
n l v
0 0 a 1
1 0 b 2
2 0 c 1
3 0 d 2
WAR stands for Web application ARchive
JAR stands for Java ARchive
NOTE calling parent method via super will only work on parent class,
If your parent is interface, and wants to call the default methods then need to add interfaceName before super like IfscName.super.method();
interface Vehicle {
//Non abstract method
public default void printVehicleTypeName() { //default keyword can be used only in interface.
System.out.println("Vehicle");
}
}
class FordFigo extends FordImpl implements Vehicle, Ford {
@Override
public void printVehicleTypeName() {
System.out.println("Figo");
Vehicle.super.printVehicleTypeName();
}
}
Interface name is needed because same default methods can be available in multiple interface name that this class extends. So explicit call to a method is required.
You can use popular external library xmltodict, with unparse
and pretty=True
you will get best result:
xmltodict.unparse(
xmltodict.parse(my_xml), full_document=False, pretty=True)
full_document=False
against <?xml version="1.0" encoding="UTF-8"?>
at the top.
Harry Martyrossian mentions in a comment on his own answer that the
Get-ItemPropertyValue cmdlet was introduced in Powershell v5, which solves the problem:
PS> Get-ItemPropertyValue 'HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion' 'ProgramFilesDir'
C:\Program Files
Alternatives for PowerShell v4-:
Here's an attempt to retain the efficiency while eliminating the need for repetition of the value name, which, however, is still a little cumbersome:
& { (Get-ItemProperty `
-LiteralPath HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion `
-Name $args `
).$args } 'ProgramFilesDir'
By using a script block, the value name can be passed in once as a parameter, and the parameter variable ($args
) can then simply be used twice inside the block.
Alternatively, a simple helper function can ease the pain:
function Get-RegValue([String] $KeyPath, [String] $ValueName) {
(Get-ItemProperty -LiteralPath $KeyPath -Name $ValueName).$ValueName
}
Note: All solutions above bypass the problem described in Ian Kemp's's answer - the need to use explicit quoting for certain value names when used as property names; e.g., .'15.0'
- because the value names are passed as parameters and property access happens via a variable; e.g., .$ValueName
As for the other answers:
In case you have PyQt4 installed, try the following code:
from PyQt4 import QtGui
import sys
MyApp = QtGui.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
For PyQt5, the following will work:
from PyQt5 import QtWidgets
import sys
MyApp = QtWidgets.QApplication(sys.argv)
V = MyApp.desktop().screenGeometry()
h = V.height()
w = V.width()
print("The screen resolution (width X height) is the following:")
print(str(w) + "X" + str(h))
In Python 3.4 pathlib was introduced:
>>> from pathlib import Path
>>> p = Path('/etc/usr/lib')
>>> p
PosixPath('/etc/usr/lib')
>>> p.parent
PosixPath('/etc/usr')
It also comes with many other helpful features e.g. for joining paths using slashes or easily walking the directory tree.
For more information refer to the docs or this blog post, which covers the differences between os.path and pathlib.
IF you're only targeting modern browsers, AND you can have your border on a separate element from your content, then you can use the CSS scale transform to get a larger dot or dash:
border: 1px dashed black;
border-radius: 10px;
-webkit-transform: scale(8);
transform: scale(8);
It takes a lot of positional tweaking to get it to line up, but it works. By changing the thickness of the border, the starting size and the scale factor, you can get to just about thickness-length ratio you want. Only thing you can't touch is dash-to-gap ratio.
.box { _x000D_
width: 100%;_x000D_
background: #000;_x000D_
font-size: 48px;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.height {_x000D_
line-height: 170px;_x000D_
height: 170px;_x000D_
}_x000D_
_x000D_
.transform { _x000D_
height: 170px;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.transform p {_x000D_
margin: 0;_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
-ms-transform: translate(-50%, -50%);_x000D_
transform: translate(-50%, -50%);_x000D_
}
_x000D_
<h4>Using Height</h4>_x000D_
<div class="box height">_x000D_
Lorem ipsum dolor sit_x000D_
</div>_x000D_
_x000D_
<hr />_x000D_
_x000D_
<h4>Using Transform</h4>_x000D_
<div class="box transform">_x000D_
<p>Lorem ipsum dolor sit</p>_x000D_
</div>
_x000D_
This code is used for disable the right click events and keyboard short cuts.
Just try with this code
document.onkeydown = function(e) {_x000D_
if(e.keyCode == 123) {_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'I'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'J'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
if(e.ctrlKey && e.keyCode == 'U'.charCodeAt(0)){_x000D_
return false;_x000D_
}_x000D_
_x000D_
if(e.ctrlKey && e.shiftKey && e.keyCode == 'C'.charCodeAt(0)){_x000D_
return false;_x000D_
} _x000D_
}
_x000D_
Just in case...
If you are using SoapUI Mock Service (as the Server), calling it from a C# WCF:
WCF --> SoapUI MockService
And in this case you are getting the same error:
The content type text/html; charset=UTF-8 of the response message does not match the content type of the binding (text/xml; charset=utf-8).
Edit your Mock Response at SoapUI and add a Header to it:
In my scenario, this fix the problem.
You're missing *
s in the last two terms of your expression, so R is interpreting (e.g.) 0.207 (log(DIAM93))^2
as an attempt to call a function named 0.207
...
For example:
> 1 + 2*(3)
[1] 7
> 1 + 2 (3)
Error: attempt to apply non-function
Your (unreproducible) expression should read:
censusdata_20$AGB93 = WD * exp(-1.239 + 1.980 * log (DIAM93) +
0.207* (log(DIAM93))^2 -
0.0281*(log(DIAM93))^3)
Mathematica is the only computer system I know of that allows juxtaposition to be used for multiplication ...
After trying all the mentioned solutions I found the PlatformTarget
somehow added to AnyCPU
configuration in my project .csproj.
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
<DebugType>pdbonly</DebugType>
<Optimize>true</Optimize>
<OutputPath>bin\Release\</OutputPath>
<DefineConstants>TRACE</DefineConstants>
<ErrorReport>prompt</ErrorReport>
<WarningLevel>4</WarningLevel>
<PlatformTarget>x64</PlatformTarget>
</PropertyGroup>
Removing the line worked for me.
npx nodemon filename.js
This will work on macOS BigSur
As mentioned in Takahiko Kawasaki's answer, java represents Unicode strings in the form of modified UTF-8 and in JVM-Spec CONSTANT_UTF8_info Structure, 2 bytes are allocated to length (and not the no. of characters of String).
To extend the answer, the ASM jvm bytecode library's putUTF8
method, contains this:
public ByteVector putUTF8(final String stringValue) {
int charLength = stringValue.length();
if (charLength > 65535) {
// If no. of characters> 65535, than however UTF-8 encoded length, wont fit in 2 bytes.
throw new IllegalArgumentException("UTF8 string too large");
}
for (int i = 0; i < charLength; ++i) {
char charValue = stringValue.charAt(i);
if (charValue >= '\u0001' && charValue <= '\u007F') {
// Unicode code-point encoding in utf-8 fits in 1 byte.
currentData[currentLength++] = (byte) charValue;
} else {
// doesnt fit in 1 byte.
length = currentLength;
return encodeUtf8(stringValue, i, 65535);
}
}
...
}
But when code-point mapping > 1byte, it calls encodeUTF8
method:
final ByteVector encodeUtf8(final String stringValue, final int offset, final int maxByteLength /*= 65535 */) {
int charLength = stringValue.length();
int byteLength = offset;
for (int i = offset; i < charLength; ++i) {
char charValue = stringValue.charAt(i);
if (charValue >= 0x0001 && charValue <= 0x007F) {
byteLength++;
} else if (charValue <= 0x07FF) {
byteLength += 2;
} else {
byteLength += 3;
}
}
...
}
In this sense, the max string length is 65535 bytes, i.e the utf-8 encoding length. and not char
count
You can find the modified-Unicode code-point range of JVM, from the above utf8 struct link.
1) You cannot overload the method (Why doesn't ruby support method overloading?) so why not write a new method altogether?
2) I solved a similar problem using the splat operator * for an array of zero or more length. Then, if I want to pass a parameter(s) I can, it is interpreted as an array, but if I want to call the method without any parameter then I don't have to pass anything. See Ruby Programming Language pages 186/187
First, set customErrors = "Off" in the web.config and redeploy to get a more detailed error message that will help us diagnose the problem. You could also RDP into the instance and browse to the site from IIS locally to view the errors.
<system.web>
<customErrors mode="Off" />
First guess though - you have some references (most likely Azure SDK references) that are not set to Copy Local = true. So, all your dependencies are not getting deployed.
Get to the detailed error first and update your question.
UPDATE: A second option now available in VS2013 is Remote Debugging a Cloud Service or Virtual Machine.
I had the same problem. I wrote my own function using replace on innerHTML, but it would screw up anchor links and such.
To make it work correctly I used a library to get this done.
The library has an awesome API. After including the script I called it like this:
findAndReplaceDOMText(document.body, {
find: 'texttofind',
replace: 'texttoreplace'
}
);
This is from MSDN sample:
(*.bmp, *.jpg)|*.bmp;*.jpg
So for your case
openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"
Update join. One other important SQL-style join is an "update join" where columns in one table are updated (or created) using another table.
Modifying the OP's example tables...
sales = data.frame(
CustomerId = c(1, 1, 1, 3, 4, 6),
Year = 2000:2005,
Product = c(rep("Toaster", 3), rep("Radio", 3))
)
cust = data.frame(
CustomerId = c(1, 1, 4, 6),
Year = c(2001L, 2002L, 2002L, 2002L),
State = state.name[1:4]
)
sales
# CustomerId Year Product
# 1 2000 Toaster
# 1 2001 Toaster
# 1 2002 Toaster
# 3 2003 Radio
# 4 2004 Radio
# 6 2005 Radio
cust
# CustomerId Year State
# 1 2001 Alabama
# 1 2002 Alaska
# 4 2002 Arizona
# 6 2002 Arkansas
Suppose we want to add the customer's state from cust
to the purchases table, sales
, ignoring the year column. With base R, we can identify matching rows and then copy values over:
sales$State <- cust$State[ match(sales$CustomerId, cust$CustomerId) ]
# CustomerId Year Product State
# 1 2000 Toaster Alabama
# 1 2001 Toaster Alabama
# 1 2002 Toaster Alabama
# 3 2003 Radio <NA>
# 4 2004 Radio Arizona
# 6 2005 Radio Arkansas
# cleanup for the next example
sales$State <- NULL
As can be seen here, match
selects the first matching row from the customer table.
Update join with multiple columns. The approach above works well when we are joining on only a single column and are satisfied with the first match. Suppose we want the year of measurement in the customer table to match the year of sale.
As @bgoldst's answer mentions, match
with interaction
might be an option for this case. More straightforwardly, one could use data.table:
library(data.table)
setDT(sales); setDT(cust)
sales[, State := cust[sales, on=.(CustomerId, Year), x.State]]
# CustomerId Year Product State
# 1: 1 2000 Toaster <NA>
# 2: 1 2001 Toaster Alabama
# 3: 1 2002 Toaster Alaska
# 4: 3 2003 Radio <NA>
# 5: 4 2004 Radio <NA>
# 6: 6 2005 Radio <NA>
# cleanup for next example
sales[, State := NULL]
Rolling update join. Alternately, we may want to take the last state the customer was found in:
sales[, State := cust[sales, on=.(CustomerId, Year), roll=TRUE, x.State]]
# CustomerId Year Product State
# 1: 1 2000 Toaster <NA>
# 2: 1 2001 Toaster Alabama
# 3: 1 2002 Toaster Alaska
# 4: 3 2003 Radio <NA>
# 5: 4 2004 Radio Arizona
# 6: 6 2005 Radio Arkansas
The three examples above all focus on creating/adding a new column. See the related R FAQ for an example of updating/modifying an existing column.
The error message tells the exact reason: "abstract methods cannot have a body".
They can only be defined in abstract classes and interfaces (interface methods are implicitly abstract!) and the idea is, that the subclass implements the method.
Example:
public abstract class AbstractGreeter {
public abstract String getHelloMessage();
public void sayHello() {
System.out.println(getHelloMessage());
}
}
public class FrenchGreeter extends AbstractGreeter{
// we must implement the abstract method
@Override
public String getHelloMessage() {
return "bonjour";
}
}
Use splatting.
$CurlArgument = '-u', '[email protected]:yyyy',
'-X', 'POST',
'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
'--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument
For gcc 4.8.4
you need to use -std=c++1y
in later versions, looks like starting with 5.2
you can use -std=c++14
.
If we look at the gcc online documents we can find the manuals for each version of gcc and we can see by going to Dialect options for 4.9.3 under the GCC 4.9.3 manual it says:
‘c++1y’
The next revision of the ISO C++ standard, tentatively planned for 2014. Support is highly experimental, and will almost certainly change in incompatible ways in future releases.
So up till 4.9.3
you had to use -std=c++1y
while the gcc 5.2 options say:
‘c++14’ ‘c++1y’
The 2014 ISO C++ standard plus amendments. The name ‘c++1y’ is deprecated.
It is not clear to me why this is listed under Options Controlling C Dialect
but that is how the documents are currently organized.
Yes, that's it.
It's just the dot version when you want to access elements of a struct/class that is a pointer instead of a reference.
struct foo
{
int x;
float y;
};
struct foo var;
struct foo* pvar;
pvar = malloc(sizeof(pvar));
var.x = 5;
(&var)->y = 14.3;
pvar->y = 22.4;
(*pvar).x = 6;
That's it!
public ResponseEntity<?> ApiCall(@PathVariable(name = "id") long id) {
JSONObject resp = new JSONObject();
resp.put("status", 0);
resp.put("id", id);
return new ResponseEntity<String>(resp.toString(), HttpStatus.CREATED);
}
Improved Crop image functionality in PHP on the fly.
http://www.example.com/cropimage.php?filename=a.jpg&newxsize=100&newysize=200&constrain=1
Code in cropimage.php
$basefilename = @basename(urldecode($_REQUEST['filename']));
$path = 'images/';
$outPath = 'crop_images/';
$saveOutput = false; // true/false ("true" if you want to save images in out put folder)
$defaultImage = 'no_img.png'; // change it with your default image
$basefilename = $basefilename;
$w = $_REQUEST['newxsize'];
$h = $_REQUEST['newysize'];
if ($basefilename == "") {
$img = $path . $defaultImage;
$percent = 100;
} else {
$img = $path . $basefilename;
$len = strlen($img);
$ext = substr($img, $len - 3, $len);
$img2 = substr($img, 0, $len - 3) . strtoupper($ext);
if (!file_exists($img)) $img = $img2;
if (file_exists($img)) {
$percent = @$_GET['percent'];
$constrain = @$_GET['constrain'];
$w = $w;
$h = $h;
} else if (file_exists($path . $basefilename)) {
$img = $path . $basefilename;
$percent = $_GET['percent'];
$constrain = $_GET['constrain'];
$w = $w;
$h = $h;
} else {
$img = $path . 'no_img.png'; // change with your default image
$percent = @$_GET['percent'];
$constrain = @$_GET['constrain'];
$w = $w;
$h = $h;
}
}
// get image size of img
$x = @getimagesize($img);
// image width
$sw = $x[0];
// image height
$sh = $x[1];
if ($percent > 0) {
// calculate resized height and width if percent is defined
$percent = $percent * 0.01;
$w = $sw * $percent;
$h = $sh * $percent;
} else {
if (isset ($w) AND !isset ($h)) {
// autocompute height if only width is set
$h = (100 / ($sw / $w)) * .01;
$h = @round($sh * $h);
} elseif (isset ($h) AND !isset ($w)) {
// autocompute width if only height is set
$w = (100 / ($sh / $h)) * .01;
$w = @round($sw * $w);
} elseif (isset ($h) AND isset ($w) AND isset ($constrain)) {
// get the smaller resulting image dimension if both height
// and width are set and $constrain is also set
$hx = (100 / ($sw / $w)) * .01;
$hx = @round($sh * $hx);
$wx = (100 / ($sh / $h)) * .01;
$wx = @round($sw * $wx);
if ($hx < $h) {
$h = (100 / ($sw / $w)) * .01;
$h = @round($sh * $h);
} else {
$w = (100 / ($sh / $h)) * .01;
$w = @round($sw * $w);
}
}
}
$im = @ImageCreateFromJPEG($img) or // Read JPEG Image
$im = @ImageCreateFromPNG($img) or // or PNG Image
$im = @ImageCreateFromGIF($img) or // or GIF Image
$im = false; // If image is not JPEG, PNG, or GIF
if (!$im) {
// We get errors from PHP's ImageCreate functions...
// So let's echo back the contents of the actual image.
readfile($img);
} else {
// Create the resized image destination
$thumb = @ImageCreateTrueColor($w, $h);
// Copy from image source, resize it, and paste to image destination
@ImageCopyResampled($thumb, $im, 0, 0, 0, 0, $w, $h, $sw, $sh);
//Other format imagepng()
if ($saveOutput) { //Save image
$save = $outPath . $basefilename;
@ImageJPEG($thumb, $save);
} else { // Output resized image
header("Content-type: image/jpeg");
@ImageJPEG($thumb);
}
}
Before writing below queries first get into your cmd or PowerShell
TYPE:
mongo //To get into MongoDB shell
use <Your_dbName> //For Creating or making use of existing db
To List All Collection Names use any one from below options :-
show collections //output every collection
OR
show tables
OR
db.getCollectionNames() //shows all collections as a list
To show all collections content or data use below listed code which had been posted by Bruno_Ferreira.
var collections = db.getCollectionNames();
for(var i = 0; i< collections.length; i++) {
print('Collection: ' + collections[i]); // print the name of each collection
db.getCollection(collections[i]).find().forEach(printjson); //and then print the json of each of its elements
}
Only set the time in mills on Calendar object
Calendar c = Calendar.getInstance();
c.setTimeInMillis(1385355600000l);
System.out.println(c.get(Calendar.YEAR));
System.out.println(c.get(Calendar.MONTH));
System.out.println(c.get(Calendar.DAY_OF_MONTH));
// get Date
System.out.println(c.getTime());
Here is a solution that creates a section that is expandable using somewhat material design, bootstrap 4.5/5 alpha and entirely non-javascript.
Style for head section
<style>
[data-toggle="collapse"] .fa:before {
content: "\f077";
}
[data-toggle="collapse"].collapsed .fa:before {
content: "\f078";
}
</style>
Body html
<div class="pt-3 pb-3" style="border-top: 1px solid #eeeeee; border-bottom: 1px solid #eeeeee; cursor: pointer;">
<a href="#expandId" class="text-dark float-right collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">
<i class="fa" aria-hidden="false"></i>
</a>
<a href="#expandId" class="text-dark collapsed" data-toggle="collapse" role="button" aria-expanded="false" aria-controls="expandId">Expand Header</a>
<div class="collapse" id="expandId">
CONTENT GOES IN HERE
</div>
Use the observer pattern. It works like this:
interface MyListener{
void somethingHappened();
}
public class MyForm implements MyListener{
MyClass myClass;
public MyForm(){
this.myClass = new MyClass();
myClass.addListener(this);
}
public void somethingHappened(){
System.out.println("Called me!");
}
}
public class MyClass{
private List<MyListener> listeners = new ArrayList<MyListener>();
public void addListener(MyListener listener) {
listeners.add(listener);
}
void notifySomethingHappened(){
for(MyListener listener : listeners){
listener.somethingHappened();
}
}
}
You create an interface which has one or more methods to be called when some event happens. Then, any class which needs to be notified when events occur implements this interface.
This allows more flexibility, as the producer is only aware of the listener interface, not a particular implementation of the listener interface.
In my example:
MyClass
is the producer here as its notifying a list of listeners.
MyListener
is the interface.
MyForm
is interested in when somethingHappened
, so it is implementing MyListener
and registering itself with MyClass
. Now MyClass
can inform MyForm
about events without directly referencing MyForm
. This is the strength of the observer pattern, it reduces dependency and increases reusability.
There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT
does exist in PDW. In SQL Server you can use this query to create an empty table:
SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;
(If you want to make a copy of the table including all of the data, then leave out the WHERE
clause.)
Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.
The problem is caused by your #grid
having a width:1140px
.
You need to set a min-width:1140px
on the body
.
This will stop the body
from getting smaller than the #grid
. Remove width:100%
as block level elements take up the available width by default. Live example: http://jsfiddle.net/tw16/LX8R3/
html, body{
margin:0;
padding:0;
min-width: 1140px; /* this is the important part*/
}
#grid-container{
background:#f8f8f8 url(../images/grid-container-bg.gif) repeat-x top left;
}
#grid{
width:1140px;
margin:0px auto;
}
Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)
As shown earlier, flexbox is the easiest. eg.
#main{ display: flex; align-items:center;}
this will align all child elements to the center within the parent element.
Better one is here.
$('#submit').click(function()
{
if( !$('#myMessage').val() ) {
alert('warning');
}
});
And you don't necessarily need .length or see if its >0 since an empty string evaluates to false anyway but if you'd like to for readability purposes:
$('#submit').on('click',function()
{
if( $('#myMessage').val().length === 0 ) {
alert('warning');
}
});
If you're sure it will always operate on a textfield element then you can just use this.value.
$('#submit').click(function()
{
if( !document.getElementById('myMessage').value ) {
alert('warning');
}
});
Also you should take note that $('input:text') grabs multiple elements, specify a context or use the this keyword if you just want a reference to a lone element ( provided theres one textfield in the context's descendants/children ).
The most simple way is using the Android lib called Volley
Volley offers the following benefits:
Automatic scheduling of network requests. Multiple concurrent network connections. Transparent disk and memory response caching with standard HTTP cache coherence. Support for request prioritization. Cancellation request API. You can cancel a single request, or you can set blocks or scopes of requests to cancel. Ease of customization, for example, for retry and backoff. Strong ordering that makes it easy to correctly populate your UI with data fetched asynchronously from the network. Debugging and tracing tools.
You can send a http/https request as simple as this:
// Instantiate the RequestQueue.
RequestQueue queue = Volley.newRequestQueue(this);
String url ="http://www.yourapi.com";
JsonObjectRequest request = new JsonObjectRequest(url, null,
new Response.Listener<JSONObject>() {
@Override
public void onResponse(JSONObject response) {
if (null != response) {
try {
//handle your response
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
@Override
public void onErrorResponse(VolleyError error) {
}
});
queue.add(request);
In this case, you needn't consider "running in the background" or "using cache" yourself as all of these has already been done by Volley.
It is indeed possible.
Here is an example calling the Weather SOAP Service using plain requests lib:
import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
<SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
<SOAP-ENV:Header/>
<ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
</SOAP-ENV:Envelope>"""
response = requests.post(url,data=body,headers=headers)
print response.content
Some notes:
application/soap+xml
is probably the more correct header to use (but the weatherservice prefers text/xml
For example:
from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()
Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).
You can do the above with suds like so:
from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service
result = client.service.GetWeatherInformation()
print result
Note: when using suds, you will almost always end up needing to use the doctor!
Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:
sudo tcpdump -As 0
This can be helpful for inspecting the requests that actually go over the wire.
The above two code snippets are also available as gists:
This approach always works for me:
# First of all, delete all broken links. Replace my_project_name` to your virtual env name
find ~/.virtualenvs/my_project_name/ -type l -delete
# Then create new links to the current Python version
virtualenv ~/.virtualenvs/my_project_name/
# It's it. Just repeat for each virtualenv located in ~/.virtualenvs
Taken from:
Select * from
(
Select ROW_NUMBER() OVER ( order by Id) as 'Row_Number', *
from tbl_Contact_Us
) as tbl
Where tbl.Row_Number = 5
<html>
<head>
<script type="text/javascript" src="jquery.js"></script>
<script>
$(document).ready(function(){
var locations = ["http://webPage1.com", "http://webPage2.com"];
var len = locations.length;
var iframe = $('#frame');
var i = 0;
setInterval(function () {
iframe.attr('src', locations[++i % len]);
}, 30000);
});
</script>
</head>
<body>
<iframe id="frame"></iframe>
</body>
</html>
Gets the value of the current TimeSpan structure expressed in whole and fractional minutes.
You can change the index as explained already using set_index
.
You don't need to manually swap rows with columns, there is a transpose (data.T
) method in pandas that does it for you:
> df = pd.DataFrame([['ABBOTSFORD', 427000, 448000],
['ABERFELDIE', 534000, 600000]],
columns=['Locality', 2005, 2006])
> newdf = df.set_index('Locality').T
> newdf
Locality ABBOTSFORD ABERFELDIE
2005 427000 534000
2006 448000 600000
then you can fetch the dataframe column values and transform them to a list:
> newdf['ABBOTSFORD'].values.tolist()
[427000, 448000]
Projections and Selections are two unary operations in Relational Algebra and has practical applications in RDBMS (relational database management systems).
In practical sense, yes Projection means selecting specific columns (attributes) from a table and Selection means filtering rows (tuples). Also, for a conventional table, Projection and Selection can be termed as vertical and horizontal slicing or filtering.
Wikipedia provides more formal definitions of these with examples and they can be good for further reading on relational algebra:
You can create an interface
, pass it to AsyncTask
(in constructor), and then call method in onPostExecute()
For example:
Your interface:
public interface OnTaskCompleted{
void onTaskCompleted();
}
Your Activity:
public class YourActivity implements OnTaskCompleted{
// your Activity
}
And your AsyncTask:
public class YourTask extends AsyncTask<Object,Object,Object>{ //change Object to required type
private OnTaskCompleted listener;
public YourTask(OnTaskCompleted listener){
this.listener=listener;
}
// required methods
protected void onPostExecute(Object o){
// your stuff
listener.onTaskCompleted();
}
}
EDIT
Since this answer got quite popular, I want to add some things.
If you're a new to Android development, AsyncTask
is a fast way to make things work without blocking UI thread. It does solves some problems indeed, there is nothing wrong with how the class works itself. However, it brings some implications, such as:
Activity
, it will stay in memory even after user left the screen (or rotated the device).AsyncTask
is not delivering result to Activity
if Activity
was already destroyed. You have to add extra code to manage all this stuff or do you operations twice.Activity
When you feel that you matured enough to move on with Android, take a look at this article which, I think, is a better way to go for developing your Android apps with asynchronous operations.
If every input asks the same question, you should use a for
loop and an array of inputs:
Scanner dd = new Scanner(System.in);
int[] vars = new int[3];
for(int i = 0; i < vars.length; i++) {
System.out.println("Enter next var: ");
vars[i] = dd.nextInt();
}
Or as Chip suggested, you can parse the input from one line:
Scanner in = new Scanner(System.in);
int[] vars = new int[3];
System.out.println("Enter "+vars.length+" vars: ");
for(int i = 0; i < vars.length; i++)
vars[i] = in.nextInt();
You were on the right track, and what you did works. This is just a nicer and more flexible way of doing things.
There's already a lot of good answers here so why not one more, use a library like lodash or underscore :)
obj = {
1 : { name : 'bob' , dinner : 'pizza' },
2 : { name : 'john' , dinner : 'sushi' },
3 : { name : 'larry', dinner : 'hummus' }
}
_.where(obj, {dinner: 'pizza'})
>> [{"name":"bob","dinner":"pizza"}]
In my case, In a loop, I put res.render()
so might have been tried to call multiple times.
The final
keyword in java is used to restrict the user. The java final
keyword can be used in many context. Final can be:
The final
keyword can be applied with the variables, a final
variable that has no value, is called blank final
variable or uninitialized final
variable. It can be initialized in the constructor only. The blank final
variable can be static
also which will be initialized in the static
block only.
Java final variable:
If you make any variable as final
, you cannot change the value of final
variable(It will be constant).
Example of final
variable
There is a final variable speedlimit, we are going to change the value of this variable, but It can't be changed because final variable once assigned a value can never be changed.
class Bike9{
final int speedlimit=90;//final variable
void run(){
speedlimit=400; // this will make error
}
public static void main(String args[]){
Bike9 obj=new Bike9();
obj.run();
}
}//end of class
Java final class:
If you make any class as final
, you cannot extend it.
Example of final class
final class Bike{}
class Honda1 extends Bike{ //cannot inherit from final Bike,this will make error
void run(){
System.out.println("running safely with 100kmph");
}
public static void main(String args[]){
Honda1 honda= new Honda();
honda.run();
}
}
Java final method:
If you make any method as final, you cannot override it.
Example of final
method
(run() in Honda cannot override run() in Bike)
class Bike{
final void run(){System.out.println("running");}
}
class Honda extends Bike{
void run(){System.out.println("running safely with 100kmph");}
public static void main(String args[]){
Honda honda= new Honda();
honda.run();
}
}
shared from: http://www.javatpoint.com/final-keyword
For those of you who are using center points and half sizes for their rectangle data, instead of the typical x,y,w,h, or x0,y0,x1,x1, here's how you can do it:
#include <cmath> // for fabsf(float)
struct Rectangle
{
float centerX, centerY, halfWidth, halfHeight;
};
bool isRectangleOverlapping(const Rectangle &a, const Rectangle &b)
{
return (fabsf(a.centerX - b.centerX) <= (a.halfWidth + b.halfWidth)) &&
(fabsf(a.centerY - b.centerY) <= (a.halfHeight + b.halfHeight));
}
Use,
String s="0.01";
int i= new Double(s).intValue();
In pandas 16.2, I had to do pd.DataFrame.from_records(d)
to get this to work.
add []
in the name of the attributes in the input tag
<form action="" name="frm" method="post">
<input type="checkbox" name="hobby[]" value="coding"> coding  
<input type="checkbox" name="hobby[]" value="database"> database  
<input type="checkbox" name="hobby[]" value="software engineer"> soft Engineering <br>
<input type="submit" name="submit" value="submit">
</form>
for PHP Code :
<?php
if(isset($_POST['submit']){
$hobby = $_POST['hobby'];
foreach ($hobby as $hobys=>$value) {
echo "Hobby : ".$value."<br />";
}
}
?>
from sklearn import metrics
import numpy as np
import matplotlib.pyplot as plt
y_true = # true labels
y_probas = # predicted results
fpr, tpr, thresholds = metrics.roc_curve(y_true, y_probas, pos_label=0)
# Print ROC curve
plt.plot(fpr,tpr)
plt.show()
# Print AUC
auc = np.trapz(tpr,fpr)
print('AUC:', auc)
If you want to pass the type, than the equivalent in Java would be
java.lang.Class
If you want to use a weakly typed method, then you would simply use
java.lang.Object
and the corresponding operator
instanceof
e.g.
private void foo(Object o) {
if(o instanceof String) {
}
}//foo
However, in Java there are primitive types, which are not classes (i.e. int from your example), so you need to be careful.
The real question is what you actually want to achieve here, otherwise it is difficult to answer:
Or is there a better way?
You can add a new line character after the @ symbol like so:
string newString = oldString.Replace("@", "@\n");
You can also use the NewLine
property in the Environment
Class (I think it is Environment).
First Create Bitmap Image
Bitmap bmp = BitmapFactory.decodeResource(getResources(), R.drawable.image);
now set bitmap in Notification Builder Icon....
Notification.Builder.setLargeIcon(bmp);
Assuming the type is CV_8UC3 you would do this:
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
Vec3b bgrPixel = foo.at<Vec3b>(i, j);
// do something with BGR values...
}
}
Here is the documentation for Vec3b. Hope that helps! Also, don't forget OpenCV stores things internally as BGR not RGB.
EDIT :
For performance reasons, you may want to use direct access to the data buffer in order to process the pixel values:
Here is how you might go about this:
uint8_t* pixelPtr = (uint8_t*)foo.data;
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = pixelPtr[i*foo.cols*cn + j*cn + 0]; // B
bgrPixel.val[1] = pixelPtr[i*foo.cols*cn + j*cn + 1]; // G
bgrPixel.val[2] = pixelPtr[i*foo.cols*cn + j*cn + 2]; // R
// do something with BGR values...
}
}
Or alternatively:
int cn = foo.channels();
Scalar_<uint8_t> bgrPixel;
for(int i = 0; i < foo.rows; i++)
{
uint8_t* rowPtr = foo.row(i);
for(int j = 0; j < foo.cols; j++)
{
bgrPixel.val[0] = rowPtr[j*cn + 0]; // B
bgrPixel.val[1] = rowPtr[j*cn + 1]; // G
bgrPixel.val[2] = rowPtr[j*cn + 2]; // R
// do something with BGR values...
}
}
I had a similar problem. It turned out that I had an alias defined for python like so:
alias python=/usr/bin/python3
Apparently virtualenv does not check or update your aliases.
So the solution for me was to remove the alias:
unalias python
Now when I run python, I get the one from the virtual environment. Problem solved.
int days = 1;
var newDate = new Date(Date.now() + days*24*60*60*1000);
var days = 2;_x000D_
var newDate = new Date(Date.now()+days*24*60*60*1000);_x000D_
_x000D_
document.write('Today: <em>');_x000D_
document.write(new Date());_x000D_
document.write('</em><br/> New: <strong>');_x000D_
document.write(newDate);
_x000D_
SupressFinalize
tells the system that whatever work would have been done in the finalizer has already been done, so the finalizer doesn't need to be called. From the .NET docs:
Objects that implement the IDisposable interface can call this method from the IDisposable.Dispose method to prevent the garbage collector from calling Object.Finalize on an object that does not require it.
In general, most any Dispose()
method should be able to call GC.SupressFinalize()
, because it should clean up everything that would be cleaned up in the finalizer.
SupressFinalize
is just something that provides an optimization that allows the system to not bother queuing the object to the finalizer thread. A properly written Dispose()
/finalizer should work properly with or without a call to GC.SupressFinalize()
.
What you're doing is fine, but if you feel the need to 'Java-it-up' you could use a Transformer and the collect method from Apache Commons, e.g.:
public class IntegerToStringTransformer implements Transformer<Integer, String> {
public String transform(final Integer i) {
return (i == null ? null : i.toString());
}
}
..and then..
CollectionUtils.collect(
collectionOfIntegers,
new IntegerToStringTransformer(),
newCollectionOfStrings);
This can be achieved by assigning the header view manually in the UITableViewController's viewDidLoad method instead of using the delegate's viewForHeaderInSection and heightForHeaderInSection. For example in your subclass of UITableViewController, you can do something like this:
- (void)viewDidLoad {
[super viewDidLoad];
UILabel *headerView = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 0, 40)];
[headerView setBackgroundColor:[UIColor magentaColor]];
[headerView setTextAlignment:NSTextAlignmentCenter];
[headerView setText:@"Hello World"];
[[self tableView] setTableHeaderView:headerView];
}
The header view will then disappear when the user scrolls. I don't know why this works like this, but it seems to achieve what you're looking to do.
I extended Ronnie's answer with a fluent implementation so you can use it like so:
dm.Context.SetCommandTimeout(120).Database.SqlQuery...
public static class EF
{
public static DbContext SetCommandTimeout(this DbContext db, TimeSpan? timeout)
{
((IObjectContextAdapter)db).ObjectContext.CommandTimeout = timeout.HasValue ? (int?) timeout.Value.TotalSeconds : null;
return db;
}
public static DbContext SetCommandTimeout(this DbContext db, int seconds)
{
return db.SetCommandTimeout(TimeSpan.FromSeconds(seconds));
}
}
Because the view must return render
, not just call it. Change the last line to
return render(request, 'auth_lifecycle/user_profile.html',
context_instance=RequestContext(request))
Found out that there's no bug there. Just add:
<base href="/" />
to your <head />
.
Adding some understanding.
By Euclidean definition the mod result must be always positive.
Ex:
int n = 5;
int x = -3;
int mod(int n, int x)
{
return ((n%x)+x)%x;
}
Output:
-1
You need to put the font files in assets folder (may be a fonts sub-folder within assets) and refer to it in the styles:
@font-face {
font-family: lato;
src: url(assets/font/Lato.otf) format("opentype");
}
Once done, you can apply this font any where like:
* {
box-sizing: border-box;
margin: 0;
padding: 0;
font-family: 'lato', 'arial', sans-serif;
}
You can put the @font-face
definition in your global styles.css
or styles.scss
and you would be able to refer to the font anywhere - even in your component specific CSS/SCSS. styles.css
or styles.scss
is already defined in angular-cli.json
. Or, if you want you can create a separate CSS/SCSS file and declare it in angular-cli.json along with the styles.css
or styles.scss
like:
"styles": [
"styles.css",
"fonts.css"
],
After looking at all the suggestions here, I've discovered a few things which I hope will be useful to others in my position:
hop is right to point me back
at /etc/init.d/functions
: the
daemon
function already allows you
to set an alternate user:
daemon --user=my_user my_cmd &>/dev/null &
This is implemented by wrapping the
process invocation with runuser
-
more on this later.
Jonathan Leffler is right: there is setuid in Python:
import os
os.setuid(501) # UID of my_user is 501
I still don't think you can setuid from inside a JVM, however.
Neither su
nor runuser
gracefully handle the case where you
ask to run a command as the user you
already are. E.g.:
[my_user@my_host]$ id
uid=500(my_user) gid=500(my_user) groups=500(my_user)
[my_user@my_host]$ su my_user -c "id"
Password: # don't want to be prompted!
uid=500(my_user) gid=500(my_user) groups=500(my_user)
To workaround that behaviour of su
and runuser
, I've changed my init script to something like:
if [[ "$USER" == "my_user" ]]
then
daemon my_cmd &>/dev/null &
else
daemon --user=my_user my_cmd &>/dev/null &
fi
Thanks all for your help!
you're comparing the result against a string ('false') not the built-in negative constant (false)
just use
if(ValidateForm() == false) {
or better yet
if(!ValidateForm()) {
also why are you calling validateForm twice?
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
You can use the date()
function which will extract the date from a datetime and give you the result as inclusive date:
SELECT * FROM Cases WHERE date(created_at)='2013-05-01' AND '2013-05-01'
I prefer null
, since it's compatible with the null-coalescing operator (??
).
You need to check if is a string to avoid getting a child element
var getIdFromDomObj = function(domObj){
var id = domObj.id;
return typeof id === 'string' ? id : false;
};
There is a workaround for the usual problem of spaces and newlines:
Use a character that is not in the original array (like $'\1'
or $'\4'
or similar).
This function gets the job done:
# Sort an Array may have spaces or newlines with a workaround (wa=$'\4')
sortarray(){ local wa=$'\4' IFS=''
if [[ $* =~ [$wa] ]]; then
echo "$0: error: array contains the workaround char" >&2
exit 1
fi
set -f; local IFS=$'\n' x nl=$'\n'
set -- $(printf '%s\n' "${@//$nl/$wa}" | sort -n)
for x
do sorted+=("${x//$wa/$nl}")
done
}
This will sort the array:
$ array=( a b 'c d' $'e\nf' $'g\1h')
$ sortarray "${array[@]}"
$ printf '<%s>\n' "${sorted[@]}"
<a>
<b>
<c d>
<e
f>
<gh>
This will complain that the source array contains the workaround character:
$ array=( a b 'c d' $'e\nf' $'g\4h')
$ sortarray "${array[@]}"
./script: error: array contains the workaround char
wa
(workaround char) and a null IFS$*
.[[ $* =~ [$wa] ]]
.exit 1
set -f
IFS=$'\n'
) a loop variable x
and a newline var (nl=$'\n'
).$@
)."${@//$nl/$wa}"
.sort -n
.set --
.for x
sorted+=(…)
"${x//$wa/$nl}"
.You can do that using count
:
my_dict = {i:MyList.count(i) for i in MyList}
>>> print my_dict #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
Or using collections.Counter
:
from collections import Counter
a = dict(Counter(MyList))
>>> print a #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}
I use the following code with a form that has 2 buttons, one for exit and the other to start. A folder browser dialog and a save file dialog. Code is listed below and works on my system Windows10 (64):
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace Directory_List
{
public partial class Form1 : Form
{
public string MyPath = "";
public string MyFileName = "";
public string str = "";
public Form1()
{
InitializeComponent();
}
private void cmdQuit_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void cmdGetDirectory_Click(object sender, EventArgs e)
{
folderBrowserDialog1.ShowDialog();
MyPath = folderBrowserDialog1.SelectedPath;
saveFileDialog1.ShowDialog();
MyFileName = saveFileDialog1.FileName;
str = "Folder = " + MyPath + "\r\n\r\n\r\n";
DirectorySearch(MyPath);
var result = MessageBox.Show("Directory saved to Disk!", "", MessageBoxButtons.OK);
Application.Exit();
}
public void DirectorySearch(string dir)
{
try
{
foreach (string f in Directory.GetFiles(dir))
{
str = str + dir + "\\" + (Path.GetFileName(f)) + "\r\n";
}
foreach (string d in Directory.GetDirectories(dir, "*"))
{
DirectorySearch(d);
}
System.IO.File.WriteAllText(MyFileName, str);
}
catch (System.Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}
}
I tried this tool and it gave me good results.
You can create a big subplot that covers the two subplots and then set the common labels.
import random
import matplotlib.pyplot as plt
x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]
fig = plt.figure()
ax = fig.add_subplot(111) # The big subplot
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
# Turn off axis lines and ticks of the big subplot
ax.spines['top'].set_color('none')
ax.spines['bottom'].set_color('none')
ax.spines['left'].set_color('none')
ax.spines['right'].set_color('none')
ax.tick_params(labelcolor='w', top=False, bottom=False, left=False, right=False)
ax1.loglog(x, y1)
ax2.loglog(x, y2)
# Set common labels
ax.set_xlabel('common xlabel')
ax.set_ylabel('common ylabel')
ax1.set_title('ax1 title')
ax2.set_title('ax2 title')
plt.savefig('common_labels.png', dpi=300)
Another way is using fig.text() to set the locations of the common labels directly.
import random
import matplotlib.pyplot as plt
x = range(1, 101)
y1 = [random.randint(1, 100) for _ in range(len(x))]
y2 = [random.randint(1, 100) for _ in range(len(x))]
fig = plt.figure()
ax1 = fig.add_subplot(211)
ax2 = fig.add_subplot(212)
ax1.loglog(x, y1)
ax2.loglog(x, y2)
# Set common labels
fig.text(0.5, 0.04, 'common xlabel', ha='center', va='center')
fig.text(0.06, 0.5, 'common ylabel', ha='center', va='center', rotation='vertical')
ax1.set_title('ax1 title')
ax2.set_title('ax2 title')
plt.savefig('common_labels_text.png', dpi=300)
sudo phpenmod mysqli
sudo service apache2 restart
phpenmod moduleName
enables a module to PHP 7 (restart Apache after that sudo service apache2 restart
)phpdismod moduleName
disables a module to PHP 7 (restart Apache after that sudo service apache2 restart
)php -m
lists the loaded modulesSome great worksheet-fu in the other answers but I think they've overlooked that you can define a user-defined function (udf) and call this from the sheet or a formula.
The next problem you have is to decide either to work with a whole array or with element.
For example this UDF function code
Public Function UdfSplit(ByVal sText As String, Optional ByVal sDelimiter As String = " ", Optional ByVal lIndex As Long = -1) As Variant
Dim vSplit As Variant
vSplit = VBA.Split(sText, sDelimiter)
If lIndex > -1 Then
UdfSplit = vSplit(lIndex)
Else
UdfSplit = vSplit
End If
End Function
allows single elements with the following in one cell
=UdfSplit("EUR/USD","/",0)
or one can use a blocks of cells with
=UdfSplit("EUR/USD","/")
Have you looked into using a HorizontalScrollView to wrap your list items? That will allow each of your list items to be horizontally scrollable (what you put in there is up to you, and can make them dynamic items similar to ListView). This will work well if you are only after a single row of items.
Follow these steps:
If you don't have the source folder added do the following
Now you can have fun and run the application.
You can also do this using DOM Level 2 CSS interfaces (MDN):
var sheet = window.document.styleSheets[0];
sheet.insertRule('strong { color: red; }', sheet.cssRules.length);
...on all but (naturally) IE8 and prior, which uses its own marginally-different wording:
sheet.addRule('strong', 'color: red;', -1);
There is a theoretical advantage in this compared to the createElement-set-innerHTML method, in that you don't have to worry about putting special HTML characters in the innerHTML, but in practice style elements are CDATA in legacy HTML, and ‘<’ and ‘&’ are rarely used in stylesheets anyway.
You do need a stylesheet in place before you can started appending to it like this. That can be any existing active stylesheet: external, embedded or empty, it doesn't matter. If there isn't one, the only standard way to create it at the moment is with createElement.
tblless
in the Tabulator package wraps the unix column
command, and also aligns numeric columns.
I had a similar problem; the anchor text in my Bootstrap4 navbar wasn't centered. Simply added text-center
in the anchor's class.
Given that you are in AWS...I would think you would want to use their CloudSearch tools. Put the data you want to search in their service...have it point to the S3 keys.
Based on generality of this question, I think, that you'll need to setup your own HTTPS proxy on some server online. Do the following steps:
If you simply download remote site content via file_get_contents or similiar, you can still have insecure links to content. You'll have to find them with regex and also replace. Images are hard to solve, but Ï found workaround here: http://foundationphp.com/tutorials/image_proxy.php
Note: While this solution may have worked in some browsers when it was written in 2014, it no longer works. Navigating or redirecting to an HTTP URL in an
iframe
embedded in an HTTPS page is not permitted by modern browsers, even if the frame started out with an HTTPS URL.
The best solution I created is to simply use google as the ssl proxy...
https://www.google.com/search?q=%http://yourhttpsite.com&btnI=Im+Feeling+Lucky
Tested and works in firefox.
Other Methods:
Use a Third party such as embed.ly (but it it really only good for well known http APIs).
Create your own redirect script on an https page you control (a simple javascript redirect on a relative linked page should do the trick. Something like: (you can use any langauge/method)
https://example.com
That has a iframe linking to...
https://example.com/utilities/redirect.html
Which has a simple js redirect script like...
document.location.href ="http://thenonsslsite.com";
Alternatively, you could add an RSS feed or write some reader/parser to read the http site and display it within your https site.
You could/should also recommend to the http site owner that they create an ssl connection. If for no other reason than it increases seo.
Unless you can get the http site owner to create an ssl certificate, the most secure and permanent solution would be to create an RSS feed grabing the content you need (presumably you are not actually 'doing' anything on the http site -that is to say not logging in to any system).
The real issue is that having http elements inside a https site represents a security issue. There are no completely kosher ways around this security risk so the above are just current work arounds.
Note, that you can disable this security measure in most browsers (yourself, not for others). Also note that these 'hacks' may become obsolete over time.
In selected text, SPACE is shown as dot (.) and TAB as a dash (-).
Firstly, you need to be aware that UTC isn't a format, it's a time zone, effectively. So "converting from ISO8601 to UTC" doesn't really make sense as a concept.
However, here's a sample program using Joda Time which parses the text into a DateTime
and then formats it. I've guessed at a format you may want to use - you haven't really provided enough information about what you're trying to do to say more than that. You may also want to consider time zones... do you want to display the local time at the specified instant? If so, you'll need to work out the user's time zone and convert appropriately.
import org.joda.time.*;
import org.joda.time.format.*;
public class Test {
public static void main(String[] args) {
String text = "2011-03-10T11:54:30.207Z";
DateTimeFormatter parser = ISODateTimeFormat.dateTime();
DateTime dt = parser.parseDateTime(text);
DateTimeFormatter formatter = DateTimeFormat.mediumDateTime();
System.out.println(formatter.print(dt));
}
}
In an Object Oriented parking lot, there will be no need for attendants because the cars will "know how to park".
Finding a usable car on the lot will be difficult; the most common models will either have all their moving parts exposed as public member variables, or they will be "fully encapsulated" cars with no windows or doors.
The parking spaces in our OO parking lot will not match the size and shape of the cars (an "impediance mismatch" between the spaces and the cars)
License tags on our lot will have a dot between each letter and digit. Handicaped parking will only be available for licenses beginning with "_", and licenses beginning with "m_" will be towed.
Note:
$('#my_table > tbody:last').append(newRow); // this will add new row inside tbody
$("table#myTable tr").last().after(newRow); // this will add new row outside tbody
//i.e. between thead and tbody
//.before() will also work similar
Simple
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary" onclick="event.preventDefault();document.getElementById('your-form').submit();">Save changes</button>
If you wrap each template in a script tag, eg:
<script id="about.html" type="text/ng-template">
<div>
<h3>About</h3>
This is the About page
Its cool!
</div>
</script>
Concatenate all templates into 1 big file. If using Visual Studio 2013, download Web essentials - it adds a right click menu to create an HTML Bundle.
Add the code that this guy wrote to change the angular $templatecache
service - its only a small piece of code and it works: Vojta Jina's Gist
Its the $http.get
that should be changed to use your bundle file:
allTplPromise = $http.get('templates/templateBundle.min.html').then(
Your routes templateUrl
should look like this:
$routeProvider.when(
"/about", {
controller: "",
templateUrl: "about.html"
}
);
#
indicates that the following line is a preprocessor directive and should be processed by the preprocessor before compilation by the compiler.
So, #include
is a preprocessor directive that tells the preprocessor to include header files in the program.
< >
indicate the start and end of the file name to be included.
iostream
is a header file that contains functions for input/output operations (cin
and cout
).
Now to sum it up C++ to English translation of the command, #include <iostream>
is:
Dear preprocessor, please include all the contents of the header file iostream
at the very beginning of this program before compiler starts the actual compilation of the code.
If you are a student you can get a free private repository at https://github.com/edu
Update
As noted in another answer, now there is an option for private repos also for simple users
strcmp()
and ===
are both case sensitive but ===
is much faster
sample code: http://snipplr.com/view/758/
I would also highly recommend Adminer - http://www.adminer.org/
It is much faster than phpMyAdmin, does less funky iframe stuff, and supports both MySQL and PostgreSQL.
In Addition you also need to be sure that you have
<context:annotation-config/>
in your SPring configuration xml.
I also would recommend you to read this blog post. It helped me alot. Spring blog - Ajax Simplifications in Spring 3.0
Update:
just checked my working code where I have @RequestBody
working correctly.
I also have this bean in my config:
<bean id="jacksonMessageConverter" class="org.springframework.http.converter.json.MappingJacksonHttpMessageConverter"></bean>
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter">
<property name="messageConverters">
<list>
<ref bean="jacksonMessageConverter"/>
</list>
</property>
</bean>
May be it would be nice to see what Log4j
is saying. it usually gives more information and from my experience the @RequestBody
will fail if your request's content type is not Application/JSON
. You can run Fiddler 2 to test it, or even Mozilla Live HTTP headers plugin can help.
You can use lambda function, an example for 1D array:
import numpy as np
a = [np.nan, 2, 3]
map(lambda v:0 if np.isnan(v) == True else v, a)
This will give you the result:
[0, 2, 3]
getActivity()- Return the Activity this fragment is currently associated with.
In C# 8.0 and above, you can use the range operator ..
as in
var s = "header-THE_TARGET_STRING.7z";
var from = s.IndexOf("-") + "-".Length;
var to = s.IndexOf(".7z");
var versionString = s[from..to]; // THE_TARGET_STRING
See documentation for details.
If you just want to use AWT, then use Graphics.getFontMetrics
(optionally specifying the font, for a non-default one) to get a FontMetrics
and then FontMetrics.stringWidth
to find the width for the specified string.
For example, if you have a Graphics
variable called g
, you'd use:
int width = g.getFontMetrics().stringWidth(text);
For other toolkits, you'll need to give us more information - it's always going to be toolkit-dependent.
Try to do port forwarding,
adb forward tcp:<PC port> tcp:<device port>.
like:
adb forward tcp:5555 tcp:5555.
sounds like 5555 port is captured so use other one. As I know 7612 is empty
[Edit]
C:\Users\m>adb forward tcp:7612 tcp:7612
C:\Users\m>adb tcpip 7612
restarting in TCP mode port: 7612
C:\Users\m>adb connect 192.168.1.12
connected to 192.168.1.12:7612
Be sure that you connect to the right IP address. (You can download Network Info 2 to check your IP)
Log.WriteLine("Value of CompanyName column:" + thisReader["CompanyName"]);
it work for me
System:
Procedure:
Open two shell sessions, logging in to one as the Linux root user
and the other as a nonroot user with access to the mysql
command.
In your root session, stop the normal mysqld listener and start a
listener which bypasses password authentication (note: this is a
significant security risk as anyone with access to the mysql
command may access your databases without a password. You may want
to close active shell sessions and/or disable shell access before
doing this):
# systemctl stop mysqld
# /usr/sbin/mysqld --skip-grant-tables -u mysql &
In your nonroot session, log in to mysql and set the mysql root password:
$ mysql
mysql> flush privileges;
Query OK, 0 rows affected (0.00 sec)
mysql> SET PASSWORD FOR 'root'@'localhost' = PASSWORD('MyNewPass');
Query OK, 0 rows affected, 1 warning (0.01 sec)
mysql> quit;
In your root session, kill the passwordless instance of mysqld and restore the normal mysqld listener to service:
# kill %1
# systemctl start mysqld
In your nonroot session, test the new root password you configured above:
$ mysql -u root -p
Enter password:
Welcome to the MySQL monitor. Commands end with ; or \g.
...
mysql>
Remove the external scripts in your index.html
Change this:
<script src="http://code.highcharts.com/highcharts-more.js"></script>
to
<script src="project_folder/highcharts-more.js"></script>
Does it have to be jquery? Or can you just use JavaScript's native yourpath.split("\\")
to split the string to an array?
DateTime.ParseExact(...)
allows you to tell the parser what each character represents.
You can delete any QuerySet you'd like. For example, to delete all blog posts with some Post model
Post.objects.all().delete()
and to delete any Post with a future publication date
Post.objects.filter(pub_date__gt=datetime.now()).delete()
You do, however, need to come up with a way to narrow down your QuerySet. If you just want a view to delete a particular object, look into the delete generic view.
EDIT:
Sorry for the misunderstanding. I think the answer is somewhere between. To implement your own, combine ModelForm
s and generic views. Otherwise, look into 3rd party apps that provide similar functionality. In a related question, the recommendation was django-filter.
For Angular 2+ you can run this in the console:
document.querySelector('[ng-version]').getAttribute('ng-version')
For AngularJS 1.x:
angular.version.full
I think you will find that the following is more efficient:
IF OBJECT_ID('dbo.ProperCase') IS NOT NULL
DROP FUNCTION dbo.ProperCase
GO
CREATE FUNCTION dbo.PROPERCASE (
@str VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
SET @str = ' ' + @str
SET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE( @str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z')
RETURN RIGHT(@str, LEN(@str) - 1)
END
GO
The replace statement could be cut and pasted directly into a SQL query. It is ultra ugly, however by replacing @str with the column you are interested in, you will not pay a price for an implicit cursor like you will with the udfs thus posted. I find that even using my UDF it is much more efficient.
Oh and instead of generating the replace statement by hand use this:
-- Code Generator for expression
DECLARE @x INT,
@c CHAR(1),
@sql VARCHAR(8000)
SET @x = 0
SET @sql = '@str' -- actual variable/column you want to replace
WHILE @x < 26
BEGIN
SET @c = CHAR(ASCII('a') + @x)
SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+ ''', '' ' + UPPER(@c) + ''')'
SET @x = @x + 1
END
PRINT @sql
Anyway it depends on the number of rows. I wish you could just do s/\b([a-z])/uc $1/, but oh well we work with the tools we have.
NOTE you would have to use this as you would have to use it as....SELECT dbo.ProperCase(LOWER(column)) since the column is in uppercase. It actually works pretty fast on my table of 5,000 entries (not even one second) even with the lower.
In response to the flurry of comments regarding internationalization I present the following implementation that handles every ascii character relying only on SQL Server's Implementation of upper and lower. Remember, the variables we are using here are VARCHAR which means that they can only hold ASCII values. In order to use further international alphabets, you have to use NVARCHAR. The logic would be similar but you would need to use UNICODE and NCHAR in place of ASCII AND CHAR and the replace statement would be much more huge....
-- Code Generator for expression
DECLARE @x INT,
@c CHAR(1),
@sql VARCHAR(8000),
@count INT
SEt @x = 0
SET @count = 0
SET @sql = '@str' -- actual variable you want to replace
WHILE @x < 256
BEGIN
SET @c = CHAR(@x)
-- Only generate replacement expression for characters where upper and lowercase differ
IF @x = ASCII(LOWER(@c)) AND @x != ASCII(UPPER(@c))
BEGIN
SET @sql = 'REPLACE(' + @sql + ', '' ' + @c+ ''', '' ' + UPPER(@c) + ''')'
SET @count = @count + 1
END
SET @x = @x + 1
END
PRINT @sql
PRINT 'Total characters substituted: ' + CONVERT(VARCHAR(255), @count)
Basically the premise of the my method is trading pre-computing for efficiency. The full ASCII implementation is as follows:
IF OBJECT_ID('dbo.ProperCase') IS NOT NULL
DROP FUNCTION dbo.ProperCase
GO
CREATE FUNCTION dbo.PROPERCASE (
@str VARCHAR(8000))
RETURNS VARCHAR(8000)
AS
BEGIN
SET @str = ' ' + @str
SET @str = REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(@str, ' a', ' A'), ' b', ' B'), ' c', ' C'), ' d', ' D'), ' e', ' E'), ' f', ' F'), ' g', ' G'), ' h', ' H'), ' i', ' I'), ' j', ' J'), ' k', ' K'), ' l', ' L'), ' m', ' M'), ' n', ' N'), ' o', ' O'), ' p', ' P'), ' q', ' Q'), ' r', ' R'), ' s', ' S'), ' t', ' T'), ' u', ' U'), ' v', ' V'), ' w', ' W'), ' x', ' X'), ' y', ' Y'), ' z', ' Z'), ' š', ' Š'), ' œ', ' Œ'), ' ž', ' Ž'), ' à', ' À'), ' á', ' Á'), ' â', ' Â'), ' ã', ' Ã'), ' ä', ' Ä'), ' å', ' Å'), ' æ', ' Æ'), ' ç', ' Ç'), ' è', ' È'), ' é', ' É'), ' ê', ' Ê'), ' ë', ' Ë'), ' ì', ' Ì'), ' í', ' Í'), ' î', ' Î'), ' ï', ' Ï'), ' ð', ' Ð'), ' ñ', ' Ñ'), ' ò', ' Ò'), ' ó', ' Ó'), ' ô', ' Ô'), ' õ', ' Õ'), ' ö', ' Ö'), ' ø', ' Ø'), ' ù', ' Ù'), ' ú', ' Ú'), ' û', ' Û'), ' ü', ' Ü'), ' ý', ' Ý'), ' þ', ' Þ'), ' ÿ', ' Ÿ')
RETURN RIGHT(@str, LEN(@str) - 1)
END
GO
The key lies in the differences between references and instances and what the reference can promise and what the instance can really do.
ArrayList<A> a = new ArrayList<A>();
Here a
is a reference to an instance of a specific type - exactly an array list of A
s. More explicitly, a
is a reference to an array list that will accept A
s and will produce A
s. new ArrayList<A>()
is an instance of an array list of A
s, that is, an array list that will accept A
s and will produce A
s.
ArrayList<Integer> a = new ArrayList<Number>();
Here, a
is a reference to exactly an array list of Integers
, i.e. exactly an array list that can accept Integer
s and will produce Integer
s. It cannot point to an array list of Number
s. That array list of Number
s can not meet all the promises of ArrayList<Integer> a
(i.e. an array list of Number
s may produce objects that are not Integer
s, even though its empty right then).
ArrayList<Number> a = new ArrayList<Integer>();
Here, declaration of a
says that a
will refer to exactly an array list of Number
s, that is, exactly an array list that will accept Number
s and will produce Number
s. It cannot point to an array list of Integer
s, because the type declaration of a
says that a
can accept any Number
, but that array list of Integer
s cannot accept just any Number
, it can only accept Integer
s.
ArrayList<? extends Object> a= new ArrayList<Object>();
Here a
is a (generic) reference to a family of types rather than a reference to a specific type. It can point to any list that is member of that family. However, the trade-off for this nice flexible reference is that they cannot promise all of the functionality that it could if it were a type-specific reference (e.g. non-generic). In this case, a
is a reference to an array list that will produce Object
s. But, unlike a type-specific list reference, this a
reference cannot accept any Object
. (i.e. not every member of the family of types that a
can point to can accept any Object
, e.g. an array list of Integer
s can only accept Integer
s.)
ArrayList<? super Integer> a = new ArrayList<Number>();
Again, a
is a reference to a family of types (rather than a single specific type). Since the wildcard uses super
, this list reference can accept Integer
s, but it cannot produce Integer
s. Said another way, we know that any and every member of the family of types that a
can point to can accept an Integer
. However, not every member of that family can produce Integer
s.
PECS - Producer extends
, Consumer super
- This mnemonic helps you remember that using extends
means the generic type can produce the specific type (but cannot accept it). Using super
means the generic type can consume (accept) the specific type (but cannot produce it).
ArrayList<ArrayList<?>> a
An array list that holds references to any list that is a member of a family of array lists types.
= new ArrayList<ArrayList<?>>(); // correct
An instance of an array list that holds references to any list that is a member of a family of array lists types.
ArrayList<?> a
An reference to any array list (a member of the family of array list types).
= new ArrayList<?>()
ArrayList<?>
refers to any type from a family of array list types, but you can only instantiate a specific type.
See also How can I add to List<? extends Number> data structures?
Finally - THERE IS YOUR .APP PROJECT FILE !
Double quotes option helped me
SET QUOTED_IDENTIFIER OFF;
insert into my_table values("hi, my name's tim.");
SET QUOTED_IDENTIFIER ON;
Create Learning Table:
CREATE TABLE "public"."learning" (
"api_id" int4 DEFAULT nextval('share_api_api_id_seq'::regclass) NOT NULL,
"title" varchar(255) COLLATE "default"
);
Insert Data Learning Table:
INSERT INTO "public"."learning" VALUES ('1', 'Google AI-01');
INSERT INTO "public"."learning" VALUES ('2', 'Google AI-02');
INSERT INTO "public"."learning" VALUES ('3', 'Google AI-01');
Step: 01
CREATE OR REPLACE FUNCTION get_all (pattern VARCHAR) RETURNS TABLE (
learn_id INT,
learn_title VARCHAR
) AS $$
BEGIN
RETURN QUERY SELECT
api_id,
title
FROM
learning
WHERE
title = pattern ;
END ; $$ LANGUAGE 'plpgsql';
Step: 02
SELECT * FROM get_all('Google AI-01');
Step: 03
DROP FUNCTION get_all();
This answer will be used as a placeholder for the not fully supported position: sticky
and will be updated over time. It is currently advised to not use the native implementation of this in a production environment.
See this for the current support: https://caniuse.com/#feat=css-sticky
position: sticky
An alternative answer would be using position: sticky
. As described by W3C:
A stickily positioned box is positioned similarly to a relatively positioned box, but the offset is computed with reference to the nearest ancestor with a scrolling box, or the viewport if no ancestor has a scrolling box.
This described exactly the behavior of a relative static header. It would be easy to assign this to the <thead>
or the first <tr>
HTML-tag, as this should be supported according to W3C. However, both Chrome, IE and Edge have problems assigning a sticky position property to these tags. There also seems to be no priority in solving this at the moment.
What does seem to work for a table element is assigning the sticky property to a table-cell. In this case the <th>
cells.
Because a table is not a block-element that respects the static size you assign to it, it is best to use a wrapper element to define the scroll-overflow.
div {_x000D_
display: inline-block;_x000D_
height: 150px;_x000D_
overflow: auto_x000D_
}_x000D_
_x000D_
table th {_x000D_
position: -webkit-sticky;_x000D_
position: sticky;_x000D_
top: 0;_x000D_
}_x000D_
_x000D_
_x000D_
/* == Just general styling, not relevant :) == */_x000D_
_x000D_
table {_x000D_
border-collapse: collapse;_x000D_
}_x000D_
_x000D_
th {_x000D_
background-color: #1976D2;_x000D_
color: #fff;_x000D_
}_x000D_
_x000D_
th,_x000D_
td {_x000D_
padding: 1em .5em;_x000D_
}_x000D_
_x000D_
table tr {_x000D_
color: #212121;_x000D_
}_x000D_
_x000D_
table tr:nth-child(odd) {_x000D_
background-color: #BBDEFB;_x000D_
}
_x000D_
<div>_x000D_
<table border="0">_x000D_
<thead>_x000D_
<tr>_x000D_
<th>head1</th>_x000D_
<th>head2</th>_x000D_
<th>head3</th>_x000D_
<th>head4</th>_x000D_
</tr>_x000D_
</thead>_x000D_
<tr>_x000D_
<td>row 1, cell 1</td>_x000D_
<td>row 1, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 2, cell 1</td>_x000D_
<td>row 2, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 2, cell 1</td>_x000D_
<td>row 2, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 2, cell 1</td>_x000D_
<td>row 2, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>row 2, cell 1</td>_x000D_
<td>row 2, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
<td>row 1, cell 2</td>_x000D_
</tr>_x000D_
</table>_x000D_
</div>
_x000D_
In this example I use a simple <div>
wrapper to define the scroll-overflow done with a static height of 150px
. This can of course be any size. Now that the scrolling box has been defined, the sticky <th>
elements will corespondent "to the nearest ancestor with a scrolling box", which is the div-wrapper.
position: sticky
polyfillNon-supported devices can make use of a polyfill, which implements the behavior through code. An example is stickybits, which resembles the same behavior as the browser's implemented position: sticky
.
Example with polyfill: http://jsfiddle.net/7UZA4/6957/
You should really post:
Here is my code, which works:
import socket, sys
def alert(msg):
print >>sys.stderr, msg
sys.exit(1)
(family, socktype, proto, garbage, address) = \
socket.getaddrinfo("::1", "http")[0] # Use only the first tuple
s = socket.socket(family, socktype, proto)
try:
s.connect(address)
except Exception, e:
alert("Something's wrong with %s. Exception type is %s" % (address, e))
When the server listens, I get nothing (this is normal), when it doesn't, I get the expected message:
Something's wrong with ('::1', 80, 0, 0). Exception type is (111, 'Connection refused')
Use the .date()
method to convert a datetime to a date:
if item_date.date() > from_date:
Alternatively, you could use datetime.today()
instead of date.today()
. You could use
from_date = from_date.replace(hour=0, minute=0, second=0, microsecond=0)
to eliminate the time part afterwards.
You cannot get green/red text, but you can get green/red highlighted text using the diff language template. Example:
```diff
+ this text is highlighted in green
- this text is highlighted in red
```
Even shorter
var foo = (user, pass) =>
new Promise((resolve, reject) => {
if (/* condition */) {
resolve("Fine");
} else {
reject("Error message");
}
});
foo(user, pass).then(result => {
/* process */
});
Shorter way is do it as follows:
private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};
Several of the other answers come close, but honestly, I think you're better off going with the cleanest, simplest syntax. The OP requested a means of exporting a class in ES6 / ES2015. I don't think you can get much cleaner than this:
'use strict';
export default class ClassName {
constructor () {
}
}
One issue could be that if either make, model, or [serial number] were null, values would never get returned. Because string concatenations with null values always result in null, and not in () with null will always return nothing. The remedy for this is to use an operator such as IsNull(make, '') + IsNull(Model, ''), etc.
Here are some examples for insert ... on conflict ...
(pg 9.5+) :
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict do nothing;`
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict(id)
do update set name = 'new_name', size = 3;
insert into dummy(id, name, size) values(1, 'new_name', 3)
on conflict on constraint dummy_pkey
do update set name = 'new_name', size = 4;
To list all unstaged tracked changed files:
git diff --name-only
To list all staged tracked changed files:
git diff --name-only --staged
To list all staged and unstaged tracked changed files:
{ git diff --name-only ; git diff --name-only --staged ; } | sort | uniq
To list all untracked files (the ones listed by git status
, so not including any ignored files):
git ls-files --other --exclude-standard
If you're using this in a shell script, and you want to programmatically check if these commands returned anything, you'll be interested in git diff
's --exit-code
option.
ALT+ENTER was far from eclipse habit ,in IDEA for me mouse over did not work , so in setting>IDESetting>Keymap>Show intention actions and quick-fixes
I changed it to mouse left click , It did not support mouse over! but mouse left click was OK and closest to my intention.
You can remove bullets by setting the list-style-type
to none
on the CSS for the parent element (typically a <ul>
), for example:
ul {
list-style-type: none;
}
You might also want to add padding: 0
and margin: 0
to that if you want to remove indentation as well.
See Listutorial for a great walkthrough of list formatting techniques.
With additional options such as hotkey, description etc.
At first, Project > Add Reference > COM > Windows Script Host Object Model.
using IWshRuntimeLibrary;
private void CreateShortcut()
{
object shDesktop = (object)"Desktop";
WshShell shell = new WshShell();
string shortcutAddress = (string)shell.SpecialFolders.Item(ref shDesktop) + @"\Notepad.lnk";
IWshShortcut shortcut = (IWshShortcut)shell.CreateShortcut(shortcutAddress);
shortcut.Description = "New shortcut for a Notepad";
shortcut.Hotkey = "Ctrl+Shift+N";
shortcut.TargetPath = Environment.GetFolderPath(Environment.SpecialFolder.System) + @"\notepad.exe";
shortcut.Save();
}
Assuming alphanumeric words, you can use:
Search = ^([A-Za-z0-9]+)$
Replace = able:"\1"
Or, if you just want to highlight the lines and use "Replace All" & "In Selection" (with the same replace):
Search = ^(.+)$
^
points to the start of the line.
$
points to the end of the line.
\1
will be the source match within the parentheses.
'\r'
means 'carriage return' and it is similar to '\n'
which means 'line break' or more commonly 'new line'
in the old days of typewriters, you would have to move the carriage that writes back to the start of the line, and move the line down in order to write onto the next line.
in the modern computer era we still have this functionality for multiple reasons. but mostly we use only '\n'
and automatically assume that we want to start writing from the start of the line, since it would not make much sense otherwise.
however, there are some times when we want to use JUST the '\r'
and that would be if i want to write something to an output, and the instead of going down to a new line and writing something else, i want to write something over what i already wrote, this is how many programs in linux or in windows command line are able to have 'progress' information that changes on the same line.
nowadays most systems use only the '\n'
to denote a newline. but some systems use both together.
you can see examples of this given in some of the other answers, but the most common are:
'\r\n'
'\r'
'\n'
and some other programs also have specific uses for them.
for more information about the history of these characters
There is no other way to do it other than what you described. Think about it - how can anyone know what classes extend ClassX without scanning each class on the classpath?
Eclipse can only tell you about the super and subclasses in what seems to be an "efficient" amount of time because it already has all of the type data loaded at the point where you press the "Display in Type Hierarchy" button (since it is constantly compiling your classes, knows about everything on the classpath, etc).
You can use the null-coalescing operator: x ?? something
, where something
is a boolean value that you want to use if x
is null
.
Example:
bool? myBool = null;
bool newBool = myBool ?? false;
newBool
will be false.
I had a similar problem and resolved it by removing any copies/backups of the .cs file from the directory.
Found a way to do this, simply add a querystring to load your components, like so:
@Component({
selector: 'some-component',
templateUrl: `./app/component/stuff/component.html?v=${new Date().getTime()}`,
styleUrls: [`./app/component/stuff/component.css?v=${new Date().getTime()}`]
})
This should force the client to load the server's copy of the template instead of the browser's. If you would like it to refresh only after a certain period of time you could use this ISOString instead:
new Date().toISOString() //2016-09-24T00:43:21.584Z
And substring some characters so that it will only change after an hour for example:
new Date().toISOString().substr(0,13) //2016-09-24T00
Hope this helps
Try this - https://github.com/laracasts/PHP-Vars-To-Js-Transformer Is simple way to append PHP variables to Javascript.
is it ok? yes, it will compile
is it recommended? no - .c files compile to .obj files, which are linked together after compilation (by the linker) into the executable (or library), so there is no need to include one .c file in another. What you probably want to do instead is to make a .h file that lists the functions/variables available in the other .c file, and include the .h file
To open docs automatically in Chrome without them being saved;
Go to the the three vertical dots on your top far right corner in Chrome.
Scroll down to Settings and click.
Scroll down to Show advance settings...
Scroll down to Downloads under Download location: click the Change button and chose tmp folder. Then just close the screen.
Click on any attachments and a small box to the left will appear, it should automatically open if you click on it.
When the bottom left box appears it will contain an arrow; click on it and choose the option "Always open files of this type". Going forward it will open the file instantly instead of the small box appearing to the left and you having to click on it to open. You will have to do it just once for various files such PDF, Excel 2010, Excel 2013 Word, ect.
Using header file stdio.h
you can easily do it as usual like c. before using %.2lf(set a specific number after % specifier.) using printf().
It simply printf specific digits after decimal point.
#include <stdio.h>
#include <iostream>
using namespace std;
int main()
{
double total=100;
printf("%.2lf",total);//this prints 100.00 like as C
}
In my case, I had inserted [(ngModel)] on label rather than input. There is also a caveat, I tried running after correctly the above error in the specified line but the error wouldn't go. If there are other places where you have committed the same mistake, it still throws you the same error at the same line
git reset
if you don't want to commit these changes.
[data-value] {
/* Attribute exists */
}
[data-value="foo"] {
/* Attribute has this exact value */
}
[data-value*="foo"] {
/* Attribute value contains this value somewhere in it */
}
[data-value~="foo"] {
/* Attribute has this value in a space-separated list somewhere */
}
[data-value^="foo"] {
/* Attribute value starts with this */
}
[data-value|="foo"] {
/* Attribute value starts with this in a dash-separated list */
}
[data-value$="foo"] {
/* Attribute value ends with this */
}
I found that none of the answers here applied to my specific use case, so I thought I would share my solution.
I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:
/app/4903294/my-great-car?email=coolguy%40gmail.com to
/public/4903294/my-great-car?email=coolguy%40gmail.com
Here's the solution that worked for me.
return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))
Hope this helps someone!
This is what worked for me, for my case it was a post for login request :
var client = new RestClient("http://www.example.com/1/2");
var request = new RestRequest();
request.Method = Method.POST;
request.AddHeader("Accept", "application/json");
request.Parameters.Clear();
request.AddParameter("application/json", body , ParameterType.RequestBody);
var response = client.Execute(request);
var content = response.Content; // raw content as string
body :
{
"userId":"[email protected]" ,
"password":"welcome"
}
In rpy2, the way to get the very same operator as "[" with R is to use ".rx". See the documentation about extracting with rpy2
For creating vectors, if you know your way around with Python there should not be any issue. See the documentation about creating vectors
It's an awesome detailed reply by Janusz. But just for the sake of people who are coming to this page for answers, the easier way is at http://android-holo-colors.com/ (dead link) linked from Android Asset Studio
A good description of all the tools are at AndroidOnRocks.com (site offline now)
However, I highly recommend everybody to read the reply from Janusz as it will make understanding clearer. Use the tool to do stuffs real quick
To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.
begin
current_user.comments.find(ids)
rescue
#do something in case of exception found
end
Here's more info on exceptions in ruby.
You don't even have to set a specific width for the cells, table-layout: fixed
suffices to spread the cells evenly.
ul {_x000D_
width: 100%;_x000D_
display: table;_x000D_
table-layout: fixed;_x000D_
border-collapse: collapse;_x000D_
}_x000D_
li {_x000D_
display: table-cell;_x000D_
text-align: center;_x000D_
border: 1px solid hotpink;_x000D_
vertical-align: middle;_x000D_
word-wrap: break-word;_x000D_
}
_x000D_
<ul>_x000D_
<li>foo<br>foo</li>_x000D_
<li>barbarbarbarbar</li>_x000D_
<li>baz</li>_x000D_
</ul>
_x000D_
Note that for
table-layout
to work the table styled element must have a width set (100% in my example).
I've found this script example useful (from http://www.mrexcel.com/forum/excel-questions/898899-json-api-excel.html#post4332075 ):
Sub getData()
Dim Movie As Object
Dim scriptControl As Object
Set scriptControl = CreateObject("MSScriptControl.ScriptControl")
scriptControl.Language = "JScript"
With CreateObject("MSXML2.XMLHTTP")
.Open "GET", "http://www.omdbapi.com/?t=frozen&y=&plot=short&r=json", False
.send
Set Movie = scriptControl.Eval("(" + .responsetext + ")")
.abort
With Sheets(2)
.Cells(1, 1).Value = Movie.Title
.Cells(1, 2).Value = Movie.Year
.Cells(1, 3).Value = Movie.Rated
.Cells(1, 4).Value = Movie.Released
.Cells(1, 5).Value = Movie.Runtime
.Cells(1, 6).Value = Movie.Director
.Cells(1, 7).Value = Movie.Writer
.Cells(1, 8).Value = Movie.Actors
.Cells(1, 9).Value = Movie.Plot
.Cells(1, 10).Value = Movie.Language
.Cells(1, 11).Value = Movie.Country
.Cells(1, 12).Value = Movie.imdbRating
End With
End With
End Sub
Why the base class' default constructor is called? Turns out it's not always be the case. Any constructor of the base class (with different signatures) can be invoked from the derived class' constructor. In your case, the default constructor is called because it has no parameters so it's default.
When a derived class is created, the order the constructors are called is always Base -> Derived in the hierarchy. If we have:
class A {..}
class B : A {...}
class C : B {...}
C c;
When c is create, the constructor for A is invoked first, and then the constructor for B, and then the constructor for C.
To guarantee that order, when a derived class' constructor is called, it always invokes the base class' constructor before the derived class' constructor can do anything else. For that reason, the programmer can manually invoke a base class' constructor in the only initialisation list of the derived class' constructor, with corresponding parameters. For instance, in the following code, Derived's default constructor will invoke Base's constructor Base::Base(int i) instead of the default constructor.
Derived() : Base(5)
{
}
If there's no such constructor invoked in the initialisation list of the derived class' constructor, then the program assumes a base class' constructor with no parameters. That's the reason why a constructor with no parameters (i.e. the default constructor) is invoked.
To change transparency on an svg code the simplest way is to open it on any text editor and look for the style attributes. It depends on the svg creator the way the styles are displayed. As i am an Inkscape user the usual way it set the style values is through a style tag just as if it were html but using svg native attributes like fill
, stroke
, stroke-width
, opacity
and so on. opacity
affects the whole svg object, or path or group in which its stated and fill-opacity
, stroke-opacity
will affect just the fill and the stroke transparency. That said, I have also used and tasted to just use fill
and instead of using#fff
use instead the rgba standard like this rgba(255, 255, 255, 1)
just as in css. This works fine for must modern browsers.
Keep in mind that if you intend to further reedit your svg the best practice, in my experience, is to always keep an untouched version at hand. Inkscape is more flexible with hand changed svgs but Illustrator and CorelDraw may have issues importing and edited svg.
Example
<path style="fill:#ff0000;fill-opacity:1;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>
Example 2
<path style="fill:#ff0000;fill-opacity:.5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>
Example 3
<path style="fill:rgba(255, 0, 0, .5;stroke:#1a1a1a;stroke-width:2px;stroke-opacity:1" d="m 144.44226,461.14425 q 16.3125,-15.05769 37.64423,-15.05769 21.33173,0 36.38942,15.05769 15.0577,15.05769 15.0577,36.38942 0,21.33173 -15.0577,36.38943 -15.05769,16.3125 -36.38942,16.3125 -21.33173,0 -37.64423,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z M 28.99995,35.764435 l 85.32692,0 23.84135,52.701923 386.48078,0 q 10.03846,0 17.5673,7.528847 8.78366,7.528845 8.78366,17.567305 0,7.52885 -2.50962,12.54808 l -94.11058,161.87019 q -13.80288,27.60577 -45.17307,27.60577 l -194.4952,0 -26.35096,40.15385 q -2.50962,6.27404 -2.50962,7.52885 0,6.27404 6.27404,6.27404 l 298.64424,0 0,50.1923 -304.91828,0 q -25.09615,0 -41.40865,-13.80288 -15.05769,-13.80289 -15.05769,-38.89904 0,-15.05769 6.27404,-25.09615 l 38.89903,-63.9952 -92.855766,-189.475962 -52.701924,0 0,-52.701923 z M 401.67784,461.14425 q 15.05769,-15.05769 36.38942,-15.05769 21.33174,0 36.38943,15.05769 16.3125,15.05769 16.3125,36.38942 0,21.33173 -16.3125,36.38943 -15.05769,16.3125 -36.38943,16.3125 -21.33173,0 -36.38942,-16.3125 -15.05769,-15.0577 -15.05769,-36.38943 0,-21.33173 15.05769,-36.38942 z"/>
Notice that in the last example the fill-opacity
has been removed as rgba standard covers both color and alpha channel.
In Swift, I'm using:
In my Macros.swift I just added
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__){
println("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
you can now just call anywhere
TICK()
// your code to be tracked
TOCK()
Swift 5.0
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = #function, file: String = #file, line: Int = #line){
print("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
The for loop can only contain three parameters, you have used 4. Please restate the question, what do you want to achieve?
The declaration for Sleep in kernel32.dll won't work in 64-bit Excel. This would be a little more general:
#If VBA7 Then
Public Declare PtrSafe Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#Else
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
#End If
This worked for me:
$.ajax({
url:"../messaging/delete.php",
type:"POST",
data:{messages:selected},
success:function(data){
if(data === "done"){
}
info($("#notification"), data);
},
beforeSend:function(){
info($("#notification"),"Deleting "+count+" messages");
},
error:function(jqXHR, textStatus, errorMessage){
error($("#notification"),errorMessage);
}
});
And this for your PHP:
$messages = $_POST['messages']
foreach($messages as $msg){
echo $msg;
}
On Windows 2003, to call another script without waiting, I used this:
$commandString = "start /b c:\\php\\php.EXE C:\\Inetpub\\wwwroot\\mysite.com\\phpforktest.php --passmsg=$testmsg";
pclose(popen($commandString, 'r'));
This only works AFTER giving changing permissions on cmd.exe
- add Read and Execute for IUSR_YOURMACHINE
(I also set write to Deny).
if you have two divs, you can use this to align the divs next to each other in the same row:
#keyword {_x000D_
float:left;_x000D_
margin-left:250px;_x000D_
position:absolute;_x000D_
}_x000D_
_x000D_
#bar {_x000D_
text-align:center;_x000D_
}
_x000D_
<div id="keyword">_x000D_
Keywords:_x000D_
</div>_x000D_
<div id="bar">_x000D_
<input type = textbox name ="keywords" value="" onSubmit="search()" maxlength=40>_x000D_
<input type = button name="go" Value="Go ahead and find" onClick="search()">_x000D_
</div>
_x000D_
Is this a stored procedure? If so, I think you could just do a Return, such as "Return NULL";
You could use multiple background: linear-gradient(); calls, but try this:
If you want the images to be completely fused together where it doesn't look like the elements load separately due to separate HTTP requests then use this technique. Here we're loading two things on the same element that load simultaneously...
Just make sure you convert your pre-rendered 32-bit transparent png image/texture to base64 string first and use it within the background-image css call (in place of INSERTIMAGEBLOBHERE in this example).
I used this technique to fuse a wafer looking texture and other image data that's serialized with a standard rgba transparency / linear gradient css rule. Works better than layering multiple art and wasting HTTP requests which is bad for mobile. Everything is loaded client side with no file operation required, but does increase document byte size.
div.imgDiv {
background: linear-gradient(to right bottom, white, rgba(255,255,255,0.95), rgba(255,255,255,0.95), rgba(255,255,255,0.9), rgba(255,255,255,0.9), rgba(255,255,255,0.85), rgba(255,255,255,0.8) );
background-image: url("data:image/png;base64,INSERTIMAGEBLOBHERE");
}
I had the same problem. I changed the order of the scripts in the head part, and it worked for me. Every script the plugin needs - needs to stay close.
For example:
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"></script>
<script type="text/javascript" src="http://cloud.github.com/downloads/malsup/cycle/jquery.cycle.all.latest.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#slider').cycle({
fx: 'fade'
});
});
</script>
try {
$result=DB::table('users')->whereExists(function ($Query){
$Query->where('id','<','14162756');
$Query->whereBetween('password',[14162756,48384486]);
$Query->whereIn('id',[3,8,12]);
});
}catch (\Exception $error){
Log::error($error);
DB::rollBack(1);
return redirect()->route('bye');
}
You will have to build a CLR procedure that provides regex functionality, as this article illustrates.
Their example function uses VB.NET:
Imports System
Imports System.Data.Sql
Imports Microsoft.SqlServer.Server
Imports System.Data.SqlTypes
Imports System.Runtime.InteropServices
Imports System.Text.RegularExpressions
Imports System.Collections 'the IEnumerable interface is here
Namespace SimpleTalk.Phil.Factor
Public Class RegularExpressionFunctions
'RegExIsMatch function
<SqlFunction(IsDeterministic:=True, IsPrecise:=True)> _
Public Shared Function RegExIsMatch( _
ByVal pattern As SqlString, _
ByVal input As SqlString, _
ByVal Options As SqlInt32) As SqlBoolean
If (input.IsNull OrElse pattern.IsNull) Then
Return SqlBoolean.False
End If
Dim RegExOption As New System.Text.RegularExpressions.RegExOptions
RegExOption = Options
Return RegEx.IsMatch(input.Value, pattern.Value, RegExOption)
End Function
End Class '
End Namespace
...and is installed in SQL Server using the following SQL (replacing '%'-delimted variables by their actual equivalents:
sp_configure 'clr enabled', 1
RECONFIGURE WITH OVERRIDE
IF EXISTS ( SELECT 1
FROM sys.objects
WHERE object_id = OBJECT_ID(N'dbo.RegExIsMatch') )
DROP FUNCTION dbo.RegExIsMatch
go
IF EXISTS ( SELECT 1
FROM sys.assemblies asms
WHERE asms.name = N'RegExFunction ' )
DROP ASSEMBLY [RegExFunction]
CREATE ASSEMBLY RegExFunction
FROM '%FILE%'
GO
CREATE FUNCTION RegExIsMatch
(
@Pattern NVARCHAR(4000),
@Input NVARCHAR(MAX),
@Options int
)
RETURNS BIT
AS EXTERNAL NAME
RegExFunction.[SimpleTalk.Phil.Factor.RegularExpressionFunctions].RegExIsMatch
GO
--a few tests
---Is this card a valid credit card?
SELECT dbo.RegExIsMatch ('^(?:4[0-9]{12}(?:[0-9]{3})?|5[1-5][0-9]{14}|6(?:011|5[0-9][0-9])[0-9]{12}|3[47][0-9]{13}|3(?:0[0-5]|[68][0-9])[0-9]{11}|(?:2131|1800|35\d{3})\d{11})$','4241825283987487',1)
--is there a number in this string
SELECT dbo.RegExIsMatch( '\d','there is 1 thing I hate',1)
--Verifies number Returns 1
DECLARE @pattern VARCHAR(255)
SELECT @pattern ='[a-zA-Z0-9]\d{2}[a-zA-Z0-9](-\d{3}){2}[A-Za-z0-9]'
SELECT dbo.RegExIsMatch (@pattern, '1298-673-4192',1),
dbo.RegExIsMatch (@pattern,'A08Z-931-468A',1),
dbo.RegExIsMatch (@pattern,'[A90-123-129X',1),
dbo.RegExIsMatch (@pattern,'12345-KKA-1230',1),
dbo.RegExIsMatch (@pattern,'0919-2893-1256',1)
There is no portable function that allows to check if a key is hit and continue if not. This is always system dependent.
Solution for linux and other posix compliant systems:
Here, for Morgan Mattews's code provide kbhit()
functionality in a way compatible with any POSIX compliant system. He uses the trick of desactivating buffering at termios level.
Solution for windows:
For windows, Microsoft offers _kbhit()
Make sure you have your maven bin directory in the path and the JAVA_HOME property set
I think if you want to use extension methods you need to use the GroupJoin
var query =
people.GroupJoin(pets,
person => person,
pet => pet.Owner,
(person, petCollection) =>
new { OwnerName = person.Name,
Pet = PetCollection.Select( p => p.Name )
.DefaultIfEmpty() }
).ToList();
You may have to play around with the selection expression. I'm not sure it would give you want you want in the case where you have a 1-to-many relationship.
I think it's a little easier with the LINQ Query syntax
var query = (from person in context.People
join pet in context.Pets on person equals pet.Owner
into tempPets
from pets in tempPets.DefaultIfEmpty()
select new { OwnerName = person.Name, Pet = pets.Name })
.ToList();
See this post - note that the IP address in the URL given is constant (which confused me at first), but the data returned is specific to your instance.
To start the PostgreSQL server:
pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start
To end the PostgreSQL server:
pg_ctl -D /usr/local/var/postgres stop -s -m fast
You can also create an alias via CLI to make it easier:
alias pg-start='pg_ctl -D /usr/local/var/postgres -l /usr/local/var/postgres/server.log start'
alias pg-stop='pg_ctl -D /usr/local/var/postgres stop -s -m fast'
With these you can just type "pg-start" to start PostgreSQL and "pg-stop" to shut it down.
I use this way:
String[] array={
"man","for","think"
}; int j;
then below the onCreate
TextView t = findViewById(R.id.textView);
new CountDownTimer(5000,1000) {
@Override
public void onTick(long millisUntilFinished) {}
@Override
public void onFinish() {
t.setText("I "+array[j] +" You");
j++;
if(j== array.length-1) j=0;
start();
}
}.start();
it's easy way to solve this problem.
When using Java 7+
use the following method to download a file from the Internet and save it to some directory:
private static Path download(String sourceURL, String targetDirectory) throws IOException
{
URL url = new URL(sourceURL);
String fileName = sourceURL.substring(sourceURL.lastIndexOf('/') + 1, sourceURL.length());
Path targetPath = new File(targetDirectory + File.separator + fileName).toPath();
Files.copy(url.openStream(), targetPath, StandardCopyOption.REPLACE_EXISTING);
return targetPath;
}
Documentation here.
AWS CLI is the best option to download an entire S3 bucket locally.
Install AWS CLI.
Configure AWS CLI for using default security credentials and default AWS Region.
To download the entire S3 bucket use command
aws s3 sync s3://yourbucketname localpath
Reference to use AWS cli for different AWS services: https://docs.aws.amazon.com/cli/latest/reference/
Callbacks are most easily described in terms of the telephone system. A function call is analogous to calling someone on a telephone, asking her a question, getting an answer, and hanging up; adding a callback changes the analogy so that after asking her a question, you also give her your name and number so she can call you back with the answer.
Paul Jakubik, Callback Implementations in C++.
In my case is a cookie-related issue, I had many cookies with value extremely big, and that was causing the problem.
You can replicate this issue here on stackoverflow.com, just open the console and type this:
[ ...Array(5) ].forEach((i, idx) => {
document.cookie = `stackoverflow_cookie${idx}=${'a'.repeat(4000)}`;
});
What is that?
I am creating 5 cookies with a string of length or value of 4000 bytes; then reload the page and you will see the same issue.
I tried it on google.com and you'll get the error but they automatically clear the cookies for you, which is a nice fallback to start fresh.
Neither one of the solutions worked form me. The only one that worked for me in Spring form is:
action="./upload?${_csrf.parameterName}=${_csrf.token}"
REPLACED WITH:
action="./upload?_csrf=${_csrf.token}"
(Spring 5 with enabled csrf in java configuration)
Just wanted to add to the answers already provided, the Python decorator library has some simple yet useful implementations that can also memoize "unhashable types", unlike functools.lru_cache
.
For the most part you treat it as if you are validating any other kind of control but use the InitialValue property of the required field validator.
<asp:RequiredFieldValidator ID="rfv1" runat="server" ControlToValidate="your-dropdownlist" InitialValue="Please select" ErrorMessage="Please select something" />
Basically what it's saying is that validation will succeed if any other value than the 1 set in InitialValue is selected in the dropdownlist.
If databinding you will need to insert the "Please select" value afterwards as follows
this.ddl1.Items.Insert(0, "Please select");
Encoding targetEncoding = Encoding.GetEncoding(1252);
// Encode a string into an array of bytes.
Byte[] encodedBytes = targetEncoding.GetBytes(utfString);
// Show the encoded byte values.
Console.WriteLine("Encoded bytes: " + BitConverter.ToString(encodedBytes));
// Decode the byte array back to a string.
String decodedString = Encoding.Default.GetString(encodedBytes);
In python "else if" is spelled "elif".
Also, you need a colon after the elif
and the else
.
Simple answer to a simple question. I had the same problem, when I first started (in the last couple of weeks).
So your code should read:
def function(a):
if a == '1':
print('1a')
elif a == '2':
print('2a')
else:
print('3a')
function(input('input:'))
One solution is to run manually a shell function that sets my environment to work or personal, but I am pretty sure that I will often forget to switch to the correct identity resulting in committing under the wrong identity.
That was exactly my problem. I have written a hook script which warns you if you have any github remote and not defined a local username.
Here's how you set it up:
Create a directory to hold the global hook
mkdir -p ~/.git-templates/hooks
Tell git to copy everything in ~/.git-templates
to your per-project .git
directory when you run git init or clone
git config --global init.templatedir '~/.git-templates'
And now copy the following lines to ~/.git-templates/hooks/pre-commit
and make the file executable (don't forget this otherwise git won't execute it!)
#!/bin/bash
RED='\033[0;31m' # red color
NC='\033[0m' # no color
GITHUB_REMOTE=$(git remote -v | grep github.com)
LOCAL_USERNAME=$(git config --local user.name)
if [ -n "$GITHUB_REMOTE" ] && [ -z "$LOCAL_USERNAME" ]; then
printf "\n${RED}ATTENTION: At least one Github remote repository is configured, but no local username. "
printf "Please define a local username that matches your Github account.${NC} [pre-commit hook]\n\n"
exit 1
fi
If you use other hosts for your private repositories you have to replace github.com
according to your needs.
Now every time you do a git init
or git clone
git will copy this script to the repository and executes it before any commit is done. If you have not set a local username it will output a warning and won't let you commit.
This should only allow decimals > 0
^([0-9]\.\d+)|([1-9]\d*\.?\d*)$
If your column is of type DATE (as you say), then you don't need to convert it into a string first (in fact you would convert it implicitly to a string first, then explicitly to a date and again explicitly to a string):
SELECT TO_CHAR(COL1, 'mm/dd/yyyy') FROM TABLE1
The date format your seeing for your column is an artifact of the tool your using (TOAD, SQL Developer etc.) and it's language settings.
Change draggable
attribute from
<span draggable="true">Label</span>
to
<span draggable="false">Label</span>
If you need to use Content-Type=x-www-urlencoded-form then DO NOT use FormDataCollection as parameter: In asp.net Core 2+ FormDataCollection has no default constructors which is required by Formatters. Use IFormCollection instead:
public IActionResult Search([FromForm]IFormCollection type)
{
return Ok();
}
Since you've got both the shell that you're typing into and the shell that sudo -s
runs, you need to quote or escape twice. (EDITED fixed quoting)
sudo -su db2inst1 '/opt/ibm/db2/V9.7/bin/db2 force application \(1995\)'
or
sudo -su db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \\\(1995\\\)
Out of curiosity, why do you need -s? Can't you just do this:
sudo -u db2inst1 /opt/ibm/db2/V9.7/bin/db2 force application \(1995\)
This may not be what you want to hear, but display: table-cell
does not respect width and will be collapsed based on the width of the entire table. You can get around this easily just by having a display: block
element inside of the table cell itself whose width you specify, e.g
<td><div style="width: 300px;">wide</div></td>
This shouldn't make much of a difference if the <table>
itself is position: fixed
or absolute because the position of the cells are all static relative to the table.
http://jsfiddle.net/ExplosionPIlls/Mkq8L/4/
EDIT: I can't take credit, but as the comments say you can just use min-width
instead of width
on the table cell instead.
The most important part is the concepts. Once you understand how the building blocks work, differences in syntax amount to little more than mild dialects. A layer on top of your regular expression engine's syntax is the syntax of the programming language you're using. Languages such as Perl remove most of this complication, but you'll have to keep in mind other considerations if you're using regular expressions in a C program.
If you think of regular expressions as building blocks that you can mix and match as you please, it helps you learn how to write and debug your own patterns but also how to understand patterns written by others.
Conceptually, the simplest regular expressions are literal characters. The pattern N
matches the character 'N'.
Regular expressions next to each other match sequences. For example, the pattern Nick
matches the sequence 'N' followed by 'i' followed by 'c' followed by 'k'.
If you've ever used grep
on Unix—even if only to search for ordinary looking strings—you've already been using regular expressions! (The re
in grep
refers to regular expressions.)
Adding just a little complexity, you can match either 'Nick' or 'nick' with the pattern [Nn]ick
. The part in square brackets is a character class, which means it matches exactly one of the enclosed characters. You can also use ranges in character classes, so [a-c]
matches either 'a' or 'b' or 'c'.
The pattern .
is special: rather than matching a literal dot only, it matches any character†. It's the same conceptually as the really big character class [-.?+%$A-Za-z0-9...]
.
Think of character classes as menus: pick just one.
Using .
can save you lots of typing, and there are other shortcuts for common patterns. Say you want to match a digit: one way to write that is [0-9]
. Digits are a frequent match target, so you could instead use the shortcut \d
. Others are \s
(whitespace) and \w
(word characters: alphanumerics or underscore).
The uppercased variants are their complements, so \S
matches any non-whitespace character, for example.
From there, you can repeat parts of your pattern with quantifiers. For example, the pattern ab?c
matches 'abc' or 'ac' because the ?
quantifier makes the subpattern it modifies optional. Other quantifiers are
*
(zero or more times)+
(one or more times){n}
(exactly n times){n,}
(at least n times){n,m}
(at least n times but no more than m times)Putting some of these blocks together, the pattern [Nn]*ick
matches all of
The first match demonstrates an important lesson: *
always succeeds! Any pattern can match zero times.
A few other useful examples:
[0-9]+
(and its equivalent \d+
) matches any non-negative integer\d{4}-\d{2}-\d{2}
matches dates formatted like 2019-01-01A quantifier modifies the pattern to its immediate left. You might expect 0abc+0
to match '0abc0', '0abcabc0', and so forth, but the pattern immediately to the left of the plus quantifier is c
. This means 0abc+0
matches '0abc0', '0abcc0', '0abccc0', and so on.
To match one or more sequences of 'abc' with zeros on the ends, use 0(abc)+0
. The parentheses denote a subpattern that can be quantified as a unit. It's also common for regular expression engines to save or "capture" the portion of the input text that matches a parenthesized group. Extracting bits this way is much more flexible and less error-prone than counting indices and substr
.
Earlier, we saw one way to match either 'Nick' or 'nick'. Another is with alternation as in Nick|nick
. Remember that alternation includes everything to its left and everything to its right. Use grouping parentheses to limit the scope of |
, e.g., (Nick|nick)
.
For another example, you could equivalently write [a-c]
as a|b|c
, but this is likely to be suboptimal because many implementations assume alternatives will have lengths greater than 1.
Although some characters match themselves, others have special meanings. The pattern \d+
doesn't match backslash followed by lowercase D followed by a plus sign: to get that, we'd use \\d\+
. A backslash removes the special meaning from the following character.
Regular expression quantifiers are greedy. This means they match as much text as they possibly can while allowing the entire pattern to match successfully.
For example, say the input is
"Hello," she said, "How are you?"
You might expect ".+"
to match only 'Hello,' and will then be surprised when you see that it matched from 'Hello' all the way through 'you?'.
To switch from greedy to what you might think of as cautious, add an extra ?
to the quantifier. Now you understand how \((.+?)\)
, the example from your question works. It matches the sequence of a literal left-parenthesis, followed by one or more characters, and terminated by a right-parenthesis.
If your input is '(123) (456)', then the first capture will be '123'. Non-greedy quantifiers want to allow the rest of the pattern to start matching as soon as possible.
(As to your confusion, I don't know of any regular-expression dialect where ((.+?))
would do the same thing. I suspect something got lost in transmission somewhere along the way.)
Use the special pattern ^
to match only at the beginning of your input and $
to match only at the end. Making "bookends" with your patterns where you say, "I know what's at the front and back, but give me everything between" is a useful technique.
Say you want to match comments of the form
-- This is a comment --
you'd write ^--\s+(.+)\s+--$
.
Regular expressions are recursive, so now that you understand these basic rules, you can combine them however you like.
†: The statement above that .
matches any character is a simplification for pedagogical purposes that is not strictly true. Dot matches any character except newline, "\n"
, but in practice you rarely expect a pattern such as .+
to cross a newline boundary. Perl regexes have a /s
switch and Java Pattern.DOTALL
, for example, to make .
match any character at all. For languages that don't have such a feature, you can use something like [\s\S]
to match "any whitespace or any non-whitespace", in other words anything.