To find all valid address list this is the code I have used
public static IEnumerable<string> GetAddresses()
{
var host = Dns.GetHostEntry(Dns.GetHostName());
return (from ip in host.AddressList where ip.AddressFamily == AddressFamily.lo select ip.ToString()).ToList();
}
The regex allows the use of leading zeros in the IPv4 parts.
Some Unix and Mac distros convert those segments into octals.
I suggest using 25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d
as an IPv4 segment.
System.setProperty is not working for applets. Because JVM already running before applet start. In this case we use applet parameters like this:
deployJava.runApplet({
id: 'MyApplet',
code: 'com.mkysoft.myapplet.SomeClass',
archive: 'com.mkysoft.myapplet.jar'
}, {
java_version: "1.6*", // Target version
cache_option: "no",
cache_archive: "",
codebase_lookup: true,
java_arguments: "-Djava.net.preferIPv4Stack=true"
},
"1.6" // Minimum version
);
You can find deployJava.js at https://www.java.com/js/deployJava.js
The standard way is to make them "setuid" so that they start up as root, and then they throw away that root privilege as soon as they've bound to the port but before they start accepting connections to it. You can see good examples of that in the source code for Apache and INN. I'm told that Lighttpd is another good example.
Another example is Postfix, which uses multiple daemons that communicate through pipes, and only one or two of them (which do very little except accept or emit bytes) run as root and the rest run at a lower privilege.
The protocols used in IPv6 are the same as the protocols in IPv4. The only thing that changed between the two versions is the addressing scheme, DHCP [DHCPv6] and ICMP [ICMPv6]. So basically, anything TCP/UDP related, including the port range (0-65535) remains unchanged.
Edit: Port 0 is a reserved port in TCP but it does exist. See RFC793
The IPAddress Java library can accomplish what you are describing here.
IPv6 addresses are 16 bytes. Using that library, if you are starting with a 16-byte array you can construct the IPv6 address object:
IPv6Address addr = new IPv6Address(bytes); //bytes is byte[16]
From there you can check if the address is IPv4 mapped, IPv4 compatible, IPv4 translated, and so on (there are many possible ways IPv6 represents IPv4 addresses). In most cases, if an IPv6 address represents an IPv4 address, the ipv4 address is in the lower 4 bytes, and so you can get the derived IPv4 address as follows. Afterwards, you can convert back to bytes, which will be just 4 bytes for IPv4.
if(addr.isIPv4Compatible() || addr.isIPv4Mapped()) {
IPv4Address derivedIpv4Address = addr.getEmbeddedIPv4Address();
byte ipv4Bytes[] = derivedIpv4Address.getBytes();
...
}
The javadoc is available at the link.
The ipv6 localhost is ::1
. The unspecified address is ::
. This is defined in RFC 4291 section 2.5.
If you want your container ports to bind on your ipv4 address, just :
works for me on docker 1.9.1
Since IPv6-Adresses are written in Hex-notation you can use "Hexspeak" (numbers 0-9 and letters a-f) in Adresses.
There are a number of words you can use as valid adresses to better momorize them.
If you ping6 www.facebook.com -n
you will get something like "2a03:2880:f01c:601:face:b00c:0:1".
Here are some examples:
45 characters.
You might expect an address to be
0000:0000:0000:0000:0000:0000:0000:0000
8 * 4 + 7 = 39
8 groups of 4 digits with 7 :
between them.
But if you have an IPv4-mapped IPv6 address, the last two groups can be written in base 10 separated by .
, eg. [::ffff:192.168.100.228]
. Written out fully:
0000:0000:0000:0000:0000:ffff:192.168.100.228
(6 * 4 + 5) + 1 + (4 * 3 + 3) = 29 + 1 + 15 = 45
Note, this is an input/display convention - it's still a 128 bit address and for storage it would probably be best to standardise on the raw colon separated format, i.e. [0000:0000:0000:0000:0000:ffff:c0a8:64e4]
for the address above.
I was able to achieve the desired result by using Alt + Shift + up/down and then typing the desired comment characters and additional character.
Dim rowNo1 As Short Dim numrow As Short Dim colNo1 As Short Dim colNo2 As Short
rowNo1 = 1
colNo1 = 1
colNo2 = 1
numrow = 1
ObjEXCEL = CType(CreateObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
objEXCELBook = CType(ObjEXCEL.Workbooks.Add, Microsoft.Office.Interop.Excel.Workbook)
objEXCELSheet = CType(objEXCELBook.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
ObjEXCEL.Visible = True
For numCounter = 0 To grdName.Columns.Count - 1
' MsgBox(grdName.Columns(numCounter).HeaderText())
If grdName.Columns(numCounter).Width > 0 Then
ObjEXCEL.Cells(1, numCounter + 1) = grdName.Columns(numCounter).HeaderText()
End If
' ObjEXCEL.Cells(1, numCounter + 1) = grdName.Columns.GetFirstColumn(DataGridViewElementStates.Displayed)
Next numCounter
ObjEXCEL.Range("A:A").ColumnWidth = 10
ObjEXCEL.Range("B:B").ColumnWidth = 25
ObjEXCEL.Range("C:C").ColumnWidth = 20
ObjEXCEL.Range("D:D").ColumnWidth = 20
ObjEXCEL.Range("E:E").ColumnWidth = 20
ObjEXCEL.Range("F:F").ColumnWidth = 25
For rowNo1 = 0 To grdName.RowCount - 1
For colNo1 = 0 To grdName.ColumnCount - 1
If grdName.Columns(colNo1).Width > 0 Then
If Trim(grdName.Item(colNo1, rowNo1).Value) <> "" Then
'If IsDate(grdName.Item(colNo1, rowNo1).Value) = True Then
' ObjEXCEL.Cells(numrow + 1, colNo2) = Format(CDate(grdName.Item(colNo1, rowNo1).Value), "dd/MMM/yyyy")
'Else
ObjEXCEL.Cells(numrow + 1, colNo2) = grdName.Item(colNo1, rowNo1).Value
'End If
End If
If colNo2 >= grdName.ColumnCount Then
colNo2 = 1
Else
colNo2 = colNo2 + 1
End If
End If
Next colNo1
numrow = numrow + 1
Next rowNo1
ps -ef | grep 'myProcessName' | grep -v grep | awk '{print $2}' | xargs -r kill -9
What's this code doing?
The ps -ef
produces a list of process id's on the computer visible to this user. The pipe grep filters that down for rows containing that string. The grep -v grep
says don't match on the process itself doing the grepping. The pipe awk print says split the rows on default delimiter whitespace and filter to the second column which is our process id. The pipe xargs spins up a new process to send all those pid's to kill -9
, ending them all.
The above code is bad, dangerous, ugly and hackish for several reasons.
If the code being force-ended is doing any database ops or secure transactions with low probability race conditions, some fraction of a percent of the time, atomicity of that transaction will be wrecked, producing undefined behavior. kill -9 takes no prisoners. If your code is sensitive to this, try replacing the xargs kill
part with a transmitted flag that requests a graceful shutdown, and only if that request is denied, last-resort to kill -9
There's a non zero possibility that you will accidentally end the operating system or caused undefined behavior in an unrelated process, leading to whole system instability because ps -ef
lists every possible process that could exist, and you can't be sure some weird 3rd party library shares your process name, or that in the time between read and execute kill -9, the processid had changed to something else, and now you've accidentally ended some random process you didn't intend to.
But, if you understand the risks and control for them with very unique names, and you're ok with a few dropped transactions or occasional corruption in data, then 99.9% of the time yer gonna be fine. If there's a problem, reboot the computer, make sure there aren't any process collisions. It's because of code like this that makes the tech support script: "Have you tried restarting your computer" a level 5 meme.
You could make use of the Javascript DOM API. In particular, look at the createElement() method.
You could create a re-usable function that will create an image like so...
function show_image(src, width, height, alt) {
var img = document.createElement("img");
img.src = src;
img.width = width;
img.height = height;
img.alt = alt;
// This next line will just add it to the <body> tag
document.body.appendChild(img);
}
Then you could use it like this...
<button onclick=
"show_image('http://google.com/images/logo.gif',
276,
110,
'Google Logo');">Add Google Logo</button>
You can't search LONGs directly. LONGs can't appear in the WHERE clause. They can appear in the SELECT list though so you can use that to narrow down the number of rows you'd have to examine.
Oracle has recommended converting LONGs to CLOBs for at least the past 2 releases. There are fewer restrictions on CLOBs.
Cross browser solution for printing pdf from base64 string:
.
const blobPdfFromBase64String = base64String => {
const byteArray = Uint8Array.from(
atob(base64String)
.split('')
.map(char => char.charCodeAt(0))
);
return new Blob([byteArray], { type: 'application/pdf' });
};
const isIE11 = !!(window.navigator && window.navigator.msSaveOrOpenBlob); // or however you want to check it
const printPDF = blob => {
try {
isIE11
? window.navigator.msSaveOrOpenBlob(blob, 'documents.pdf')
: printJS(URL.createObjectURL(blob)); // http://printjs.crabbly.com/
} catch (e) {
throw PDFError;
}
};
printPDF(blobPdfFromBase64String(base64String))
BONUS - Opening blob file in new tab for IE11
If you're able to do some preprocessing of the base64 string on the server you could expose it under some url and use the link in printJS
:)
Am going to try and add value to this very good question and to build on @BrittonKerin's question in one of the comments under @David Wolever's fantastic answer. Wanted to share here because I had the same challenge as @BrittonKerin and I got something working (i.e. just want to run a piece of code only IF the table doesn't exist).
# for completeness lets do the routine thing of connections and cursors
conn = sqlite3.connect(db_file, timeout=1000)
cursor = conn.cursor()
# get the count of tables with the name
tablename = 'KABOOM'
cursor.execute("SELECT count(name) FROM sqlite_master WHERE type='table' AND name=? ", (tablename, ))
print(cursor.fetchone()) # this SHOULD BE in a tuple containing count(name) integer.
# check if the db has existing table named KABOOM
# if the count is 1, then table exists
if cursor.fetchone()[0] ==1 :
print('Table exists. I can do my custom stuff here now.... ')
pass
else:
# then table doesn't exist.
custRET = myCustFunc(foo,bar) # replace this with your custom logic
In my case, I had 2 different test projects in the solution. Project 1 tests could be found, but Project 2 tests could not. I found that first Unloading the test Project 1, then closing VS > clearing my temp files > re-open solution > rebuild, allowed VS to discover my Project 2 tests.
I'm assuming something must be conflicting between the two test projects and this was the quickest way to get me up and running in a few minutes. The kinks can be worked out later :).
This is what worked for me:
KeyStore keyStore = KeyStore.getInstance("PKCS12");
FileInputStream instream = new FileInputStream(new File("client-p12-keystore.p12"));
try {
keyStore.load(instream, "password".toCharArray());
} finally {
instream.close();
}
// Trust own CA and all self-signed certs
SSLContext sslcontext = SSLContexts.custom()
.loadKeyMaterial(keyStore, "password".toCharArray())
//.loadTrustMaterial(trustStore, new TrustSelfSignedStrategy())
.build();
// Allow TLSv1 protocol only
SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
sslcontext,
new String[] { "TLSv1" },
null,
SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER); //TODO
CloseableHttpClient httpclient = HttpClients.custom()
.setHostnameVerifier(SSLConnectionSocketFactory.ALLOW_ALL_HOSTNAME_VERIFIER) //TODO
.setSSLSocketFactory(sslsf)
.build();
try {
HttpGet httpget = new HttpGet("https://localhost:8443/secure/index");
System.out.println("executing request" + httpget.getRequestLine());
CloseableHttpResponse response = httpclient.execute(httpget);
try {
HttpEntity entity = response.getEntity();
System.out.println("----------------------------------------");
System.out.println(response.getStatusLine());
if (entity != null) {
System.out.println("Response content length: " + entity.getContentLength());
}
EntityUtils.consume(entity);
} finally {
response.close();
}
} finally {
httpclient.close();
}
}
This code is a modified version of http://hc.apache.org/httpcomponents-client-4.3.x/httpclient/examples/org/apache/http/examples/client/ClientCustomSSL.java
I have python 2.7.13 and 3.6.2 both installed. Install Anaconda for python 3 first and then you can use conda syntax to get 2.7. My install used: conda create -n py27 python=2.7.13 anaconda
I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.
Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled
Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is
Here is the xmlns reference:
xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI"
Then the ad itself:
<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480" AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/>
I realize this is an older thread, but for future reference:
As of iPhone SDK 3.0, custom gradients can be implemented very easily, without subclassing or images, by using the new CAGradientLayer
:
UIView *view = [[[UIView alloc] initWithFrame:CGRectMake(0, 0, 320, 100)] autorelease];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = view.bounds;
gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor blackColor] CGColor], (id)[[UIColor whiteColor] CGColor], nil];
[view.layer insertSublayer:gradient atIndex:0];
Take a look at the CAGradientLayer docs. You can optionally specify start and end points (in case you don't want a linear gradient that goes straight from the top to the bottom), or even specific locations that map to each of the colors.
For the line
line.split()
What are you splitting on? Looks like a CSV, so try
line.split(',')
Example:
"one,two,three".split() # returns one element ["one,two,three"]
"one,two,three".split(',') # returns three elements ["one", "two", "three"]
As @TigerhawkT3 mentions, it would be better to use the CSV module. Incredibly quick and easy method available here.
I have had to resort to this, but this has issues with upkeep.
Function sheet_match(rng As Range) As String ' Converts Excel TAB names to the required VSB Sheetx names.
TABname = rng.Worksheet.Name ' Excel sheet TAB name, not VSB Sheetx name. Thanks, Bill Gates.
' Next, match this Excel sheet TAB name to the VSB Sheetx name:
Select Case TABname 'sheet_match
Case Is = "Sheet1": sheet_match = "Sheet1" ' You supply these relationships
Case Is = "Sheet2": sheet_match = "Sheet2"
Case Is = "TABnamed": sheet_match = "Sheet3" 'Re-named TAB
Case Is = "Sheet4": sheet_match = "Sheet4"
Case Is = "Sheet5": sheet_match = "Sheet5"
Case Is = "Sheet6": sheet_match = "Sheet6"
Case Is = "Sheet7": sheet_match = "Sheet7"
Case Is = "Sheet8": sheet_match = "Sheet8"
End Select
End Function
You can try this snippet
$("#your-id")[0].selectedIndex = -1
It worked for me.
=IF(X2>=85,0.559,IF(X2>=80,0.327,IF(X2>=75,0.255,-1)))
Explanation:
=IF(X2>=85, 'If the value is in the highest bracket
0.559, 'Use the appropriate number
IF(X2>=80, 'Otherwise, if the number is in the next highest bracket
0.327, 'Use the appropriate number
IF(X2>=75, 'Otherwise, if the number is in the next highest bracket
0.255, 'Use the appropriate number
-1 'Otherwise, we're not in any of the ranges (Error)
)
)
)
I did it in following way :
success: function (result) {
response($.map(result.d.slice(0,10), function (item) {
return {
// Mapping to Required columns (Employee Name and Employee No)
label: item.EmployeeName,
value: item.EmployeeNo
}
}
));
Addressing Vicky Ronnen's head up, considering the following code:
function use_global
{
eval "$1='changed using a global var'"
}
function capture_output
{
echo "always changed"
}
function test_inside_a_func
{
local _myvar='local starting value'
echo "3. $_myvar"
use_global '_myvar'
echo "4. $_myvar"
_myvar=$( capture_output )
echo "5. $_myvar"
}
function only_difference
{
local _myvar='local starting value'
echo "7. $_myvar"
local use_global '_myvar'
echo "8. $_myvar"
local _myvar=$( capture_output )
echo "9. $_myvar"
}
declare myvar='global starting value'
echo "0. $myvar"
use_global 'myvar'
echo "1. $myvar"
myvar=$( capture_output )
echo "2. $myvar"
test_inside_a_func
echo "6. $_myvar" # this was local inside the above function
only_difference
will give
0. global starting value
1. changed using a global var
2. always changed
3. local starting value
4. changed using a global var
5. always changed
6.
7. local starting value
8. local starting value
9. always changed
Maybe the normal scenario is to use the syntax used in the test_inside_a_func
function, thus you can use both methods in the majority of cases, although capturing the output is the safer method always working in any situation, mimicking the returning value from a function that you can find in other languages, as Vicky Ronnen
correctly pointed out.
It allows servlets to have multiple servlet mappings:
<servlet>
<servlet-name>Servlet1</servlet-name>
<servlet-path>foo.Servlet</servlet-path>
</servlet>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/enroll</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/pay</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>Servlet1</servlet-name>
<url-pattern>/bill</url-pattern>
</servlet-mapping>
It allows filters to be mapped on the particular servlet:
<filter-mapping>
<filter-name>Filter1</filter-name>
<servlet-name>Servlet1</servlet-name>
</filter-mapping>
Your proposal would support neither of them. Note that the web.xml
is read and parsed only once during application's startup, not on every HTTP request as you seem to think.
Since Servlet 3.0, there's the @WebServlet
annotation which minimizes this boilerplate:
@WebServlet("/enroll")
public class Servlet1 extends HttpServlet {
Old but relevant issue. I solved for 2012 by logging in to the reporting server and:
Can't say that I'm comfortable with this solution, but I needed something that worked and it worked. Hope this helps someone else.
We basically use user controls when we have to use similar functionality on different locations of an app. Like we use master pages for consistent look and feel of app, similarly to avoid repeating the same functionality and UI all over the app, we use usercontrols. There might me much more usage too, but I know this one only...
For example, let's say your site has 4 levels of users and for each user there are different pages under different directories with different access mechanisms. Say you are requesting address info for all users, then creating address fields like Street, City, State, Zip, etc on each page. That would be a repetitive job. Instead you can create it as an ascx file (ext for user control) and in this control put the necessary UI and business code for add/update/delete/select the address role wise and then simply reference it all required page.
So, thought user controls, one can avoid code repetition for each role and UI creation for each role.
For your example, Dirk's answer is perfect. If you instead had a data frame and wanted to add that sort of sequence as a column, you could also use group
from groupdata2 (disclaimer: my package) to greedily divide the datapoints into groups.
# Attach groupdata2
library(groupdata2)
# Create a random data frame
df <- data.frame("x" = rnorm(27))
# Create groups with 5 members each (except last group)
group(df, n = 5, method = "greedy")
x .groups
<dbl> <fct>
1 0.891 1
2 -1.13 1
3 -0.500 1
4 -1.12 1
5 -0.0187 1
6 0.420 2
7 -0.449 2
8 0.365 2
9 0.526 2
10 0.466 2
# … with 17 more rows
There's a whole range of methods for creating this kind of grouping factor. E.g. by number of groups, a list of group sizes, or by having groups start when the value in some column differs from the value in the previous row (e.g. if a column is c("x","x","y","z","z")
the grouping factor would be c(1,1,2,3,3)
.
ALTER TABLE <tablename> CHANGE COLUMN <colname> <colname> VARCHAR(65536);
You have to list the column name twice, even if you aren't changing its name.
Note that after you make this change, the data type of the column will be MEDIUMTEXT
.
Miky D is correct, the MODIFY
command can do this more concisely.
Re the MEDIUMTEXT
thing: a MySQL row can be only 65535 bytes (not counting BLOB/TEXT columns). If you try to change a column to be too large, making the total size of the row 65536 or greater, you may get an error. If you try to declare a column of VARCHAR(65536)
then it's too large even if it's the only column in that table, so MySQL automatically converts it to a MEDIUMTEXT
data type.
mysql> create table foo (str varchar(300));
mysql> alter table foo modify str varchar(65536);
mysql> show create table foo;
CREATE TABLE `foo` (
`str` mediumtext
) ENGINE=MyISAM DEFAULT CHARSET=latin1
1 row in set (0.00 sec)
I misread your original question, you want VARCHAR(65353)
, which MySQL can do, as long as that column size summed with the other columns in the table doesn't exceed 65535.
mysql> create table foo (str1 varchar(300), str2 varchar(300));
mysql> alter table foo modify str2 varchar(65353);
ERROR 1118 (42000): Row size too large.
The maximum row size for the used table type, not counting BLOBs, is 65535.
You have to change some columns to TEXT or BLOBs
If using Vagrant try reloading your box. This solved my issue.
You need to escape the braces:
git stash pop stash@\{1\}
Besides the way suggested in the "possible duplicate", the other main way of getting around this problem is for the array itself (or at least a template of one) to be supplied by the caller, who will hopefully know the concrete type and can thus safely create the array.
This is the way methods like ArrayList.toArray(T[])
are implemented. I'd suggest you take a look at that method for inspiration. Better yet, you should probably be using that method anyway as others have noted.
The other answers are correct, in that chmod -R 755
will set these permissions to all files and subfolders in the tree. But why on earth would you want to? It might make sense for the directories, but why set the execute bit on all the files?
I suspect what you really want to do is set the directories to 755 and either leave the files alone or set them to 644. For this, you can use the find
command. For example:
To change all the directories to 755 (drwxr-xr-x
):
find /opt/lampp/htdocs -type d -exec chmod 755 {} \;
To change all the files to 644 (-rw-r--r--
):
find /opt/lampp/htdocs -type f -exec chmod 644 {} \;
This is how I did it:
curl -v \
--key ./admin-key.pem \
--cert ./admin.pem \
https://xxxx/api/v1/
If you have access to ES2015 functions, and you're looking for a more functional approach I'd go with something like:
const people = [
{ id: 1, name: 'serdar' },
{ id: 5, name: 'alex' },
{ id: 300, name: 'brittany' }
];
const idToRemove = 5;
const filteredPeople = people.filter((item) => item.id !== idToRemove);
// [
// { id: 1, name: 'serdar' },
// { id: 300, name: 'brittany' }
// [
Watch out though, filter()
is non-mutating, so you'll get a new array back.
ECMAscript edition 5 also offers you the neat methods Object.keys()
and Object.getOwnPropertyNames()
.
So
Object.keys( buttons ); // ['button1', 'button2'];
You could use the Chr(int) function
Updated answer for 2019.
Regex object is thread-safe for Matching functions. Knowing that and there are some performance options or cultural / language issues, I propose this simple solution.
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Singleline);
public static bool IsValidEmailFormat(string emailInput)
{
return _regex.IsMatch(emailInput);
}
Alternative Configuration for Regex:
public static Regex _regex = new Regex(
@"^([a-zA-Z0-9_\-\.]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?)$",
RegexOptions.CultureInvariant | RegexOptions.Compiled);
I find that compiled is only faster on big string matches, like book parsing for example. Simple email matching is faster just letting Regex interpret.
%lu
for unsigned long%llu
for unsigned long longHere you have a very good tutorial, that explains, how to use the new grid classes in Bootstrap 3.
It also covers mixins etc.
A few line of java code.
public static void main(String args[]) throws Exception{
String str="test string";
MessageDigest messageDigest=MessageDigest.getInstance("MD5");
messageDigest.update(str.getBytes(),0,str.length());
System.out.println("MD5: "+new BigInteger(1,messageDigest.digest()).toString(16));
}
I like to use a dict to rename the df.
rename = {'old1': 'new1', 'old2': 'new2'}
for col in df.schema.names:
df = df.withColumnRenamed(col, rename[col])
When we do something like this obj[key] Typescript can't know for sure if that key exists in that object. What I did:
Object.entries(data).forEach(item => {
formData.append(item[0], item[1]);
});
@echo off
RD %TEMP%\. /S /Q
::pause
explorer %temp%
This batch can run from anywhere. RD stands for Remove Directory but this can remove both folders and files which available to delete.
You can write
i = 5 + tup()[0]
Tuples can be indexed just like lists.
The main difference between tuples and lists is that tuples are immutable - you can't set the elements of a tuple to different values, or add or remove elements like you can from a list. But other than that, in most situations, they work pretty much the same.
Edit
This answer is now deprecated. See the answer by apsillers.
Since this is for a Chrome extension, you might as well use the standard DOM event - DOMSubtreeModified
. See the support for this event across browsers. It has been supported in Chrome since 1.0.
$("#someDiv").bind("DOMSubtreeModified", function() {
alert("tree changed");
});
See a working example here.
For some reason none of the other solutions here worked for me. However, after a lot of troubleshooting, I finally arrived at this method which works perfectly (for me at least).
$('html').click(function(e) {
if( !$(e.target).parents().hasClass('popover') ) {
$('#popover_parent').popover('destroy');
}
});
In my case I was adding a popover to a table and absolutely positioning it above/below the td
that was clicked. The table selection was handled by jQuery-UI Selectable so I'm not sure if that was interfering. However whenever I clicked inside the popover my click handler which targeted $('.popover')
never worked and the event handling was always delegated to the $(html)
click handler. I'm fairly new to JS so perhaps I'm just missing something?
Anyways I hope this helps someone!
Primary key is a subset of super key. Which is uniquely define and other field are depend on it. In a table their can be just one primary key and rest sub set are candidate key or alternate keys.
There's always git describe
as well. By default it gives you --
john@eleanor:/dev/shm/mpd/ncmpc/pkg (master)$ git describe --always
release-0.19-11-g7a68a75
In Python 3 this can be done in 2 steps:
datetime
objectdatetime
object by 1000 to convert it to milliseconds.For example like this:
from datetime import datetime
dt_obj = datetime.strptime('20.12.2016 09:38:42,76',
'%d.%m.%Y %H:%M:%S,%f')
millisec = dt_obj.timestamp() * 1000
print(millisec)
Output:
1482223122760.0
strptime
accepts your timestring and a format string as input. The timestring (first argument) specifies what you actually want to convert to a datetime
object. The format string (second argument) specifies the actual format of the string that you have passed.
Here is the explanation of the format specifiers from the official documentation:
%d
- Day of the month as a zero-padded decimal number.%m
- Month as a zero-padded decimal number.%Y
- Year with century as a decimal number%H
- Hour (24-hour clock) as a zero-padded decimal number.%M
- Minute as a zero-padded decimal number.%S
- Second as a zero-padded decimal number.%f
- Microsecond as a decimal number, zero-padded on the left.matcher.find()
does what you needed. Example:
Pattern.compile("stores.*store.*product").matcher(someString).find();
Here's the Java code using registerDefaultNetworkCallback
(and registerNetworkCallback
for API < 24):
ConnectivityManager.NetworkCallback networkCallback = new ConnectivityManager.NetworkCallback() {
@Override
public void onAvailable(Network network) {
// network available
}
@Override
public void onLost(Network network) {
// network unavailable
}
};
ConnectivityManager connectivityManager =
(ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
connectivityManager.registerDefaultNetworkCallback(networkCallback);
} else {
NetworkRequest request = new NetworkRequest.Builder()
.addCapability(NetworkCapabilities.NET_CAPABILITY_INTERNET).build();
connectivityManager.registerNetworkCallback(request, networkCallback);
}
This regex matches any number with the common format 1-(999)-999-9999 and anything in between. Also, the regex will allow braces or no braces and separations with period, space or dash. "^([01][- .])?(\(\d{3}\)|\d{3})[- .]?\d{3}[- .]\d{4}$"
This is the best way I found for Proxy and not proxy users
RewriteEngine On
### START WWW & HTTPS
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
### END WWW & HTTPS
The method described in the accepted answer didn't work for me even after applying changes mentioned in its comments. But the below simple code worked:
import matplotlib.pyplot as plt
plt.imsave(filename, np_array, cmap='Greys')
np_array could be either a 2D array with values from 0..1 floats o2 0..255 uint8, and in that case it needs cmap. For 3D arrays, cmap will be ignored.
I am guessing you are using a 32 bit eclipse with 32 bit JVM. It wont allow heapsize above what you have specified.
Using a 64-bit Eclipse with a 64-bit JVM helps you to start up eclipse with much larger memory. (I am starting with -Xms1024m -Xmx4000m)
I had the same issue. It seems the easiest solution is to just remove the remote, readd it, and fetch.
Follow these steps
1>Download the *.jar file from here .
2>Put the *.jar file into the folder eclipse/dropins/ and Restart eclipse.
3>In the top right of eclipse, click the DDMS icon.
4>Select the proper emulator in the left panel.
5In the File Explorer tab on the main panel, go to /data/data/[YOUR.APP.NAMESPACE]/databases.
6>Underneath the DDMS icon, there should be a new blue icon of a Database light up when you select your database. Click it and you will see a Questoid Sqlite Manager tab open up to view your data.
*Note: If the database doesn't light up, it may be because your database doesn't have a *.db file extension. Be sure your database is called [DATABASE_NAME].db
*Note: if you want to use a DB without .db-Extension:
-Download this Questoid SqLiteBrowser: Download fro here.
-Unzip and put it into eclipse/dropins (not Plugins).
-Check this for more information Click here.
Just add a background image to all images using css:
img {
background: url('loading.gif') no-repeat;
}
Pink ip Address
public static int pingHost(String host, int timeout) throws IOException,
InterruptedException {
Runtime runtime = Runtime.getRuntime();
timeout /= 1000;
String cmd = "ping -c 1 -W " + timeout + " " + host;
Process proc = runtime.exec(cmd);
Log.d(TAG, cmd);
proc.waitFor();
int exit = proc.exitValue();
return exit;
}
Ping a host and return an int value of 0 or 1 or 2 0=success, 1=fail,
* 2=error
Ask this questions yourself? And you will decide your DB selection.
Thanks to John Magnolia. This is my postForm function that I am using in my Symfony projects and it is fine now to work with CK Editor.
function postForm($form, callback)
{
// Get all form values
var values = {};
var fields = {};
for(var instanceName in CKEDITOR.instances){
CKEDITOR.instances[instanceName].updateElement();
}
$.each($form.serializeArray(), function(i, field) {
values[field.name] = field.value;
});
// Throw the form values to the server!
$.ajax({
type : $form.attr('method'),
url : $form.attr('action'),
data : values,
success : function(data) {
callback( data );
}
});
Just a supplement here.
The following question is that what if I want more subplots in the figure?
As mentioned in the Doc, we can use fig = plt.subplots(nrows=2, ncols=2)
to set a group of subplots with grid(2,2) in one figure object.
Then as we know, the fig, ax = plt.subplots()
returns a tuple, let's try fig, ax1, ax2, ax3, ax4 = plt.subplots(nrows=2, ncols=2)
firstly.
ValueError: not enough values to unpack (expected 4, got 2)
It raises a error, but no worry, because we now see that plt.subplots()
actually returns a tuple with two elements. The 1st one must be a figure object, and the other one should be a group of subplots objects.
So let's try this again:
fig, [[ax1, ax2], [ax3, ax4]] = plt.subplots(nrows=2, ncols=2)
and check the type:
type(fig) #<class 'matplotlib.figure.Figure'>
type(ax1) #<class 'matplotlib.axes._subplots.AxesSubplot'>
Of course, if you use parameters as (nrows=1, ncols=4), then the format should be:
fig, [ax1, ax2, ax3, ax4] = plt.subplots(nrows=1, ncols=4)
So just remember to keep the construction of the list as the same as the subplots grid we set in the figure.
Hope this would be helpful for you.
You can implement error-specific logic as follows:
error: function (XMLHttpRequest, textStatus, errorThrown) {
if (textStatus == 'Unauthorized') {
alert('custom message. Error: ' + errorThrown);
} else {
alert('custom message. Error: ' + errorThrown);
}
}
As all of these comments are true, you should note that as far as ICANN approved Arabic (Persian) and Chinese characters to be registered as Domain Name, all of the browser-making companies (Microsoft, Mozilla, Apple, etc.) have to support Unicode in URLs without any encoding, and those should be searchable by Google, etc.
So this issue will resolve ASAP.
Above Answers are correct. I faced an different issue where in HTC M8 my application crashes when selecting an image from gallery. I'm getting null value for image path. I fixed and optimized with the following solution. in onActivityResult method
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if ((requestCode == RESULT_LOAD_IMAGE) && (resultCode == RESULT_OK)) {
if (data != null) {
Uri selectedImageUri = null;
selectedImageUri = data.getData();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor imageCursor = mainActivity.getContentResolver().query(
selectedImageUri, filePathColumn, null, null, null);
if (imageCursor == null) {
return;
}
imageCursor.moveToFirst();
int columnIndex = imageCursor.getColumnIndex(filePathColumn[0]);
picturePath = imageCursor.getString(columnIndex);
if (picturePath == null) {
picturePath = selectedImageUri.getPath();
String wholeID = DocumentsContract
.getDocumentId(selectedImage);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
String[] column = { MediaStore.Images.Media.DATA };
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
Cursor cursor = mainActivity.getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
column, sel, new String[] { id }, null);
columnIndex = cursor.getColumnIndex(column[0]);
if (cursor.moveToFirst()) {
picturePath = cursor.getString(columnIndex);
}
cursor.close();
}
picturePathAbs = new File(picturePath).getAbsolutePath();
imageCursor.close();
}
}
For just one run (from the unix shell prompt):
$ PORT=1234 node app.js
More permanently:
$ export PORT=1234
$ node app.js
In Windows:
set PORT=1234
In Windows PowerShell:
$env:PORT = 1234
Try this: add white-space: normal; to the style definition of the Bootstrap Button or you can replace the code you displayed with the one below
<div class="col-lg-3"> <!-- FIRST COL -->
<div class="panel panel-default">
<div class="panel-body">
<h4>Posted on</h4>
<p>22nd September 2013</p>
<h4>Tags</h4>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
<a href="#" class="btn btn-primary btn-xs col-lg-12" style="margin-bottom:4px;white-space: normal;">Lorem ipsum dolor sit amet, consectetur adipiscing elit.</a>
</div>
</div>
</div>
I have updated your fiddle here to show how it comes out.
I think what you are looking for is to keep the background image fixed and just move the content on scroll. For that you have to simply use the following css property :
background-attachment: fixed;
I'm constantly running into this problem. Make sure you set git --config user.name "" and not your real name, which I've done a few times..
Solution: In order to increase your buffer history on iterm bash terminal you've got two options:
Go to iterm -> Preferences -> Profiles -> Terminal Tab -> Scrollback Buffer (section)
Option 1. select the checkbox Unlimited scrollback
Option 2. type the selected Scrollback lines
numbers you'd like your terminal buffer to cache (See image below)
If you are using WAMP on you local computer (mysql version 5.7.14) Step 1: open my.ini file Step 2: un-comment this line 'skip-grant-tables' by removing the semi-colon step 3: restart mysql server step 4: launch mySQL console step 5:
UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';
FLUSH PRIVILEGES;
Step 6: Problem solved!!!!
add the activity in your manifest file
<activity android:name=".OrderScreen" />
dir(sys)
says no. len(sys.argv)
works, but in Python it is better to ask for forgiveness than permission, so
#!/usr/bin/python
import sys
try:
in_file = open(sys.argv[1], "r")
except:
sys.exit("ERROR. Can't read supplied filename.")
text = in_file.read()
print(text)
in_file.close()
works fine and is shorter.
If you're going to exit anyway, this would be better:
#!/usr/bin/python
import sys
text = open(sys.argv[1], "r").read()
print(text)
I'm using print()
so it works in 2.7 as well as Python 3.
It seems that the struct
datatype is commonly used in SOAP:
var_dump($client->__getTypes());
array(52) {
[0] =>
string(43) "struct Bank {\n string Code;\n string Name;\n}"
}
This is not a native PHP datatype!
It seems that the properties of the struct
type referred to in SOAP can be accessed as a simple PHP stdClass
object:
$some_struct = $client->SomeMethod();
echo 'Name: ' . $some_struct->Name;
From another search. Worked for me!
"You can use Visual Studio 2010 and it does support it, provided your OS supports .NET 4.5.
Right click on your solution to add a reference (as you do). When the dialog box shows, select browse, then navigate to the following folder:
C:\Program Files(x86)\Reference Assemblies\Microsoft\Framework\.Net Framework\4.5
You will find it there."
I wanted a splash screen that would display until the main program form was ready to be displayed, so timers etc were no use to me. I also wanted to keep it as simple as possible. My application starts with (abbreviated):
static void Main()
{
Splash frmSplash = new Splash();
frmSplash.Show();
Application.Run(new ReportExplorer(frmSplash));
}
Then, ReportExplorer has the following:
public ReportExplorer(Splash frmSplash)
{
this.frmSplash = frmSplash;
InitializeComponent();
}
Finally, after all the initialisation is complete:
if (frmSplash != null)
{
frmSplash.Close();
frmSplash = null;
}
Maybe I'm missing something, but this seems a lot easier than mucking about with threads and timers.
You can also setup multiple domain with nginx, forwarding to multiple node.js processes.
For example to achieve these:
These ports (4000 and 5000) should be used to listen the app requests in your app code.
/etc/nginx/sites-enabled/domain1
server {
listen 80;
listen [::]:80;
server_name domain1.com;
access_log /var/log/nginx/domain1.access.log;
location / {
proxy_pass http://127.0.0.1:4000/;
}
}
In /etc/nginx/sites-enabled/domain2
server {
listen 80;
listen [::]:80;
server_name domain2.com;
access_log /var/log/nginx/domain2.access.log;
location / {
proxy_pass http://127.0.0.1:5000/;
}
}
If you want to achieve this (you can resize the window to see how it will look for mobile version), all you have to do is to have 2 logo images (1 for desktop and one for mobile) and display them depending of the enviroment using visible-xs
and hidden-xs
classes.
So i used something like this:
<img class="hidden-xs" src="http://placehold.it/150x50&text=Logo" alt="">
<img class="visible-xs" src="http://placehold.it/120x40&text=Logo" alt="">
And ofcourse, i styled the mobile logo using:
@media (max-width: 767px) {
.navbar-brand {
padding: 0;
}
.navbar-brand img {
margin-top: 5px;
margin-left: 5px;
}
}
You can see all the code here. In case you need a text on mobile version insted of the logo, it's not a big deal. Just replace the logo with a <h1 class="visible-xs">AppName</h3>
and change the style inside the media query like this:
@media (max-width: 767px) {
.navbar-brand {
padding: 0;
}
.navbar-brand h1{
//here add your style depending of the position you want the text to be placed
}
}
EDIT:
You need this conditions to make it work:
.navbar-toggle {
margin: 23px 0;
}
.navbar-nav, .navbar-nav li, .navbar-nav li a {
height: 80px;
line-height: 80px;
}
.navbar-nav li a {
padding-top: 0;
padding-bottom:0;
}
You could also use:
<body onload="focusOnInput()">
<form name="passwordForm" action="verify.php" method="post">
<input name="passwordInput" type="password" />
</form>
</body>
And then in your JavaScript:
function focusOnInput() {
document.forms["passwordForm"]["passwordInput"].focus();
}
XMLHttpRequest, i.e. AJAX, without the XML.
The precise manner you do this is dependent on what JavaScript framework you're using, but if we disregard interoperability issues, your code will look something like:
var client = new XMLHttpRequest(); client.open('GET', '/foo.txt'); client.onreadystatechange = function() { alert(client.responseText); } client.send();
Normally speaking, though, XMLHttpRequest isn't available on all platforms, so some fudgery is done. Once again, your best bet is to use an AJAX framework like jQuery.
One extra consideration: this will only work as long as foo.txt is on the same domain. If it's on a different domain, same-origin security policies will prevent you from reading the result.
I have something that seems to me has a bit more order:
import boto3
from pprint import pprint
from botocore.exceptions import NoCredentialsError
class S3(object):
BUCKET = "test"
connection = None
def __init__(self):
try:
vars = get_s3_credentials("aws")
self.connection = boto3.resource('s3', 'aws_access_key_id',
'aws_secret_access_key')
except(Exception) as error:
print(error)
self.connection = None
def upload_file(self, file_to_upload_path, file_name):
if file_to_upload is None or file_name is None: return False
try:
pprint(file_to_upload)
file_name = "your-folder-inside-s3/{0}".format(file_name)
self.connection.Bucket(self.BUCKET).upload_file(file_to_upload_path,
file_name)
print("Upload Successful")
return True
except FileNotFoundError:
print("The file was not found")
return False
except NoCredentialsError:
print("Credentials not available")
return False
There're three important variables here, the BUCKET const, the file_to_upload and the file_name
BUCKET
: is the name of your S3 bucket
file_to_upload_path
: must be the path from file you want to upload
file_name
: is the resulting file and path in your bucket (this is where you add folders or what ever)
There's many ways but you can reuse this code in another script like this
import S3
def some_function():
S3.S3().upload_file(path_to_file, final_file_name)
Since mobile doesn't give hover feedback, I want, as a user, to see instant feedback when a link is tapped. I noticed that -webkit-tap-highlight-color
is the fastest to respond (subjective).
Add the following to your body and your links will have a tap effect.
body {
-webkit-tap-highlight-color: #ccc;
}
Another option would be to use join
var mystr = "Matayoshi";
mystr = ["Mariano", mystr].join(' ');
I think this drop shadow value is good for most cases:
<solid android:color="#20000000" />
Check out this plunkr.
When you're binding to variables, you need to use the brackets. Also, you use the hashtag when you want to get references to elements in your html, not for declaring variables inside of templates like that.
<md-button-toggle *ngFor="let indicador of indicadores; let first = first;" [value]="indicador.id" [checked]="first">
...
Edit: Thanks to Christopher Moore: Angular exposes the following local variables:
index
first
last
even
odd
class Aeroplane : IFlyable, IFuelable, IMachine
{ // Aeroplane's Design says:
// Aeroplane is a flying object
// Aeroplane can be fueled
// Aeroplane is a Machine
}
// But the code related to Pilot, or Driver of Aeroplane is not bothered
// about Machine or Fuel. Hence,
// pilot code:
IFlyable flyingObj = new Aeroplane();
flyingObj.Fly();
// fighter Pilot related code
IFlyable flyingObj2 = new FighterAeroplane();
flyingObj2.Fly();
// UFO related code
IFlyable ufoObj = new UFO();
ufoObj.Fly();
// **All the 3 Above codes are genaralized using IFlyable,
// Interface Abstraction**
// Fly related code knows how to fly, irrespective of the type of
// flying object they are.
// Similarly, Fuel related code:
// Fueling an Aeroplane
IFuelable fuelableObj = new Aeroplane();
fuelableObj.FillFuel();
// Fueling a Car
IFuelable fuelableObj2 = new Car(); // class Car : IFuelable { }
fuelableObj2.FillFuel();
// ** Fueling code does not need know what kind of vehicle it is, so far
// as it can Fill Fuel**
if you return var-binary data from DB to display PDF on popup or browser means follow this code:-
View page:
@using (Html.BeginForm("DisplayPDF", "Scan", FormMethod.Post))
{
<a href="javascript:;" onclick="document.forms[0].submit();">View PDF</a>
}
Scan controller:
public ActionResult DisplayPDF()
{
byte[] byteArray = GetPdfFromDB(4);
MemoryStream pdfStream = new MemoryStream();
pdfStream.Write(byteArray, 0, byteArray.Length);
pdfStream.Position = 0;
return new FileStreamResult(pdfStream, "application/pdf");
}
private byte[] GetPdfFromDB(int id)
{
#region
byte[] bytes = { };
string constr = System.Configuration.ConfigurationManager.ConnectionStrings["Connection"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
cmd.CommandText = "SELECT Scan_Pdf_File FROM PWF_InvoiceMain WHERE InvoiceID=@Id and Enabled = 1";
cmd.Parameters.AddWithValue("@Id", id);
cmd.Connection = con;
con.Open();
using (SqlDataReader sdr = cmd.ExecuteReader())
{
if (sdr.HasRows == true)
{
sdr.Read();
bytes = (byte[])sdr["Scan_Pdf_File"];
}
}
con.Close();
}
}
return bytes;
#endregion
}
Let's see how we get the params, headers and body in Flask. I'm gonna explain with the help of postman.
The params keys and values are reflected in the API endpoint. for example key1 and key2 in the endpoint : https://127.0.0.1/upload?key1=value1&key2=value2
from flask import Flask, request
app = Flask(__name__)
@app.route('/upload')
def upload():
key_1 = request.args.get('key1')
key_2 = request.args.get('key2')
print(key_1)
#--> value1
print(key_2)
#--> value2
After params, let's now see how to get the headers:
header_1 = request.headers.get('header1')
header_2 = request.headers.get('header2')
print(header_1)
#--> header_value1
print(header_2)
#--> header_value2
Now let's see how to get the body
file_name = request.files['file'].filename
ref_id = request.form['referenceId']
print(ref_id)
#--> WWB9838yb3r47484
so we fetch the uploaded files with request.files and text with request.form
Bit late but hopefully can still be useful to someone.
2 steps to adding items to a specific position in an ArrayList
add
null items to a specific index in an ArrayList
Then set
the positions as and when required.
list = new ArrayList();//Initialise the ArrayList
for (Integer i = 0; i < mItems.size(); i++) {
list.add(i, null); //"Add" all positions to null
}
// "Set" Items
list.set(position, SomeObject);
This way you don't have redundant items in the ArrayList
i.e. if you were to add items such as,
list = new ArrayList(mItems.size());
list.add(position, SomeObject);
This would not overwrite existing items in the position merely, shifting existing ones to the right by one - so you have an ArrayList with twice as many indicies.
You can enable the CURLOPT_VERBOSE
option and log that information to a (temporary) CURLOPT_STDERR
:
// CURLOPT_VERBOSE: TRUE to output verbose information. Writes output to STDERR,
// or the file specified using CURLOPT_STDERR.
curl_setopt($handle, CURLOPT_VERBOSE, true);
$verbose = fopen('php://temp', 'w+');
curl_setopt($handle, CURLOPT_STDERR, $verbose);
You can then read it after curl has done the request:
$result = curl_exec($handle);
if ($result === FALSE) {
printf("cUrl error (#%d): %s<br>\n", curl_errno($handle),
htmlspecialchars(curl_error($handle)));
}
rewind($verbose);
$verboseLog = stream_get_contents($verbose);
echo "Verbose information:\n<pre>", htmlspecialchars($verboseLog), "</pre>\n";
(I originally answered similar but more extended in a related question.)
More information like metrics about the last request is available via curl_getinfo
. This information can be useful for debugging curl requests, too. A usage example, I would normally wrap that into a function:
$version = curl_version();
extract(curl_getinfo($handle));
$metrics = <<<EOD
URL....: $url
Code...: $http_code ($redirect_count redirect(s) in $redirect_time secs)
Content: $content_type Size: $download_content_length (Own: $size_download) Filetime: $filetime
Time...: $total_time Start @ $starttransfer_time (DNS: $namelookup_time Connect: $connect_time Request: $pretransfer_time)
Speed..: Down: $speed_download (avg.) Up: $speed_upload (avg.)
Curl...: v{$version['version']}
EOD;
As a late corolloary to the earlier answers here, you probably end up in situations where you want some but not all variables to be interpolated. You can solve that by using backslashes to escape dollar signs and backticks; or you can put the static text in a variable.
Name='Rich Ba$tard'
dough='$$$dollars$$$'
cat <<____HERE
$Name, you can win a lot of $dough this week!
Notice that \`backticks' need escaping if you want
literal text, not `pwd`, just like in variables like
\$HOME (current value: $HOME)
____HERE
Demo: https://ideone.com/rMF2XA
Note that any of the quoting mechanisms -- \____HERE
or "____HERE"
or '____HERE'
-- will disable all variable interpolation, and turn the here-document into a piece of literal text.
A common task is to combine local variables with script which should be evaluated by a different shell, programming language, or remote host.
local=$(uname)
ssh -t remote <<:
echo "$local is the value from the host which ran the ssh command"
# Prevent here doc from expanding locally; remote won't see backslash
remote=\$(uname)
# Same here
echo "\$remote is the value from the host we ssh:ed to"
:
Use LINQ and add the condition on the "selected" as a question mark condition.
var listSiteId = (from site in db.GetSiteId().ToList()
select new SelectListItem
{
Value = site.SITEID,
Text = site.NAME,
Selected = (dimension.DISPLAYVALUE == site.SITEID) ? true : false,
}).ToList();
ViewBag.SiteId = listSiteId;
No, it's not the script, it's the fact that your script is not executed by Python at all. If your script is stored in a file named script.py
, you have to execute it as python script.py
, otherwise the default shell will execute it and it will bail out at the from
keyword. (Incidentally, from
is the name of a command line utility which prints names of those who have sent mail to the given username, so that's why it tries to access the mailboxes).
Another possibility is to add the following line to the top of the script:
#!/usr/bin/env python
This will instruct your shell to execute the script via python
instead of trying to interpret it on its own.
For Python 2:
pip install rglob
Then do
import rglob
file_list = rglob.rglob("/home/base/dir/", "*")
print file_list
You need to get the mouse position relative to the canvas
To do that you need to know the X/Y position of the canvas on the page.
This is called the canvas’s “offset”, and here’s how to get the offset. (I’m using jQuery in order to simplify cross-browser compatibility, but if you want to use raw javascript a quick Google will get that too).
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
Then in your mouse handler, you can get the mouse X/Y like this:
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
}
Here is an illustrating code and fiddle that shows how to successfully track mouse events on the canvas:
http://jsfiddle.net/m1erickson/WB7Zu/
<!doctype html>
<html>
<head>
<link rel="stylesheet" type="text/css" media="all" href="css/reset.css" /> <!-- reset css -->
<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<style>
body{ background-color: ivory; }
canvas{border:1px solid red;}
</style>
<script>
$(function(){
var canvas=document.getElementById("canvas");
var ctx=canvas.getContext("2d");
var canvasOffset=$("#canvas").offset();
var offsetX=canvasOffset.left;
var offsetY=canvasOffset.top;
function handleMouseDown(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#downlog").html("Down: "+ mouseX + " / " + mouseY);
// Put your mousedown stuff here
}
function handleMouseUp(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#uplog").html("Up: "+ mouseX + " / " + mouseY);
// Put your mouseup stuff here
}
function handleMouseOut(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#outlog").html("Out: "+ mouseX + " / " + mouseY);
// Put your mouseOut stuff here
}
function handleMouseMove(e){
mouseX=parseInt(e.clientX-offsetX);
mouseY=parseInt(e.clientY-offsetY);
$("#movelog").html("Move: "+ mouseX + " / " + mouseY);
// Put your mousemove stuff here
}
$("#canvas").mousedown(function(e){handleMouseDown(e);});
$("#canvas").mousemove(function(e){handleMouseMove(e);});
$("#canvas").mouseup(function(e){handleMouseUp(e);});
$("#canvas").mouseout(function(e){handleMouseOut(e);});
}); // end $(function(){});
</script>
</head>
<body>
<p>Move, press and release the mouse</p>
<p id="downlog">Down</p>
<p id="movelog">Move</p>
<p id="uplog">Up</p>
<p id="outlog">Out</p>
<canvas id="canvas" width=300 height=300></canvas>
</body>
</html>
In JSF I used:
<h:head>
<f:facet name="first">
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
</f:facet>
<!-- ... other meta tags ... -->
</h:head>
I use the following shell script for such purposes:
#!/bin/bash
for fld in $(find -name "CMakeLists.txt" -printf '%h ')
do
for cmakefile in CMakeCache.txt cmake_install.cmake CTestTestfile.cmake CMakeFiles Makefile
do
rm -rfv $fld/$cmakefile
done
done
If you are using Windows then use Cygwin for this script.
As per the Django Project Skeleton, the proper directory structure that could be followed is :
[projectname]/ <- project root
+-- [projectname]/ <- Django root
¦ +-- __init__.py
¦ +-- settings/
¦ ¦ +-- common.py
¦ ¦ +-- development.py
¦ ¦ +-- i18n.py
¦ ¦ +-- __init__.py
¦ ¦ +-- production.py
¦ +-- urls.py
¦ +-- wsgi.py
+-- apps/
¦ +-- __init__.py
+-- configs/
¦ +-- apache2_vhost.sample
¦ +-- README
+-- doc/
¦ +-- Makefile
¦ +-- source/
¦ +-- *snap*
+-- manage.py
+-- README.rst
+-- run/
¦ +-- media/
¦ ¦ +-- README
¦ +-- README
¦ +-- static/
¦ +-- README
+-- static/
¦ +-- README
+-- templates/
+-- base.html
+-- core
¦ +-- login.html
+-- README
Refer https://django-project-skeleton.readthedocs.io/en/latest/structure.html for the latest directory structure.
This works for me
msg.BodyFormat = MailFormat.Html;
and then you can use html in your body
msg.Body = "<em>It's great to use HTML in mail!!</em>"
jQuery
provides $(window).resize()
function by default:
<script type="text/javascript">
// function for resize of div/span elements
var $window = $( window ),
$rightPanelData = $( '.rightPanelData' )
$leftPanelData = $( '.leftPanelData' );
//jQuery window resize call/event
$window.resize(function resizeScreen() {
// console.log('window is resizing');
// here I am resizing my div class height
$rightPanelData.css( 'height', $window.height() - 166 );
$leftPanelData.css ( 'height', $window.height() - 236 );
});
</script>
i am assuming you will display 10 data in every page
HTML:-
<!DOCTYPE html>
<html>
<head>
<title>pagination</title>
<link rel="stylesheet" href="pathofcssfile.css">
</head>
<body>
<div>
<table id="user"></table>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<ul>
<li value="1">1</li>
<li value="2">2</li>
<li value="3">3</li>
<li value="4">4</li>
<li value="5">5</li>
<li value="6">6</li>
<li value="7">7</li>
<li value="8">8</li>
<li value="9">9</li>
<li value="10">10</li>
</ul>
<script src="pathnameofjsfile.js" type="text/javascript"></script>
</body>
</html>
JS:-
var xhr = new XMLHttpRequest();
xhr.open('GET',"https://jsonplaceholder.typicode.com/albums",true);
xhr.send();
var udata;
xhr.onload = function()
{
if(this.status == 200)
{
var userdata = JSON.parse(this.responseText);
console.log(userdata);
udata = userdata;
data(1);
}
}
$("li").click(function ()
{
var a = $(this).attr("value");
console.log("value li "+ a);
data(a);
});
function data(a)
{
var output = "";
for(i=((a-1)*10);i<(a*10);i++)
{
output +='<tr>'+
'<td>'+ udata[i].userId + '</td>'+
'<td>'+ udata[i].id + '</td>'+
'<td>'+ udata[i].title + '</td>'+ '<br>'
'</tr>';
}
document.getElementById('user').innerHTML = output;
}
CSS:-
ul{
display: flex;
list-style-type:none;
padding: 20px;
}
li{
padding: 20px;
}
td,tr{
padding: 10px;
}
Assume that you have dynamic currency precision
value => 1.002431
currency precision => 3
`result => 1.002
CAST(Floor(your_float_value) AS VARCHAR) + '.' + REPLACE(STR(FLOOR((your_float_value FLOOR(your_float_value)) * power(10,cu_precision)), cu_precision), SPACE(1), '0')
It's pretty pointless to return a const
value from a function.
It's difficult to get it to have any effect on your code:
const int foo() {
return 3;
}
int main() {
int x = foo(); // copies happily
x = 4;
}
and:
const int foo() {
return 3;
}
int main() {
foo() = 4; // not valid anyway for built-in types
}
// error: lvalue required as left operand of assignment
Though you can notice if the return type is a user-defined type:
struct T {};
const T foo() {
return T();
}
int main() {
foo() = T();
}
// error: passing ‘const T’ as ‘this’ argument of ‘T& T::operator=(const T&)’ discards qualifiers
it's questionable whether this is of any benefit to anyone.
Returning a reference is different, but unless Object
is some template parameter, you're not doing that.
import Cocoa
class ViewController: NSViewController{
override func viewDidLoad() {
super.viewDidLoad()
self.view.wantsLayer = true
self.view.layer?.backgroundColor = NSColor(hexString: "#4d9b48").cgColor
}
extension NSColor {
convenience init(hexString: String, alpha: CGFloat = 1.0) {
let hexString: String = hexString.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
let scanner = Scanner(string: hexString)
if (hexString.hasPrefix("#")) {
scanner.scanLocation = 1
}
var color: UInt32 = 0
scanner.scanHexInt32(&color)
let mask = 0x000000FF
let r = Int(color >> 16) & mask
let g = Int(color >> 8) & mask
let b = Int(color) & mask
let red = CGFloat(r) / 255.0
let green = CGFloat(g) / 255.0
let blue = CGFloat(b) / 255.0
self.init(red:red, green:green, blue:blue, alpha:alpha)
}
func toHexString() -> String {
var r:CGFloat = 0
var g:CGFloat = 0
var b:CGFloat = 0
var a:CGFloat = 0
getRed(&r, green: &g, blue: &b, alpha: &a)
let rgb:Int = (Int)(r*255)<<16 | (Int)(g*255)<<8 | (Int)(b*255)<<0
return String(format:"#%06x", rgb)
}
}
Another option is to update the Microsoft.AspnNet.Mvc NuGet package. Be careful, because NuGet update does not update the Web.Config. You should update all previous version numbers to updated number. For example if you update from asp.net MVC 4.0.0.0 to 5.0.0.0, then this should be replaced in the Web.Config:
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages
validateRequest="false"
pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"
userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
Your piece of script works just great. Are you sure you are not assigning anything else before the if to "i"?
A common mistake is also not to leave a space after and before the square brackets.
In most cases simply switching the virtual machine network adapter to bridged mode is enough to make the guest machine accessible from outside.
Sometimes it's possible for the guest machine to not automatically receive an IP which matches the host's IP range after switching to bridged mode (even after rebooting the guest machine). This is often caused by a malfunctioning or badly configured DHCP on the host network.
For example, if the host IP is 192.168.1.1
the guest machine needs to have an IP in the format 192.168.1.*
where only the last group of numbers is allowed to be different from the host IP.
You can use a terminal (shell) and type ifconfig
(ipconfig
for Windows guests) to check what IP is assigned to the guest machine and change it if required.
If the host and guest IPs do not match simply setting a static IP for the guest machine explicitly should resolve the issue.
window.location.replace('http://sidanmor.com');
It's better than using window.location.href = 'http://sidanmor.com';
Using replace()
is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
window.location.href
If you want to simulate an HTTP redirect, use
window.location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");
// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
Taken from here: How to redirect to another page in jQuery?
I'd recommend using std::vector: something like
typedef std::vector<int> A;
typedef std::vector<A> AS;
There's nothing wrong with the slight overkill of STL, and you'll be able to spend more time implementing the specific features of your app instead of reinventing the bicycle.
Download and install Eclipse, and you're good to go.
http://www.eclipse.org/downloads/
Apple provides its own version of Java, so make sure it's up-to-date.
http://developer.apple.com/java/download/
Eclipse is an integrated development environment. It has many features, but the ones that are relevant for you at this stage is:
As you gain more experience, you'll start to appreciate the rest of its rich set of features.
Given
volumes:
- /dir/on/host:/var/www/html
if /dir/on/host
doesn't exist, it is created on the host and the empty content is mounted in the container at /var/www/html
. Whatever content you had before in /var/www/html
inside the container is inaccessible, until you unmount the volume; the new mount is hiding the old content.
I had to include -lmysqlcppconn to my build in order to get it to work.
You could do $stmt->queryString
to obtain the SQL query used in the statement. If you want to save the entire $stmt variable (I can't see why), you could just copy it. It is an instance of PDOStatement so there is apparently no advantage in storing it.
try:
SELECT first_name + ISNULL(' '+last_name, '') AS Name FROM dbo.person
This adds the space to the last name, if it is null, the entire space+last name goes to NULL and you only get a first name, otherwise you get a firts+space+last name.
this will work as long as the default setting for concatenation with null strings is set:
SET CONCAT_NULL_YIELDS_NULL ON
this shouldn't be a concern since the OFF
mode is going away in future versions of SQl Server
Some times this problem arise when Application is build in one PC and try to run another PC. And also build the application with Visual Studio 2010.I have the following problem
Problem Description
Stop Working
Problem Signature
Problem Event Name: CLR20r3
Problem Signature 01: diagnosticcentermngr.exe
Problem Signature 02: 1.0.0.0
Problem Signature 03: 4f8c1772
Problem Signature 04: System.Drawing
Problem Signature 05: 2.0.0.0
Problem Signature 06: 4a275e83
Problem Signature 07: 7af
Problem Signature 08: 6c
Problem Signature 09: System.ArgumentException
OS Version: 6.1.7600.2.0.0.256.1
Locale ID: 1033
Read our privacy statement online:
http://go.microsoft.com/fwlink/?linkid=104288&clcid=0x0409
If the online privacy statement is not available, please read our privacy statement offline:
C:\Windows\system32\en-US\erofflps.txt
Dont worry, Please check out following link and install .net framework 4.Although my application .net properties was .net framework 2.
http://www.microsoft.com/download/en/details.aspx?id=17718
restart your PC and try again.
Old post I know, but using Select(x => x)
can be useful to split the EF Core (or even just Linq) expression up into a query builder.
This is handy for adding dynamic conditions.
For example:
public async Task<User> GetUser(Guid userId, string userGroup, bool noTracking = false)
{
IQueryable<User> queryable = _context.Users.Select(x => x);
if(!string.IsNullOrEmpty(userGroup))
queryable = queryable.Where(x => x.UserGroup == userGroup);
if(noTracking)
queryable = queryable.AsNoTracking();
return await queryable.FirstOrDefaultAsync(x => x.userId == userId);
}
Your solution is here but instead of addition you need to use subtraction
c.add(Calendar.MONTH, -1);
Then you can call getter on the Calendar
to acquire proper fields
int month = c.get(Calendar.MONTH) + 1; // beware of month indexing from zero
int year = c.get(Calendar.YEAR);
The following should work:
public static void main(String[] args)
{
final String title = "Test Window";
final int width = 1200;
final int height = width / 16 * 9;
//Creating the frame.
JFrame frame = new JFrame(title);
frame.setSize(width, height);
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
frame.setLocationRelativeTo(null);
frame.setResizable(false);
frame.setVisible(true);
//Creating the canvas.
Canvas canvas = new Canvas();
canvas.setSize(width, height);
canvas.setBackground(Color.BLACK);
canvas.setVisible(true);
canvas.setFocusable(false);
//Putting it all together.
frame.add(canvas);
canvas.createBufferStrategy(3);
boolean running = true;
BufferStrategy bufferStrategy;
Graphics graphics;
while (running) {
bufferStrategy = canvas.getBufferStrategy();
graphics = bufferStrategy.getDrawGraphics();
graphics.clearRect(0, 0, width, height);
graphics.setColor(Color.GREEN);
graphics.drawString("This is some text placed in the top left corner.", 5, 15);
bufferStrategy.show();
graphics.dispose();
}
}
Indeed SET TEST_VARIABLE=value works for current process only, so SETX
is required. A quick example for permanently storing an environment variable at user level.
SETX TEST_VARIABLE etc
. Not applied yet (echo %TEST_VARIABLE%
shows %TEST_VARIABLE%
,echo %TEST_VARIABLE%
shows etc
.etc
.There is no direct method to draw a triangle.
You can use drawPolygon() method for this.
It takes three parameters in the following form:
drawPolygon(int x[],int y[], int number_of_points);
To draw a triangle:
(Specify the x coordinates in array x and y coordinates in array y and number of points which will be equal to the elements of both the arrays.Like in triangle you will have 3 x coordinates and 3 y coordinates which means you have 3 points in total.)
Suppose you want to draw the triangle using the following points:(100,50),(70,100),(130,100)
Do the following inside public void paint(Graphics g)
:
int x[]={100,70,130};
int y[]={50,100,100};
g.drawPolygon(x,y,3);
Similarly you can draw any shape using as many points as you want.
Even though this question is answered, providing an example as to what "theirs" and "ours" means in the case of git rebase vs merge. See this link
Git Rebase
theirs
is actually the current branch in the case of rebase. So the below set of commands are actually accepting your current branch changes over the remote branch.
# see current branch
$ git branch
...
* branch-a
# rebase preferring current branch changes during conflicts
$ git rebase -X theirs branch-b
Git Merge
For merge, the meaning of theirs
and ours
is reversed. So, to get the same effect during a merge, i.e., keep your current branch changes (ours
) over the remote branch being merged (theirs
).
# assuming branch-a is our current version
$ git merge -X ours branch-b # <- ours: branch-a, theirs: branch-b
I made a simple to use utility, hope you enjoy.
If the generated INSERT statements are being truncated, check the limit text length of the results on the Management Studio Options: Tools > Options
, Query Results > SQL Server > Results to Grid
, "Non XML data" value under "Maximum Characters Retrieved".
-- Make sure you're on the correct database
SET NOCOUNT ON;
BEGIN TRY
BEGIN TRANSACTION
DECLARE @Tables TABLE (
TableName varchar(50) NOT NULL,
Arguments varchar(1000) NULL
);
-- INSERT HERE THE TABLES AND CONDITIONS YOU WANT TO GENERATE THE INSERT STATEMENTS
INSERT INTO @Tables (TableName, Arguments) VALUES ('table1', 'WHERE field1 = 3101928464');
-- (ADD MORE LINES IF YOU LIKE) INSERT INTO @Tables (TableName, Arguments) VALUES ('table2', 'WHERE field2 IN (1, 3, 5)');
-- YOU DON'T NEED TO EDIT FROM NOW ON.
-- Generating the Script
DECLARE @TableName varchar(50),
@Arguments varchar(1000),
@ColumnName varchar(50),
@strSQL varchar(max),
@strSQL2 varchar(max),
@Lap int,
@Iden int,
@TypeOfData int;
DECLARE C1 CURSOR FOR
SELECT TableName, Arguments FROM @Tables
OPEN C1
FETCH NEXT FROM C1 INTO @TableName, @Arguments;
WHILE @@FETCH_STATUS = 0
BEGIN
-- If you want to delete the lines before inserting, uncomment the next line
-- PRINT 'DELETE FROM ' + @TableName + ' ' + @Arguments
SET @strSQL = 'INSERT INTO ' + @TableName + ' (';
-- List all the columns from the table (to the INSERT into columns...)
SET @Lap = 0;
DECLARE C2 CURSOR FOR
SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
OPEN C2
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Lap>0)
BEGIN
SET @strSQL = @strSQL + ', ';
END
SET @strSQL = @strSQL + @ColumnName;
SET @Lap = @Lap + 1;
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
END
CLOSE C2
DEALLOCATE C2
SET @strSQL = @strSQL + ')'
SET @strSQL2 = 'SELECT ''' + @strSQL + '
SELECT '' + ';
-- List all the columns from the table again (for the SELECT that will be the input to the INSERT INTO statement)
SET @Lap = 0;
DECLARE C2 CURSOR FOR
SELECT sc.name, sc.type FROM syscolumns sc INNER JOIN sysobjects so ON so.id = sc.id AND so.name = @TableName AND so.type = 'U' WHERE sc.colstat = 0 ORDER BY sc.colorder
OPEN C2
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
WHILE @@FETCH_STATUS = 0
BEGIN
IF(@Lap>0)
BEGIN
SET @strSQL2 = @strSQL2 + ' + '', '' + ';
END
-- For each data type, convert the data properly
IF(@TypeOfData IN (55, 106, 56, 108, 63, 38, 109, 50, 48, 52)) -- Numbers
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (62)) -- Float Numbers
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), CONVERT(decimal(18,5), ' + @ColumnName + ')), ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (61, 111)) -- Datetime
SET @strSQL2 = @strSQL2 + 'ISNULL( '''''''' + CONVERT(varchar(max),' + @ColumnName + ', 121) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
ELSE IF(@TypeOfData IN (47, 39)) -- Texts
SET @strSQL2 = @strSQL2 + 'ISNULL('''''''' + RTRIM(LTRIM(' + @ColumnName + ')) + '''''''', ''NULL'') + '' as ' + @ColumnName + '''';
ELSE -- Unknown data types
SET @strSQL2 = @strSQL2 + 'ISNULL(CONVERT(varchar(max), ' + @ColumnName + '), ''NULL'') + '' as ' + @ColumnName + '(INCORRECT TYPE ' + CONVERT(varchar(10), @TypeOfData) + ')''';
SET @Lap = @Lap + 1;
FETCH NEXT FROM C2 INTO @ColumnName, @TypeOfData;
END
CLOSE C2
DEALLOCATE C2
SET @strSQL2 = @strSQL2 + ' as [-- ' + @TableName + ']
FROM ' + @TableName + ' WITH (NOLOCK) ' + @Arguments
SET @strSQL2 = @strSQL2 + ';
';
--PRINT @strSQL;
--PRINT @strSQL2;
EXEC(@strSQL2);
FETCH NEXT FROM C1 INTO @TableName, @Arguments;
END
CLOSE C1
DEALLOCATE C1
ROLLBACK
END TRY
BEGIN CATCH
ROLLBACK TRAN
SELECT 0 AS Situacao;
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_SEVERITY() AS ErrorSeverity
,ERROR_STATE() AS ErrorState
,ERROR_PROCEDURE() AS ErrorProcedure
,ERROR_LINE() AS ErrorLine
,ERROR_MESSAGE() AS ErrorMessage,
@strSQL As strSQL,
@strSQL2 as strSQL2;
END CATCH
If you want to open specific activity of another application we can use this.
Intent intent = new Intent(Intent.ACTION_MAIN, null);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
final ComponentName cn = new ComponentName("com.android.settings", "com.android.settings.fuelgauge.PowerUsageSummary");
intent.setComponent(cn);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try
{
startActivity(intent)
}catch(ActivityNotFoundException e){
Toast.makeText(context,"Activity Not Found",Toast.LENGTH_SHORT).show()
}
If you must need other application, instead of showing Toast you can show a dialog. Using dialog you can bring the user to Play-Store to download required application.
An another way: your application can open a server socet and wait for an information arrived to it. For example a string with a "magic" word :) and then react to make shutdown: System.exit(). You can send such information to the socke using an external application like telnet.
UPDATE:
You have wrong capitalization of environment variables in ENV. Correct one is http_proxy
. Your example should be:
FROM ubuntu:13.10
ENV http_proxy <HTTP_PROXY>
ENV https_proxy <HTTPS_PROXY>
RUN apt-get update && apt-get upgrade
or
FROM centos
ENV http_proxy <HTTP_PROXY>
ENV https_proxy <HTTPS_PROXY>
RUN yum update
All variables specified in ENV are prepended to every RUN command. Every RUN command is executed in own container/environment, so it does not inherit variables from previous RUN commands!
Note: There is no need to call docker daemon with proxy for this to work, although if you want to pull images etc. you need to set the proxy for docker deamon too. You can set proxy for daemon in /etc/default/docker
in Ubuntu (it does not affect containers setting).
Also, this can happen in case you run your proxy on host (i.e. localhost, 127.0.0.1). Localhost on host differ from localhost in container. In such case, you need to use another IP (like 172.17.42.1) to bind your proxy to or if you bind to 0.0.0.0, you can use 172.17.42.1 instead of 127.0.0.1 for connection from container during docker build
.
You can also look for an example here: How to rebuild dockerfile quick by using cache?
I find the Code Metrics and Dependency Structure Matrix add-ins for Reflector very useful.
Returning &iterator will return the address of the iterator. If you want to return a way of referring to the element return the iterator itself.
Beware that you do not need the vector to be a global in order to return the iterator/pointer, but that operations in the vector can invalidate the iterator. Adding elements to the vector, for example, can move the vector elements to a different position if the new size() is greater than the reserved memory. Deletion of an element before the given item from the vector will make the iterator refer to a different element.
In both cases, depending on the STL implementation it can be hard to debug with just random errors happening each so often.
EDIT after comment: 'yes, I didn't want to return the iterator a) because its const, and b) surely it is only a local, temporary iterator? – Krakkos'
Iterators are not more or less local or temporary than any other variable and they are copyable. You can return it and the compiler will make the copy for you as it will with the pointer.
Now with the const-ness. If the caller wants to perform modifications through the returned element (whether pointer or iterator) then you should use a non-const iterator. (Just remove the 'const_' from the definition of the iterator).
Just to complement the Yuval Itzchakov answer.
You can load configuration without builder function, you can just inject it.
public IConfiguration Configuration { get; set; }
public Startup(IConfiguration configuration)
{
Configuration = configuration;
}
You could add a Category partial and a Product partial, each would take a smaller part of the main model as it's own model, i.e. Category's model type might be an IEnumerable, you would pass in Model.Theme to it. The Product's partial might be an IEnumerable that you pass Model.Products into (from within the Category partial).
I'm not sure if that would be the right way forward, but would be interested in knowing.
EDIT
Since posting this answer, I've used EditorTemplates and find this the easiest way to handle repeating input groups or items. It handles all your validation message problems and form submission/model binding woes automatically.
public static void Serialize(object value, Stream s)
{
using (StreamWriter writer = new StreamWriter(s))
using (JsonTextWriter jsonWriter = new JsonTextWriter(writer))
{
JsonSerializer ser = new JsonSerializer();
ser.Serialize(jsonWriter, value);
jsonWriter.Flush();
}
}
public static T Deserialize<T>(Stream s)
{
using (StreamReader reader = new StreamReader(s))
using (JsonTextReader jsonReader = new JsonTextReader(reader))
{
JsonSerializer ser = new JsonSerializer();
return ser.Deserialize<T>(jsonReader);
}
}
Also you could use
${pageContext.request.requestURI}
import os
for subdir, dirs, files in os.walk('./'):
for file in files:
do some stuff
print file
You can improve this code with del dirs[:]
which will be like following .
import os
for subdir, dirs, files in os.walk('./'):
del dirs[:]
for file in files:
do some stuff
print file
Or even better if you could point os.walk with current working directory .
import os
cwd = os.getcwd()
for subdir, dirs, files in os.walk(cwd, topdown=True):
del dirs[:] # remove the sub directories.
for file in files:
do some stuff
print file
If your file is short (or even not extremely long), you can use the following snippet to replace text in place:
# Replace variables in file
with open('path/to/in-out-file', 'r+') as f:
content = f.read()
f.seek(0)
f.truncate()
f.write(content.replace('replace this', 'with this'))
Do you mean include javascript variable values in the query string of the URL?
Yes:
window.location.href = "http://www.gorissen.info/Pierre/maps/googleMapLocation.php?lat="+var1+"&lon="+var2+"&setLatLon="+varEtc;
If I understand correctly you may be experiencing the problem because in order to be able to set the labels "text" property you actually have to use the "content" property.
so instead of:
Label output = null;
output = Label1;
output.Text = "hello";
try:
Label output = null;
output = Label1;
output.Content = "hello";
When you directly print print_r(($value['<YOUR_ARRAY>']-><YOUR_OBJECT>));
then it shows this fatal error Cannot use string offset as an object in
.
If you print like this
$var = $value['#node']-><YOU_OBJECT>;
print_r($var);
You won't get the error!!
Your values
object is obviously an Object[]
containing a String[]
containing the values.
String[] stringValues = (String[])values[0];
Run this command to show ip4 and ip6:
ifconfig eth0 | grep inet | awk '{print $2}' | cut -d/ -f1
Possibly:
select lpad(column, 8, 0) from table;
Edited in response to question from mylesg, in comments below:
ok, seems to make the change on the query- but how do I make it stick (change it) permanently in the table? I tried an UPDATE instead of SELECT
I'm assuming that you used a query similar to:
UPDATE table SET columnName=lpad(nums,8,0);
If that was successful, but the table's values are still without leading-zeroes, then I'd suggest you probably set the column as a numeric type? If that's the case then you'd need to alter the table so that the column is of a text/varchar() type in order to preserve the leading zeroes:
First:
ALTER TABLE `table` CHANGE `numberColumn` `numberColumn` CHAR(8);
Second, run the update:
UPDATE table SET `numberColumn`=LPAD(`numberColum`, 8, '0');
This should, then, preserve the leading-zeroes; the down-side is that the column is no longer strictly of a numeric type; so you may have to enforce more strict validation (depending on your use-case) to ensure that non-numerals aren't entered into that column.
References:
subset()
is also useful:
subset(DATAFRAME, COLUMNNAME == "")
For a survey package, maybe the survey
package is pertinent?
This image illustrates this concept well. Unfortunately, I could not find the original source of this image, but someone made it, he has shown this concept very well in the form of an image.
Try this. Don't forget using System.Reflection
.
string baseDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
9Rays used to have a decompiler, but I haven't checked in a while. It was not free, I remember...
There is also a new one (at least for me) named Dis#.
This one works on Bootstrap 4.3.1.
Jsfiddle: https://jsfiddle.net/ko6L31w4/1/
The HTML code might be a little bit messy because I create a slightly complex dropdown menu for comprehensive test, otherwise everything is pretty straight forward.
Js includes fewer ways to collapse opened dropdowns and CSS only includes minimal styles for full functionalities.
$(function() {_x000D_
$("ul.dropdown-menu [data-toggle='dropdown']").on("click", function(event) {_x000D_
event.preventDefault();_x000D_
event.stopPropagation();_x000D_
_x000D_
//method 1: remove show from sibilings and their children under your first parent_x000D_
_x000D_
/* if (!$(this).next().hasClass('show')) {_x000D_
_x000D_
$(this).parents('.dropdown-menu').first().find('.show').removeClass('show');_x000D_
} */ _x000D_
_x000D_
_x000D_
//method 2: remove show from all siblings of all your parents_x000D_
$(this).parents('.dropdown-submenu').siblings().find('.show').removeClass("show");_x000D_
_x000D_
$(this).siblings().toggleClass("show");_x000D_
_x000D_
_x000D_
//collapse all after nav is closed_x000D_
$(this).parents('li.nav-item.dropdown.show').on('hidden.bs.dropdown', function(e) {_x000D_
$('.dropdown-submenu .show').removeClass("show");_x000D_
});_x000D_
_x000D_
});_x000D_
});
_x000D_
.dropdown-submenu {_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.dropdown-submenu>.dropdown-menu {_x000D_
top: 0;_x000D_
left: 100%;_x000D_
}
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous">_x000D_
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" integrity="sha384-UO2eT0CpHqdSJQ6hJty5KVphtPhzWj9WO1clHTMGa3JDZwrnQq4sF86dIHNDz0W1" crossorigin="anonymous"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" integrity="sha384-JjSmVgyd0p3pXB1rRibZUAYoIIy6OrQ6VrjIEaFf/nJGzIxFDsf4x0xIM+B07jRM" crossorigin="anonymous"></script>_x000D_
_x000D_
_x000D_
<nav class="navbar navbar-expand-md navbar-light bg-white py-3 shadow-sm">_x000D_
<div class="container-fluid">_x000D_
<a href="#" class="navbar-brand font-weight-bold">Multilevel Dropdown</a>_x000D_
_x000D_
<button type="button" data-toggle="collapse" data-target="#navbarContent" aria-controls="navbars" aria-expanded="false" aria-label="Toggle navigation" class="navbar-toggler">_x000D_
<span class="navbar-toggler-icon"></span>_x000D_
</button>_x000D_
_x000D_
_x000D_
<div id="navbarContent" class="collapse navbar-collapse">_x000D_
<ul class="navbar-nav mr-auto">_x000D_
_x000D_
<!-- nav dropdown -->_x000D_
<li class="nav-item dropdown">_x000D_
_x000D_
<a href="#" data-toggle="dropdown" class="nav-link dropdown-toggle">Dropdown</a>_x000D_
<ul class="dropdown-menu">_x000D_
_x000D_
<li><a href="#" class="dropdown-item">Some action</a></li>_x000D_
_x000D_
<!-- lvl 1 dropdown -->_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
_x000D_
<!-- lvl 2 dropdown -->_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
_x000D_
<!-- lvl 3 dropdown --> _x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 3</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 4</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">Some other action</a></li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 1</a>_x000D_
<ul class="dropdown-menu">_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
_x000D_
<li class="dropdown-submenu">_x000D_
<a href="#" role="button" data-toggle="dropdown" class="dropdown-item dropdown-toggle">level 2</a>_x000D_
<ul class="dropdown-menu">_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
<li><a href="#" class="dropdown-item">level 3</a></li>_x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li><a href="#" class="dropdown-item">level 2</a></li>_x000D_
</ul>_x000D_
</li> _x000D_
</ul>_x000D_
</li>_x000D_
_x000D_
<li class="nav-item"><a href="#" class="nav-link">About</a></li>_x000D_
<li class="nav-item"><a href="#" class="nav-link">Services</a></li>_x000D_
<li class="nav-item"><a href="#" class="nav-link">Contact</a></li>_x000D_
</ul>_x000D_
</div>_x000D_
</div>_x000D_
</nav>
_x000D_
The answers are partially correct because @@ is actually a class variable which is per class hierarchy meaning it is shared by a class, its instances and its descendant classes and their instances.
class Person
@@people = []
def initialize
@@people << self
end
def self.people
@@people
end
end
class Student < Person
end
class Graduate < Student
end
Person.new
Student.new
puts Graduate.people
This will output
#<Person:0x007fa70fa24870>
#<Student:0x007fa70fa24848>
So there is only one same @@variable for Person, Student and Graduate classes and all class and instance methods of these classes refer to the same variable.
There is another way of defining a class variable which is defined on a class object (Remember that each class is actually an instance of something which is actually the Class class but it is another story). You use @ notation instead of @@ but you can't access these variables from instance methods. You need to have class method wrappers.
class Person
def initialize
self.class.add_person self
end
def self.people
@people
end
def self.add_person instance
@people ||= []
@people << instance
end
end
class Student < Person
end
class Graduate < Student
end
Person.new
Person.new
Student.new
Student.new
Graduate.new
Graduate.new
puts Student.people.join(",")
puts Person.people.join(",")
puts Graduate.people.join(",")
Here, @people is single per class instead of class hierarchy because it is actually a variable stored on each class instance. This is the output:
#<Student:0x007f8e9d2267e8>,#<Student:0x007f8e9d21ff38>
#<Person:0x007f8e9d226158>,#<Person:0x007f8e9d226608>
#<Graduate:0x007f8e9d21fec0>,#<Graduate:0x007f8e9d21fdf8>
One important difference is that, you cannot access these class variables (or class instance variables you can say) directly from instance methods because @people in an instance method would refer to an instance variable of that specific instance of the Person or Student or Graduate classes.
So while other answers correctly state that @myvariable (with single @ notation) is always an instance variable, it doesn't necessarily mean that it is not a single shared variable for all instances of that class.
window.clipboardData.getData('Text')
will work in some browsers. However, many browsers where it does work will prompt the user as to whether or not they wish the web page to have access to the clipboard.
I liked Webjins answer the most, so i extended it to display days with a d suffix, made display conditional and included a s suffix on plain seconds:
function sec2str(t){
var d = Math.floor(t/86400),
h = ('0'+Math.floor(t/3600) % 24).slice(-2),
m = ('0'+Math.floor(t/60)%60).slice(-2),
s = ('0' + t % 60).slice(-2);
return (d>0?d+'d ':'')+(h>0?h+':':'')+(m>0?m+':':'')+(t>60?s:s+'s');
}
returns "3d 16:32:12" or "16:32:12" or "32:12" or "12s"
This is how we can set it in run-time:
public class Program
{
public static void Main(string[] args)
{
Environment.SetEnvironmentVariable("ASPNETCORE_ENVIRONMENT", "Development");
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
If you are using LINUX, you can use pyALSAAUDIO. For windows, we have PyAudio and there is also a library called SoundAnalyse.
I found an example for Linux here:
#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:
import alsaaudio, time, audioop
# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)
# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)
# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)
while True:
# Read data from device
l,data = inp.read()
if l:
# Return the maximum of the absolute value of all samples in a fragment.
print audioop.max(data, 2)
time.sleep(.001)
Const: Constant variable values have to be defined along with the declaration and after that it won't change.const are implicitly static, so without creating a class instance we can access them. This has a value at compile time.
ReadOnly: We can define read-only variable values while declaring as well as using the constructor at runtime. Read-only variables can't access without a class instance.
Static readonly: We can define static readonly variable values while declaring as well as only through a static constructor, but not with any other constructor. We can also access these variables without creating a class instance (as static variables).
Static readonly will be better choice if we have to consume the variables in different assemblies. Please check the full details in the below blog post:
Const Strings – a very convenient way to shoot yourself in the foot
You can also have a look at the method findText(const QString & text) from QComboBox; it returns the index of the element which contains the given text, (-1 if not found). The advantage of using this method is that you don't need to set the second parameter when you add an item.
Here is a little example :
/* Create the comboBox */
QComboBox *_comboBox = new QComboBox;
/* Create the ComboBox elements list (here we use QString) */
QList<QString> stringsList;
stringsList.append("Text1");
stringsList.append("Text3");
stringsList.append("Text4");
stringsList.append("Text2");
stringsList.append("Text5");
/* Populate the comboBox */
_comboBox->addItems(stringsList);
/* Create the label */
QLabel *label = new QLabel;
/* Search for "Text2" text */
int index = _comboBox->findText("Text2");
if( index == -1 )
label->setText("Text2 not found !");
else
label->setText(QString("Text2's index is ")
.append(QString::number(_comboBox->findText("Text2"))));
/* setup layout */
QVBoxLayout *layout = new QVBoxLayout(this);
layout->addWidget(_comboBox);
layout->addWidget(label);
ACE.oledb.16.0 dosen't work in the 64-bit os
download patch from https://www.microsoft.com/en-us/download/details.aspx?id=13255
First, you're missing some parentheses in your conditional:
if ($("#about").hasClass("opened")) {
$("#about").animate({right: "-700px"}, 2000);
}
But you can also simplify this to:
$('#about.opened').animate(...);
If #about
doesn't have the opened
class, it won't animate.
If the problem is with the animation itself, we'd need to know more about your element positioning (absolute? absolute inside relative parent? does the parent have layout?)
You could use $
extraction:
class(aframe$a1)
[1] "numeric"
or the double square bracket:
class(aframe[["a1"]])
[1] "numeric"
From Pro C# 5.0 and the .NET 4.5 Framework
The ObservableCollection<T>
class is very useful in that it has the ability to inform external objects
when its contents have changed in some way (as you might guess, working with
ReadOnlyObservableCollection<T>
is very similar, but read-only in nature).
In many ways, working with
the ObservableCollection<T>
is identical to working with List<T>
, given that both of these classes
implement the same core interfaces. What makes the ObservableCollection<T>
class unique is that this
class supports an event named CollectionChanged
. This event will fire whenever a new item is inserted, a current item is removed (or relocated), or if the entire collection is modified.
Like any event, CollectionChanged is defined in terms of a delegate, which in this case is
NotifyCollectionChangedEventHandler
. This delegate can call any method that takes an object as the first parameter, and a NotifyCollectionChangedEventArgs
as the second. Consider the following Main()
method, which populates an observable collection containing Person objects and wires up the
CollectionChanged
event:
class Program
{
static void Main(string[] args)
{
// Make a collection to observe and add a few Person objects.
ObservableCollection<Person> people = new ObservableCollection<Person>()
{
new Person{ FirstName = "Peter", LastName = "Murphy", Age = 52 },
new Person{ FirstName = "Kevin", LastName = "Key", Age = 48 },
};
// Wire up the CollectionChanged event.
people.CollectionChanged += people_CollectionChanged;
// Now add a new item.
people.Add(new Person("Fred", "Smith", 32));
// Remove an item.
people.RemoveAt(0);
Console.ReadLine();
}
static void people_CollectionChanged(object sender, System.Collections.Specialized.NotifyCollectionChangedEventArgs e)
{
// What was the action that caused the event?
Console.WriteLine("Action for this event: {0}", e.Action);
// They removed something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Remove)
{
Console.WriteLine("Here are the OLD items:");
foreach (Person p in e.OldItems)
{
Console.WriteLine(p.ToString());
}
Console.WriteLine();
}
// They added something.
if (e.Action == System.Collections.Specialized.NotifyCollectionChangedAction.Add)
{
// Now show the NEW items that were inserted.
Console.WriteLine("Here are the NEW items:");
foreach (Person p in e.NewItems)
{
Console.WriteLine(p.ToString());
}
}
}
}
The incoming NotifyCollectionChangedEventArgs
parameter defines two important properties,
OldItems
and NewItems
, which will give you a list of items that were currently in the collection before the event fired, and the new items that were involved in the change. However, you will want to examine these lists only under the correct circumstances. Recall that the CollectionChanged event can fire when
items are added, removed, relocated, or reset. To discover which of these actions triggered the event,
you can use the Action property of NotifyCollectionChangedEventArgs. The Action property can be
tested against any of the following members of the NotifyCollectionChangedAction
enumeration:
public enum NotifyCollectionChangedAction
{
Add = 0,
Remove = 1,
Replace = 2,
Move = 3,
Reset = 4,
}
Postman
.http://{server:port}/json/metallica/post
.Headers
button and enter Content-Type
as header and application/json
in value.POST
from the dropdown next to the URL text box.raw
from the buttons available below URL text box.JSON
from the following dropdown.In the textarea available below, post your request object:
{
"title" : "test title",
"singer" : "some singer"
}
Hit Send
.
Refer to screenshot below:
Since my previous answer I came up with another solution that is different and perhaps better. This code allows processes to be run more than 60 times a minute with microsecond precision. You need the usleep program to make this work. Should be good to up to 50 times a second.
#! /bin/sh
# Microsecond Cron
# Usage: cron-ms start
# Copyright 2014 by Marc Perkel
# docs at http://wiki.junkemailfilter.com/index.php/How_to_run_a_Linux_script_every_few_seconds_under_cron"
# Free to use with attribution
basedir=/etc/cron-ms
if [ $# -eq 0 ]
then
echo
echo "cron-ms by Marc Perkel"
echo
echo "This program is used to run all programs in a directory in parallel every X times per minute."
echo "Think of this program as cron with microseconds resolution."
echo
echo "Usage: cron-ms start"
echo
echo "The scheduling is done by creating directories with the number of"
echo "executions per minute as part of the directory name."
echo
echo "Examples:"
echo " /etc/cron-ms/7 # Executes everything in that directory 7 times a minute"
echo " /etc/cron-ms/30 # Executes everything in that directory 30 times a minute"
echo " /etc/cron-ms/600 # Executes everything in that directory 10 times a second"
echo " /etc/cron-ms/2400 # Executes everything in that directory 40 times a second"
echo
exit
fi
# If "start" is passed as a parameter then run all the loops in parallel
# The number of the directory is the number of executions per minute
# Since cron isn't accurate we need to start at top of next minute
if [ $1 = start ]
then
for dir in $basedir/* ; do
$0 ${dir##*/} 60000000 &
done
exit
fi
# Loops per minute and the next interval are passed on the command line with each loop
loops=$1
next_interval=$2
# Sleeps until a specific part of a minute with microsecond resolution. 60000000 is full minute
usleep $(( $next_interval - 10#$(date +%S%N) / 1000 ))
# Run all the programs in the directory in parallel
for program in $basedir/$loops/* ; do
if [ -x $program ]
then
$program &> /dev/null &
fi
done
# Calculate next_interval
next_interval=$(($next_interval % 60000000 + (60000000 / $loops) ))
# If minute is not up - call self recursively
if [ $next_interval -lt $(( 60000000 / $loops * $loops)) ]
then
. $0 $loops $next_interval &
fi
# Otherwise we're done
In order to use Http in your app you will need to add the HttpModule to your app.module.ts:
import { BrowserModule } from '@angular/platform-browser';
import { NgModule, ErrorHandler } from '@angular/core';
import { HttpModule } from '@angular/http';
...
imports: [
BrowserModule,
HttpModule,
IonicModule.forRoot(MyApp),
IonicStorageModule.forRoot()
]
EDIT
As mentioned in the comment below, HttpModule
is deprecated
now, use import { HttpClientModule } from '@angular/common/http'
; Make sure HttpClientModule
in your imports:[]
array
since xcode5 organizer no longer team section exists. but the bold sentence was the answer for me. God thanks there is another mac to restore and import to problemmatic mac. now all is ok.
I used this to sort a gallery of images where the sort array would be altered by an ajax call. Hopefully it can be useful to someone.
var myArray = ['2', '3', '1'];_x000D_
var elArray = [];_x000D_
_x000D_
$('.imgs').each(function() {_x000D_
elArray[$(this).data('image-id')] = $(this);_x000D_
});_x000D_
_x000D_
$.each(myArray,function(index,value){_x000D_
$('#container').append(elArray[value]); _x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>_x000D_
<div id='container'>_x000D_
<div class="imgs" data-image-id='1'>1</div>_x000D_
<div class="imgs" data-image-id='2'>2</div>_x000D_
<div class="imgs" data-image-id='3'>3</div>_x000D_
</div>
_x000D_
Fiddle: http://jsfiddle.net/ruys9ksg/
In addition to the link provided by Floremin, which clears text selection using JavaScript to "clear" the selection, you can also use pure CSS to accomplish this. The CSS is here...
.noSelect {
-webkit-touch-callout: none;
-webkit-user-select: none;
-khtml-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
user-select: none;
}
Simply add the class="noSelect"
attribute to the element you wish to apply this class to. I would highly recommend giving this CSS solution a try. Nothing wrong with using the JavaScript, I just believe this could potentially be easier, and clean things up a little bit in your code.
For chrome on android
-webkit-tap-highlight-color: transparent;
is an additional rule you may want to experiment with for support in Android.
Make sure you don't have multiple transactions in the same procedure/query out of which one or more are left uncommited.
In my case, I accidentally had a BEGIN TRAN statement in the query
According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:
FieldType term | Type | Interpretation -------------- | --------- | -------------- L ClassName ; | reference | an instance of class ClassName [ | reference | one array dimension ... | ... | ...
the expression [Ljava.lang.String;@45a877
means this is an array ( [
) of class java.lang.String ( Ljava.lang.String;
). And @45a877
is the address where the String object is stored in memory.
I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.
Basically what you need to do is put your .so
files inside a a folder named lib
(Note: it is not libs
and this is not a mistake). It should be in the same structure it should be in the APK
file.
In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.
So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip
(the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip
file into armeabi.jar
and added the line compile fileTree(dir: 'libs', include: '*.jar')
into dependencies {}
in the gradle's build file.
This solved my problem in a rather clean way.
I had a similar problem and this is the workaround that helped me without having to edit the csv file contents:
If you have the flexibility to name the file something other than ".csv", you can name it with a ".txt" extension, such as "Myfile.txt" or "Myfile.csv.txt". Then when you open it in Excel (not by drag and drop, but using File->Open or the Most Recently Used files list), Excel will provide you with a "Text Import Wizard".
In the first page of the wizard, choose "Delimited" for the file type.
In the second page of the wizard choose "," as the delimiter and also choose the text qualifier if you have surrounded your values by quotes
In the third page, select every column individually and assign each the type "Text" instead of "General" to stop Excel from messing with your data.
Hope this helps you or someone with a similar problem!
if you want to show text put # at the begging of the message you want it will share it as Hashtag
$filelist | % {
$file = $_
mkdir -force (Split-Path $dest) | Out-Null
cp $file $dest
}
Yes and no. Self signed certificates result in that warning message because the certificate was not signed by a trusted Certificate Authority. There are a few options that you can consider to remove this warning on your local machine. See the highest ranked answers to this question for details:
What do I need to do to get Internet Explorer 8 to accept a self signed certificate?
Hope this helps!
EDIT:
Sorry, I wasn't initially aware that you were constrained to localhost. You can attempt to follow the directions on the the link below to "Generate a Self Signed Certificate with the Correct Common Name."
http://www.sslshopper.com/article-how-to-create-a-self-signed-certificate-in-iis-7.html
You don't need to convert your dates to timestamp before the sorting, but it's a good idea though because it will take more time to sort without it.
$data = array(
array(
"title" => "Another title",
"date" => "Fri, 17 Jun 2011 08:55:57 +0200"
),
array(
"title" => "My title",
"date" => "Mon, 16 Jun 2010 06:55:57 +0200"
)
);
function sortFunction( $a, $b ) {
return strtotime($a["date"]) - strtotime($b["date"]);
}
usort($data, "sortFunction");
var_dump($data);
edit: Reading the faq a bit longer I like the idea of the << >> operator overloading and adding as a friend of those classes, however I am not sure how this doesn't break encapsulation
How would it break encapsulation?
You break encapsulation when you allow unrestricted access to a data member. Consider the following classes:
class c1 {
public:
int x;
};
class c2 {
public:
int foo();
private:
int x;
};
class c3 {
friend int foo();
private:
int x;
};
c1
is obviously not encapsulated. Anyone can read and modify x
in it. We have no way to enforce any kind of access control.
c2
is obviously encapsulated. There is no public access to x
. All you can do is call the foo
function, which performs some meaningful operation on the class.
c3
? Is that less encapsulated? Does it allow unrestricted access to x
? Does it allow unknown functions access?
No. It allows precisely one function to access the private members of the class. Just like c2
did. And just like c2
, the one function which has access is not "some random, unknown function", but "the function listed in the class definition". Just like c2
, we can see, just by looking at the class definitions, a complete list of who has access.
So how exactly is this less encapsulated? The same amount of code has access to the private members of the class. And everyone who has access is listed in the class definition.
friend
does not break encapsulation. It makes some Java people programmers feel uncomfortable, because when they say "OOP", they actually mean "Java". When they say "Encapsulation", they don't mean "private members must be protected from arbitrary accesses", but "a Java class where the only functions able to access private members, are class members", even though this is complete nonsense for several reasons.
First, as already shown, it is too restricting. There's no reason why friend methods shouldn't be allowed to do the same.
Second, it is not restrictive enough. Consider a fourth class:
class c4 {
public:
int getx();
void setx(int x);
private:
int x;
};
This, according to aforesaid Java mentality, is perfectly encapsulated. And yet, it allows absolutely anyone to read and modify x. How does that even make sense? (hint: It doesn't)
Bottom line: Encapsulation is about being able to control which functions can access private members. It is not about precisely where the definitions of these functions are located.
I noticed that when it's set to false, I'm able to see the value of an item using the debugger. When it was set to true, I was getting an error - item.FullName.GetValue The embedded interop type 'FullName' does not contain a definition for 'QBFC11Lib.IItemInventoryRet' since it was not used in the compiled assembly. Consider casting to object or changing the 'Embed Interop Types' property to true.
Be aware, that \W
leaves the underscore. A short equivalent for [^a-zA-Z0-9]
would be [\W_]
text.replace(/[\W_]+/g," ");
\W
is the negation of shorthand \w
for [A-Za-z0-9_]
word characters (including the underscore)
document.getElementById("uploadCaptureInputFile").value = "";
_x000D_
Capslock + Tab to indent multiple lines at once. Highlight the text first.
<div style="text-align:center;">
<img src="queuedError.jpg" style="margin:auto; width:200px;" />
</div>
In Python 2.6 or newer:
If you want StopIteration
to be raised if no matching element is found:
next(x for x in the_iterable if x > 3)
If you want default_value
(e.g. None
) to be returned instead:
next((x for x in the_iterable if x > 3), default_value)
Note that you need an extra pair of parentheses around the generator expression in this case - they are needed whenever the generator expression isn't the only argument.
I see most answers resolutely ignore the next
built-in and so I assume that for some mysterious reason they're 100% focused on versions 2.5 and older -- without mentioning the Python-version issue (but then I don't see that mention in the answers that do mention the next
built-in, which is why I thought it necessary to provide an answer myself -- at least the "correct version" issue gets on record this way;-).
In 2.5, the .next()
method of iterators immediately raises StopIteration
if the iterator immediately finishes -- i.e., for your use case, if no item in the iterable satisfies the condition. If you don't care (i.e., you know there must be at least one satisfactory item) then just use .next()
(best on a genexp, line for the next
built-in in Python 2.6 and better).
If you do care, wrapping things in a function as you had first indicated in your Q seems best, and while the function implementation you proposed is just fine, you could alternatively use itertools
, a for...: break
loop, or a genexp, or a try/except StopIteration
as the function's body, as various answers suggested. There's not much added value in any of these alternatives so I'd go for the starkly-simple version you first proposed.
The css is
text-decoration: none;
and
text-decoration: underline;
In 2010 it is Ctrl+k, Ctrl+d. See image below.
Use this query to get values
SELECT * FROM `buy` group by date order by date DESC
If you're using Apache and can use a .htaccess
file you should use the following type of redirect. Add the following to an .htaccess
file in the root of your website.
RewriteEngine On
RewriteRule ^/oldfile_path/file_name\.html$ /oldfile_path/file_name.html [R=301,L]
This has the advantage of being a very fast and immediate redirect. It also depends on your reason for the redirect. This is a more permanent method because it sends the HTTP 301 status code signifying that the file has moved permanently and causes many browsers to cache that request. You can change the code to something else like a 302 for temporary redirects.
Otherwise you can do a simple redirect using an HTML <meta>
tag as suggested by others:
<meta http-equiv="refresh" content="5; url=http://example.com/">
By default the content="5"
makes that redirect after 5 seconds. This will be slower and not all browsers support it. A redirect can also be done in the server language of your choice PHP
, Node.js
, etc.
select.list1 option.option2
{
background-color: #007700;
}
_x000D_
<select class="list1">
<option value="1">Option 1</option>
<option value="2" class="option2">Option 2</option>
</select>
_x000D_
On saveAndFlush
, changes will be flushed to DB immediately in this command. With save
, this is not necessarily true, and might stay just in memory, until flush
or commit
commands are issued.
But be aware, that even if you flush the changes in transaction and do not commit them, the changes still won't be visible to the outside transactions until the commit in this transaction.
In your case, you probably use some sort of transactions mechanism, which issues commit
command for you if everything works out fine.
It's always annoyed me how Windows doesn't have some of more useful little scripting utilities of Unix, such as who/whoami, sed and AWK. Anyway, if you want something foolproof, get Visual Studio Express and compile the following:
#include <windows.h>
#include <stdio.h>
int main(int argc, char **argv) {
printf("%s", GetUserName());
}
And just use that in your batch file.
As mentioned you need to use obj.getTile()
But, in this case I think you are looking to use a Property.
public class Pin
{
private string title;
public Pin() { }
public setTitle(string title) {
this.title = title;
}
public String Title
{
get { return title; }
}
}
This will allow you to use
foreach (Pin obj in ClassListPin.pins)
{
string t = obj.Title;
}
This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd
to another (existing) directory and then cd
back; the simplest would be: cd; cd -
.
In pandas 16.2, I had to do pd.DataFrame.from_records(d)
to get this to work.
This in my C# 3.0 variation of Ian Kemp's solution:
public static void SetPropertyInGuiThread<C,V>(this C control, Expression<Func<C, V>> property, V value) where C : Control
{
var memberExpression = property.Body as MemberExpression;
if (memberExpression == null)
throw new ArgumentException("The 'property' expression must specify a property on the control.");
var propertyInfo = memberExpression.Member as PropertyInfo;
if (propertyInfo == null)
throw new ArgumentException("The 'property' expression must specify a property on the control.");
if (control.InvokeRequired)
control.Invoke(
(Action<C, Expression<Func<C, V>>, V>)SetPropertyInGuiThread,
new object[] { control, property, value }
);
else
propertyInfo.SetValue(control, value, null);
}
You call it like this:
myButton.SetPropertyInGuiThread(b => b.Text, "Click Me!")
Otherwise, the original is a very nice solution.
I would start with upgrade of CMAKE version.
You can use INCLUDE_DIRECTORIES for header location and LINK_DIRECTORIES + TARGET_LINK_LIBRARIES for libraries
INCLUDE_DIRECTORIES(your/header/dir)
LINK_DIRECTORIES(your/library/dir)
rosbuild_add_executable(kinectueye src/kinect_ueye.cpp)
TARGET_LINK_LIBRARIES(kinectueye lib1 lib2 lib2 ...)
note that lib1
is expanded to liblib1.so
(on Linux), so use ln to create appropriate links in case you do not have them
;extension=mysqli
;
symbol if (!function_exists('mysqli_init') && !extension_loaded('mysqli')) {
echo 'We don\'t have mysqli!!!';
} else {
echo 'mysqli is installed';
}
You are not indicating what to include in the archive.
Go one level outside your folder and try:
sudo tar -cvjSf folder.tar.bz2 folder
Or from the same folder try
sudo tar -cvjSf folder.tar.bz2 *
Cheers!
See if this answer can help you. Particularly the fact that CLI ini could be different than when the script is running through a browser.
Some of the other answers return an actual string whereas I had more need to know the actual index int. And the answers that do that seem to over-complicate things. Using some of the other answers as inspiration, I did the following...
First, I created a function:
CREATE FUNCTION [dbo].[LastIndexOf] (@stringToFind varchar(max), @stringToSearch varchar(max))
RETURNS INT
AS
BEGIN
RETURN (LEN(@stringToSearch) - CHARINDEX(@stringToFind,REVERSE(@stringToSearch))) + 1
END
GO
Then, in your query you can simply do this:
declare @stringToSearch varchar(max) = 'SomeText: SomeMoreText: SomeLastText'
select dbo.LastIndexOf(':', @stringToSearch)
The above should return 23 (the last index of ':')
Hope this made it a little easier for someone!
Old question, but since the question asks "using jQuery", I thought I'd provide an option that lets you do this without introducing any vendor dependency.
While there are a lot of templating engines out there, many of their features have fallen in to disfavour recently, with iteration (<% for
), conditionals (<% if
) and transforms (<%= myString | uppercase %>
) seen as microlanguage at best, and anti-patterns at worst. Modern templating practices encourage simply mapping an object to its DOM (or other) representation, e.g. what we see with properties mapped to components in ReactJS (especially stateless components).
One property you can rely on for keeping the HTML for your template next to the rest of your HTML, is by using a non-executing <script>
type
, e.g. <script type="text/template">
. For your case:
<script type="text/template" data-template="listitem">
<a href="${url}" class="list-group-item">
<table>
<tr>
<td><img src="${img}"></td>
<td><p class="list-group-item-text">${title}</p></td>
</tr>
</table>
</a>
</script>
On document load, read your template and tokenize it using a simple String#split
var itemTpl = $('script[data-template="listitem"]').text().split(/\$\{(.+?)\}/g);
Notice that with our token, you get it in the alternating [text, property, text, property]
format. This lets us nicely map it using an Array#map
, with a mapping function:
function render(props) {
return function(tok, i) { return (i % 2) ? props[tok] : tok; };
}
Where props
could look like { url: 'http://foo.com', img: '/images/bar.png', title: 'Lorem Ipsum' }
.
Putting it all together assuming you've parsed and loaded your itemTpl
as above, and you have an items
array in-scope:
$('.search').keyup(function () {
$('.list-items').append(items.map(function (item) {
return itemTpl.map(render(item)).join('');
}));
});
This approach is also only just barely jQuery - you should be able to take the same approach using vanilla javascript with document.querySelector
and .innerHTML
.
A question to ask yourself is: do you really want/need to define templates as HTML files? You can always componentize + re-use a template the same way you'd re-use most things you want to repeat: with a function.
In es7-land, using destructuring, template strings, and arrow-functions, you can write downright pretty looking component functions that can be easily loaded using the $.fn.html
method above.
const Item = ({ url, img, title }) => `
<a href="${url}" class="list-group-item">
<div class="image">
<img src="${img}" />
</div>
<p class="list-group-item-text">${title}</p>
</a>
`;
Then you could easily render it, even mapped from an array, like so:
$('.list-items').html([
{ url: '/foo', img: 'foo.png', title: 'Foo item' },
{ url: '/bar', img: 'bar.png', title: 'Bar item' },
].map(Item).join(''));
Oh and final note: don't forget to sanitize your properties passed to a template, if they're read from a DB, or someone could pass in HTML (and then run scripts, etc.) from your page.
Format in other syntax is possible in this way
[DateTime]::Today.AddDays(-1).ToString("yyyyMMdd")
nawk '$0 ~ /string$/ {printf "%s ",$0; getline; printf "%s\n", $0}' filename
This reads as
$0 ~ /string$/ ## matches any lines that end with the word string
printf ## so print the first line without newline
getline ## get the next line
printf "%s\n" ## print the whole line and carriage return
Use CSS :before
and content
property to print the breakpoint state in the <span id="breakpoint-js">
so the JavaScript just have to read this data to turn it as a variable to use within your function.
(run the snippet to see the example)
NOTE: I added a few line of CSS to use the <span>
as a red flag in the upper corner of my browser. Just make sure to switch it back to display:none;
before pushing your stuff public.
// initialize it with jquery when DOM is ready_x000D_
$(document).on('ready', function() {_x000D_
getBootstrapBreakpoint();_x000D_
});_x000D_
_x000D_
// get bootstrap grid breakpoints_x000D_
var theBreakpoint = 'xs'; // bootstrap336 default = mobile first_x000D_
function getBootstrapBreakpoint(){_x000D_
theBreakpoint = window.getComputedStyle(document.querySelector('#breakpoint-js'),':before').getPropertyValue('content').replace(/['"]+/g, '');_x000D_
console.log('bootstrap grid breakpoint = ' + theBreakpoint);_x000D_
}
_x000D_
#breakpoint-js {_x000D_
/* display: none; //comment this while developping. Switch back to display:NONE before commit */_x000D_
/* optional red flag layout */_x000D_
position: fixed;_x000D_
z-index: 999;_x000D_
top: 0;_x000D_
left: 0;_x000D_
color: white;_x000D_
padding: 5px 10px;_x000D_
background-color: red;_x000D_
opacity: .7;_x000D_
/* end of optional red flag layout */_x000D_
}_x000D_
#breakpoint-js:before {_x000D_
content: 'xs'; /* default = mobile first */_x000D_
}_x000D_
@media screen and (min-width: 768px) {_x000D_
#breakpoint-js:before {_x000D_
content: 'sm';_x000D_
}_x000D_
}_x000D_
@media screen and (min-width: 992px) {_x000D_
#breakpoint-js:before {_x000D_
content: 'md';_x000D_
}_x000D_
}_x000D_
@media screen and (min-width: 1200px) {_x000D_
#breakpoint-js:before {_x000D_
content: 'lg';_x000D_
}_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<!-- Latest compiled and minified CSS -->_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" integrity="sha384-1q8mTJOASx8j1Au+a5WDVnPi2lkFfwwEAa8hDDdjZlpLegxhjVME1fgjWPGmkzs7" crossorigin="anonymous">_x000D_
_x000D_
<div class="container">_x000D_
<span id="breakpoint-js"></span>_x000D_
<div class="page-header">_x000D_
<h1>Bootstrap grid examples</h1>_x000D_
<p class="lead">Basic grid layouts to get you familiar with building within the Bootstrap grid system.</p>_x000D_
</div>_x000D_
</div>
_x000D_
The default vector constructor will create an empty vector. As such, you should be able to write:
struct user r = { string(), vector<unsigned char>() };
Note, I've also used the default string constructor instead of "".
You might want to consider making user a class and adding a default constructor that does this for you:
class User {
User() {}
string username;
vector<unsigned char> password;
};
Then just writing:
User r;
Will result in a correctly initialized user.
In PowerShell, boolean parameters can be declared by mentioning their type before their variable.
function GetWeb() {
param([bool] $includeTags)
........
........
}
You can assign value by passing $true | $false
GetWeb -includeTags $true
If you're in Windows, go to Task Manager, then go to Processes, look for a process called "node", then click on it with the right button of your mouse and then click the "End Process" option.
This has already been answered, but I think the simplest syntax is:
CREATE TABLE History (
ID int primary key IDENTITY(1,1) NOT NULL,
. . .
The more complicated constraint index is useful when you actually want to change the options.
By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.
Just a simple explanation to use it in an HTML document.
If you have a Map of types (key, array) then you initialise the array this way:
public cityShop: Map<string, Shop[]> = new Map();
And to iterate over it, you create an array from key values.
Just use it as an array as in:
keys = Array.from(this.cityShop.keys());
Then, in HTML, you can use:
*ngFor="let key of keys"
Inside this loop, you just get the array value with:
this.cityShop.get(key)
Done!