Provide a format string:
date +"%H:%M"
Running man date
will give all the format options
%a locale's abbreviated weekday name (e.g., Sun)
%A locale's full weekday name (e.g., Sunday)
%b locale's abbreviated month name (e.g., Jan)
%B locale's full month name (e.g., January)
%c locale's date and time (e.g., Thu Mar 3 23:05:25 2005)
%C century; like %Y, except omit last two digits (e.g., 20)
%d day of month (e.g., 01)
%D date; same as %m/%d/%y
%e day of month, space padded; same as %_d
%F full date; same as %Y-%m-%d
%g last two digits of year of ISO week number (see %G)
%G year of ISO week number (see %V); normally useful only with %V
%h same as %b
%H hour (00..23)
%I hour (01..12)
%j day of year (001..366)
%k hour, space padded ( 0..23); same as %_H
%l hour, space padded ( 1..12); same as %_I
%m month (01..12)
%M minute (00..59)
%n a newline
%N nanoseconds (000000000..999999999)
%p locale's equivalent of either AM or PM; blank if not known
%P like %p, but lower case
%r locale's 12-hour clock time (e.g., 11:11:04 PM)
%R 24-hour hour and minute; same as %H:%M
%s seconds since 1970-01-01 00:00:00 UTC
%S second (00..60)
%t a tab
%T time; same as %H:%M:%S
%u day of week (1..7); 1 is Monday
%U week number of year, with Sunday as first day of week (00..53)
%V ISO week number, with Monday as first day of week (01..53)
%w day of week (0..6); 0 is Sunday
%W week number of year, with Monday as first day of week (00..53)
%x locale's date representation (e.g., 12/31/99)
%X locale's time representation (e.g., 23:13:48)
%y last two digits of year (00..99)
%Y year
%z +hhmm numeric time zone (e.g., -0400)
%:z +hh:mm numeric time zone (e.g., -04:00)
%::z +hh:mm:ss numeric time zone (e.g., -04:00:00)
%:::z numeric time zone with : to necessary precision (e.g., -04, +05:30)
%Z alphabetic time zone abbreviation (e.g., EDT)
Just to add an additional function should you need it. You can include a variable in the named location, for example a date identifier
date <- yyyymmdd
save(city, file=paste0("c:\\myuser\\somelocation\\",date,"_RData.Data")
This was you can always keep a check of when it was run
Date(date&time field) and DATE_FORMAT(date&time,'%Y-%m-%d') both returns only date from date&time
If you want to add multiple items, you have to use the spread operator
a = [1,2]
b = [3,4,5,6]
a.push(...b)
The output will be
a = [1,2,3,4,5,6]
This answer is a bit late but I hope it helps someone out there all the same.
In my case, it was because the repository had been moved. I recloned the project and everything became alright afterwards. A better alternative would have been to re-initialize git.
I hope this helps.. Merry coding!
I had the same error but I discovered that when you import an AddEventModule
, you can't import an AddEvent
module as it would present an error in this case.
@PeterMajeed's comment in the accepted answer helped me out with a related problem. I am not using the portable library, but have the same build error on a fresh Windows Server 2012 install, where I'm running TeamCity.
Installing the Microsoft .NET Framework 4.5.1 Developer Pack took care of the issue (after having separately installed the MS Build Tools).
i have the same probleme, i always change the "style.css" to "styles.css" or any other name and it worked fine for me.
A segementation fault is an internal error in php (or, less likely, apache). Oftentimes, the segmentation fault is caused by one of the newer and lesser-tested php modules such as imagemagick or subversion.
Try disabling all non-essential modules (in php.ini
), and then re-enabling them one-by-one until the error occurs. You may also want to update php and apache.
If that doesn't help, you should report a php bug.
You should really use generics and the enhanced for loop for this:
Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");
for (Integer key : hm.keySet()) {
System.out.println(key);
System.out.println(hm.get(key));
}
Or the entrySet()
version:
Map<Integer, String> hm = new HashMap<>();
hm.put(0, "zero");
hm.put(1, "one");
for (Map.Entry<Integer, String> e : hm.entrySet()) {
System.out.println(e.getKey());
System.out.println(e.getValue());
}
A perl oneliner would do: perl -i.bak -pe 's/[^[:ascii:]]//g' <your file>
-i
says that the file is going to be edited inplace, and the backup is going to be saved with extension .bak
.
You could use the object data type:
>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)
If you have a LDAP connection with a username and password to connect to Active Directory, here is the code I used to connect properly:
using System.DirectoryServices.AccountManagement;
// ...
// Connection information
var connectionString = "LDAP://domain.com/DC=domain,DC=com";
var connectionUsername = "your_ad_username";
var connectionPassword = "your_ad_password";
// Get groups for this user
var username = "myusername";
// Split the LDAP Uri
var uri = new Uri(connectionString);
var host = uri.Host;
var container = uri.Segments.Count() >=1 ? uri.Segments[1] : "";
// Create context to connect to AD
var princContext = new PrincipalContext(ContextType.Domain, host, container, connectionUsername, connectionPassword);
// Get User
UserPrincipal user = UserPrincipal.FindByIdentity(princContext, IdentityType.SamAccountName, username);
// Browse user's groups
foreach (GroupPrincipal group in user.GetGroups())
{
Console.Out.WriteLine(group.Name);
}
NULL
is already ignored so you can use NULLIF
to turn 0
to NULL
. Also you don't need DISTINCT
and your WHERE
on ActualTime
is not sargable.
SELECT AVG(cast(NULLIF(a.SecurityW, 0) AS BIGINT)) AS Average1,
AVG(cast(NULLIF(a.TransferW, 0) AS BIGINT)) AS Average2,
AVG(cast(NULLIF(a.StaffW, 0) AS BIGINT)) AS Average3
FROM Table1 a
WHERE a.ActualTime >= '20130401'
AND a.ActualTime < '20130501'
PS I have no idea what Table2 b
is in the original query for as there is no join condition for it so have omitted it from my answer.
In Windows 10 I browsed to *%APPDATA%\MySQL\Workbench* then deleted the workbench_user_data.dat file
Doing so lost my MySqlWorkbence settings but allowed MySqlWorkbence to open.
As ivan.sim writes in his answer
- Ensure that your user account has administrator privilege.
- Disable UAC(User Account Control) as it restricts certain administrative function needed to run a web server.
- Install in C://xampp.
Problem with the correct answer is in the explanation of point 2., and magicandre1981 writes more about it
Moving the slider down doesn't completely disable UAC since Windows 8. This is changed compared to Windows 7, because the new Store apps require an active UAC. With UAC off, they no longer run.
How can we then disable UAC and install XAMPP?
Easy. Go to Registry Editor and navigate to
HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System
Right click EnableLUA and modify the Value data to 0.
Then restart your computer and you're ready to install XAMPP.
I would use the DATE_DIFF function to provide this value as below:
SELECT dtCreated
, bActive
, dtLastPaymentAttempt
, dtLastUpdated
, dtLastVisit
, DATEDIFF(d, dtLastUpdated, dtCreated) AS Difference
FROM Customers
WHERE (bActive = 'true')
AND (dtLastUpdated > CONVERT(DATETIME, '2012-01-0100:00:00', 102))
EDIT: IF using MySQL you omit the 'd' leaving you with
DATEDIFF(dtLastUpdated, dtCreated) AS Difference
import React, { Component } from 'react'
export default class Form extends Component {
constructor(props) {
super(props)
this.formRef = React.createRef()
this.state = {
email: '',
loading: false,
eror: null
}
}
reset = () => {
this.formRef.current.reset()
}
render() {
return (
<div>
<form>
<input type="email" name="" id=""/>
<button type="submit">Submit</button>
<button onClick={()=>this.reset()}>Reset</button>
</form>
</div>
)
}
}
_x000D_
They have a very good answer here: https://stackoverflow.com/a/32455275/165865
Just run below images:
docker run --rm -v /var/run/docker.sock:/var/run/docker.sock nate/dockviz images -t
Fibonacci sequence generator using the yield keyword.
function* fibbonaci(){
var a = -1, b = 1, c;
while(1){
c = a + b;
a = b;
b = c;
yield c;
}
}
var fibonacciGenerator = fibbonaci();
fibonacciGenerator.next().value; // 0
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 1
fibonacciGenerator.next().value; // 2
In .Net Core (as of v2.2) it should be:
new Process
{
StartInfo = new ProcessStartInfo(@"file path")
{
UseShellExecute = true
}
}.Start();
Related github issue can be found here
I used the following two steps which I found in the comments/posts linked in the other answers:
Step one: Convert the x.509 cert and key to a pkcs12 file
openssl pkcs12 -export -in server.crt -inkey server.key \
-out server.p12 -name [some-alias] \
-CAfile ca.crt -caname root
Note: Make sure you put a password on the pkcs12 file - otherwise you'll get a null pointer exception when you try to import it. (In case anyone else had this headache). (Thanks jocull!)
Note 2: You might want to add the -chain
option to preserve the full certificate chain. (Thanks Mafuba)
Step two: Convert the pkcs12 file to a Java keystore
keytool -importkeystore \
-deststorepass [changeit] -destkeypass [changeit] -destkeystore server.keystore \
-srckeystore server.p12 -srcstoretype PKCS12 -srcstorepass some-password \
-alias [some-alias]
Finished
OPTIONAL Step zero: Create self-signed certificate
openssl genrsa -out server.key 2048
openssl req -new -out server.csr -key server.key
openssl x509 -req -days 365 -in server.csr -signkey server.key -out server.crt
Cheers!
Usually, you do not want to add anything to a Request object, it's better to use collection and put()
helper:
function store(Request $request)
{
// some additional logic or checking
User::create(array_merge($request->all(), ['index' => 'value']));
}
Or you could union arrays:
User::create($request->all() + ['index' => 'value']);
But, if you really want to add something to a Request object, do this:
$request->request->add(['variable' => 'value']); //add request
There important changes to the Connector/J API going from version 5.1 to 8.0. You might need to adjust your API calls accordingly if the version you are using falls above 5.1.
please visit MySQL on the following link for more information https://dev.mysql.com/doc/connector-j/8.0/en/connector-j-api-changes.html
The ECMAScript 6 version (aka ECMAScript 2015) of JavaScript introduced string literals.
var classType = "stringbuilder";
var q = `Does JavaScript have a built-in ${classType} class?`;
Notice that back-ticks, instead of single quotes, enclose the string.
RabbitMQ has 2 things under queue
Delete - will delete the queue
Purge - This will empty the queue (meaning removes messages from the queue but queue still exists)
To perform a linear regression between two vectors x
and y
follow these steps:
[p,err] = polyfit(x,y,1); % First order polynomial
y_fit = polyval(p,x,err); % Values on a line
y_dif = y - y_fit; % y value difference (residuals)
SSdif = sum(y_dif.^2); % Sum square of difference
SStot = (length(y)-1)*var(y); % Sum square of y taken from variance
rsq = 1-SSdif/SStot; % Correlation 'r' value. If 1.0 the correlelation is perfect
For x=[10;200;7;150]
and y=[0.001;0.45;0.0007;0.2]
I get rsq = 0.9181
.
Reference URL: http://www.mathworks.com/help/matlab/data_analysis/linear-regression.html
The command palette
tells you the colours and their order when col = somefactor
. It can also be used to set the colours as well.
palette()
[1] "black" "red" "green3" "blue" "cyan" "magenta" "yellow" "gray"
In order to see that in your graph you could use a legend.
legend('topright', legend = levels(iris$Species), col = 1:3, cex = 0.8, pch = 1)
You'll notice that I only specified the new colours with 3 numbers. This will work like using a factor. I could have used the factor originally used to colour the points as well. This would make everything logically flow together... but I just wanted to show you can use a variety of things.
You could also be specific about the colours. Try ?rainbow
for starters and go from there. You can specify your own or have R do it for you. As long as you use the same method for each you're OK.
I have found a simpler answer to this problem. I simply use reverse logic. The code is in VB but it is not much different than C#.
Private Sub DataGridView1_CellContentClick(sender As Object, e As
DataGridViewCellEventArgs) Handles DataGridView1.CellContentClick
Dim _ColumnIndex As Integer = e.ColumnIndex
Dim _RowIndex As Integer = e.RowIndex
'Uses reverse logic for current cell because checkbox checked occures
'after click
'If you know current state is False then logic dictates that a click
'event will set it true
'With these 2 check boxes only one can be true while both can be off
If DataGridView1.Rows(_RowIndex).Cells("Column2").Value = False And
DataGridView1.Rows(_RowIndex).Cells("Column3").Value = True Then
DataGridView1.Rows(_RowIndex).Cells("Column3").Value = False
End If
If DataGridView1.Rows(_RowIndex).Cells("Column3").Value = False And
DataGridView1.Rows(_RowIndex).Cells("Column2").Value = True Then
DataGridView1.Rows(_RowIndex).Cells("Column2").Value = False
End If
End Sub
One of the best things about this is no need for multiple events.
You will need to cast or convert the values to decimal before division. Take a look at this http://msdn.microsoft.com/en-us/library/aa226054.aspx
For example
DECLARE @num1 int = 3 DECLARE @num2 int = 2
SELECT @num1/@num2
SELECT @num1/CONVERT(decimal(4,2), @num2)
The first SELECT will result in what you're seeing while the second SELECT will have the correct answer 1.500000
swal({
title: 'Are you sure?',
text: "You won't be able to revert this!",
type: 'warning',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: 'Confirm!'
}).then(function(){
alert("The confirm button was clicked");
}).catch(function(reason){
alert("The alert was dismissed by the user: "+reason);
});
.innerText
doesnt work in Firefox.
.innerHTML
works in both the browsers.
Given the comment of "say Windows XP as an example", then your options are:
Interact directly with the operating system via its API, which for Microsoft Windows is surprise surprise call Windows API. The definitive reference for the WinAPI is Microsoft's MSDN website. A popular online beginner tutorial for that is theForger's Win32 API Programming Tutorial. The classic book for that is Charles Petzold's Programming Windows, 5th Edition.
Use a platform (both in terms of OS and compiler) specific library such as MFC, which wraps the WinAPI into C++ class. The reference for that is again MSDN. A classic book for that is Jeff Prosise's Programming Windows with MFC, 2nd Edition. If you are using say CodeGear C++ Builder, then the option here is VCL.
Use a cross platform library such as GTK+ (C++ wrapper: gtkmm), Qt, wxWidgets, or FLTK that wrap the specific OS's API. The advantages with these are that in general, your program could been compiled for different OS without having to change the source codes. As have already been mentioned, they each have its own strengths and weaknesses. One consideration when selecting which one to use is its license. For the examples given, GTK+ & gtkmm is license under LGPL, Qt is under various licenses including proprietary option, wxWidgets is under its own wxWindows Licence (with a rename to wxWidgets Licence), and FLTK is under LGPL with exception. For reference, tutorial, and or books, refer to each one's website for details.
If its SQL Server you can do it on the column properties within design view
Try this?:
ALTER TABLE dbo.TableName
ADD CONSTRAINT DF_TableName_ColumnName
DEFAULT '01/01/2000' FOR ColumnName
Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.
On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.
The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.
Sources:
Via Enterprise Manager (SSMS)...
To see the SQL you can then right click on the Table
> Script Table As
> Create To
Almost all CPUs use stack. The program stack is LIFO technique with hardware supported manage.
Stack is amount of program (RAM) memory normally allocated at the top of CPU memory heap and grow (at PUSH instruction the stack pointer is decreased) in opposite direction. A standard term for inserting into stack is PUSH and for remove from stack is POP.
Stack is managed via stack intended CPU register, also called stack pointer, so when CPU perform POP or PUSH the stack pointer will load/store a register or constant into stack memory and the stack pointer will be automatic decreased xor increased according number of words pushed or poped into (from) stack.
Via assembler instructions we can store to stack:
I had a similar situation where a download needed to stay active overnight and required a key press that refreshed my connection. I also found that the mouse move does not work. However, using notepad and a send key function appears to have done the trick. I send a space instead of a "." because if there is a [yes/no] popup, it will automatically click the default response using the spacebar. Here is the code used.
param($minutes = 120)
$myShell = New-Object -com "Wscript.Shell"
for ($i = 0; $i -lt $minutes; $i++) {
Start-Sleep -Seconds 30
$myShell.sendkeys(" ")
}
This function will work for the designated 120 minutes (2 Hours), but can be modified for the timing desired by increasing or decreasing the seconds of the input, or increasing or decreasing the assigned value of the minutes parameter.
Just run the script in powershell ISE, or powershell, and open notepad. A space will be input at the specified interval for the desired length of time ($minutes).
Good Luck!
As @TomMcKenzie says in a comment to another answer, date -r 123456789
is arguably a more common (i.e. more widely implemented) simple solution for times given as seconds since the Unix Epoch, but unfortunately there's no universal guaranteed portable solution.
The -d
option on many types of systems means something entirely different than GNU Date's --date
extension. Sadly GNU Date doesn't interpret -r
the same as these other implementations. So unfortunately you have to know which version of date
you're using, and many older Unix date
commands don't support either option.
Even worse, POSIX date
recognizes neither -d
nor -r
and provides no standard way in any command at all (that I know of) to format a Unix time from the command line (since POSIX Awk also lacks strftime()
). (You can't use touch -t
and ls
because the former does not accept a time given as seconds since the Unix Epoch.)
Note though The One True Awk available direct from Brian Kernighan does now have the strftime()
function built-in as well as a systime()
function to return the current time in seconds since the Unix Epoch), so perhaps the Awk solution is the most portable.
If you want to increase the height of the input field, you can specify line-height
css property for the input field.
input {
line-height: 2em; // 2em is (2 * default line height)
}
In python 2.6 the '%' operator performed a modulus. I don't think they changed it in 3.0.1
The modulo operator tells you the remainder of a division of two numbers.
Add this 2 lines in your code -
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());?
We can create static constructor
static class StaticParent
{
StaticParent()
{
//write your initialization code here
}
}
and it is always parameter less.
static class StaticParent
{
static int i =5;
static StaticParent(int i) //Gives error
{
//write your initialization code here
}
}
and it doesn't have the access modifier
See here: http://docs.python.org/using/windows.html
pythonw.exe "This suppresses the terminal window on startup."
<kdb></kdb>
is required when we have a space in Alias Name like
SELECT employee_id,department_id AS "Department ID"
FROM employees
order by department
Okay, this is still not the best possible solution, but a nice point to start. I wrote a little Java app that calculates the contrast ratio of two colors and only processes colors with a ratio of 5:1 or better - this ratio and the formula I use has been released by the W3C and will probably replace the current recommendation (which I consider very limited). It creates a file in the current working dir named "chosen-font-colors.html", with the background color of your choice and a line of text in every color that passed this W3C test. It expects a single argument, being the background color.
E.g. you can call it like this
java FontColorChooser 33FFB4
then just open the generated HTML file in a browser of your choice and choose a color from the list. All colors given passed the W3C test for this background color. You can change the cut off by replacing 5 with a number of your choice (lower numbers allow weaker contrasts, e.g. 3 will only make sure contrast is 3:1, 10 will make sure it is at least 10:1) and you can also cut off to avoid too high contrasts (by making sure it is smaller than a certain number), e.g. adding
|| cDiff > 18.0
to the if clause will make sure contrast won't be too extreme, as too extreme contrasts can stress your eyes. Here's the code and have fun playing around with it a bit :-)
import java.io.*;
/* For text being readable, it must have a good contrast difference. Why?
* Your eye has receptors for brightness and receptors for each of the colors
* red, green and blue. However, it has much more receptors for brightness
* than for color. If you only change the color, but both colors have the
* same contrast, your eye must distinguish fore- and background by the
* color only and this stresses the brain a lot over the time, because it
* can only use the very small amount of signals it gets from the color
* receptors, since the breightness receptors won't note a difference.
* Actually contrast is so much more important than color that you don't
* have to change the color at all. E.g. light red on dark red reads nicely
* even though both are the same color, red.
*/
public class FontColorChooser {
int bred;
int bgreen;
int bblue;
public FontColorChooser(String hexColor) throws NumberFormatException {
int i;
i = Integer.parseInt(hexColor, 16);
bred = (i >> 16);
bgreen = (i >> 8) & 0xFF;
bblue = i & 0xFF;
}
public static void main(String[] args) {
FontColorChooser fcc;
if (args.length == 0) {
System.out.println("Missing argument!");
System.out.println(
"The first argument must be the background" +
"color in hex notation."
);
System.out.println(
"E.g. \"FFFFFF\" for white or \"000000\" for black."
);
return;
}
try {
fcc = new FontColorChooser(args[0]);
} catch (Exception e) {
System.out.println(
args[0] + " is no valid hex color!"
);
return;
}
try {
fcc.start();
} catch (IOException e) {
System.out.println("Failed to write output file!");
}
}
public void start() throws IOException {
int r;
int b;
int g;
OutputStreamWriter out;
out = new OutputStreamWriter(
new FileOutputStream("chosen-font-colors.html"),
"UTF-8"
);
// simple, not W3C comform (most browsers won't care), HTML header
out.write("<html><head><title>\n");
out.write("</title><style type=\"text/css\">\n");
out.write("body { background-color:#");
out.write(rgb2hex(bred, bgreen, bblue));
out.write("; }\n</style></head>\n<body>\n");
// try 4096 colors
for (r = 0; r <= 15; r++) {
for (g = 0; g <= 15; g++) {
for (b = 0; b <= 15; b++) {
int red;
int blue;
int green;
double cDiff;
// brightness increasse like this: 00, 11,22, ..., ff
red = (r << 4) | r;
blue = (b << 4) | b;
green = (g << 4) | g;
cDiff = contrastDiff(
red, green, blue,
bred, bgreen, bblue
);
if (cDiff < 5.0) continue;
writeDiv(red, green, blue, out);
}
}
}
// finalize HTML document
out.write("</body></html>");
out.close();
}
private void writeDiv(int r, int g, int b, OutputStreamWriter out)
throws IOException
{
String hex;
hex = rgb2hex(r, g, b);
out.write("<div style=\"color:#" + hex + "\">");
out.write("This is a sample text for color " + hex + "</div>\n");
}
private double contrastDiff(
int r1, int g1, int b1, int r2, int g2, int b2
) {
double l1;
double l2;
l1 = (
0.2126 * Math.pow((double)r1/255.0, 2.2) +
0.7152 * Math.pow((double)g1/255.0, 2.2) +
0.0722 * Math.pow((double)b1/255.0, 2.2) +
0.05
);
l2 = (
0.2126 * Math.pow((double)r2/255.0, 2.2) +
0.7152 * Math.pow((double)g2/255.0, 2.2) +
0.0722 * Math.pow((double)b2/255.0, 2.2) +
0.05
);
return (l1 > l2) ? (l1 / l2) : (l2 / l1);
}
private String rgb2hex(int r, int g, int b) {
String rs = Integer.toHexString(r);
String gs = Integer.toHexString(g);
String bs = Integer.toHexString(b);
if (rs.length() == 1) rs = "0" + rs;
if (gs.length() == 1) gs = "0" + gs;
if (bs.length() == 1) bs = "0" + bs;
return (rs + gs + bs);
}
}
Remember that when you restart the database by removing .lock files by force, the data might get corrupted. Your server shouldn't be considered "healthy" if you restarted the server that way.
To amend the situation, either run
mongod --repair
or
> db.repairDatabase();
in the mongo shell to bring your database back to "healthy" state.
I tried to do this in next way
public static DataTable JoinTwoTables(DataTable innerTable, DataTable outerTable)
{
DataTable resultTable = new DataTable();
var innerTableColumns = new List<string>();
foreach (DataColumn column in innerTable.Columns)
{
innerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
var outerTableColumns = new List<string>();
foreach (DataColumn column in outerTable.Columns)
{
if (!innerTableColumns.Contains(column.ColumnName))
{
outerTableColumns.Add(column.ColumnName);
resultTable.Columns.Add(column.ColumnName);
}
}
for (int i = 0; i < innerTable.Rows.Count; i++)
{
var row = resultTable.NewRow();
innerTableColumns.ForEach(x =>
{
row[x] = innerTable.Rows[i][x];
});
outerTableColumns.ForEach(x =>
{
row[x] = outerTable.Rows[i][x];
});
resultTable.Rows.Add(row);
}
return resultTable;
}
You can use cookies if the data is small enough and does not present a security concern. The same HttpContext.Current based approach should work.
Request and response HTTP headers can also be used to pass information between service calls.
Specifying the path to the DLL file in your project's settings does not ensure that your application will find the DLL at run-time. You only told Visual Studio how to find the files it needs. That has nothing to do with how the program finds what it needs, once built.
Placing the DLL file into the same folder as the executable is by far the simplest solution. That's the default search path for dependencies, so you won't need to do anything special if you go that route.
To avoid having to do this manually each time, you can create a Post-Build Event for your project that will automatically copy the DLL into the appropriate directory after a build completes.
Alternatively, you could deploy the DLL to the Windows side-by-side cache, and add a manifest to your application that specifies the location.
This should work perfect just copy this div code
<div onclick="thevid=document.getElementById('thevideo'); thevid.style.display='block'; this.style.display='none'">
<img style="cursor: pointer;" alt="" src="http://oi59.tinypic.com/33trpyo.jpg" />
</div>
<div id="thevideo" style="display: none;">
<embed width="631" height="466" type="application/x-shockwave-flash" src="https://www.youtube.com/v/26EpwxkU5js?version=3&hl=en_US&autoplay=1" allowFullScreen="true" allowscriptaccess="always" allowfullscreen="true" />
</div>
Give zero to mindate
and it'll disabale past dates.
$( "#datepicker" ).datepicker({ minDate: 0});
here is a Live fiddle working example http://jsfiddle.net/mayooresan/ZL2Bc/
What do you mean by converting?
(int) $float
or intval($float)
floor($float)
(down) or ceil($float)
(up)round($float)
- has additional modes, see PHP_ROUND_HALF_...
constants*: casting has some chance, that float values cannot be represented in int (too big, or too small), f.ex. in your case.
PHP_INT_MAX
: The largest integer supported in this build of PHP. Usually int(2147483647).
But, you could use the BCMath, or the GMP extensions for handling these large numbers. (Both are boundled, you only need to enable these extensions)
typedef
defines a new data type. So you can have:
typedef char* my_string;
typedef struct{
int member1;
int member2;
} my_struct;
So now you can declare variables with these new data types
my_string s;
my_struct x;
s = "welcome";
x.member1 = 10;
For enum
, things are a bit different - consider the following examples:
enum Ranks {FIRST, SECOND};
int main()
{
int data = 20;
if (data == FIRST)
{
//do something
}
}
using typedef enum
creates an alias for a type:
typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
Order data = (Order)20; // Must cast to defined type to prevent error
if (data == FIRST)
{
//do something
}
}
Add your li
to a class, and do $(".myclass").hide();
at the start to hide it instead of the visibility style attribute.
As far as I know, jquery uses the display
style attribute to show/hide elements instead of visibility (may be wrong on that one, in either case the above is worth trying)
How do I edit my global Git configuration?
Short answer: git config --edit --global
To understand Git configuration, you should know that:
Git configuration variables can be stored at three different levels. Each level overrides values at the previous level.
1. System level (applied to every user on the system and all their repositories)
git config --list --system
(may need sudo
)git config --system color.ui true
git config --edit --system
2. Global level (values specific personally to you, the user).
git config --list --global
git config --global user.name xyz
git config --edit --global
3. Repository level (specific to that single repository)
git config --list --local
git config --local core.ignorecase true
(--local
optional)git config --edit --local
(--local
optional)How do I view all settings?
git config --list
, showing system, global, and (if inside a repository) local configsgit config --list --show-origin
, also shows the origin file of each config itemHow do I read one particular configuration?
git config user.name
to get user.name
, for example.--system
, --global
, --local
to read that value at a particular level.Reference: 1.6 Getting Started - First-Time Git Setup
You could do something like this:
public function __construct($param)
{
if(is_int($param)) {
$this->id = $param;
} elseif(is_object($param)) {
// do something else
}
}
Just run graphics.off()
before plotting your data.
This instruction solved my error. So, it's harmless to try it before taking a more complex solution.
I wish comments had proper code text formatting, because I think @1_CR 's answer needs more bumps, and I would like to augment his answer. Anyway, He led me to the following technique; it will use cStringIO if available (BUT NOTE: cStringIO and StringIO are not the same, because you cannot subclass cStringIO... it is a built-in... but for basic operations the syntax will be identical, so you can do this):
try:
import cStringIO
StringIO = cStringIO
except ImportError:
import StringIO
for line in StringIO.StringIO(variable_with_multiline_string):
pass
print line.strip()
I came across a wonderful piece of code to check whether or not an element is a child of another element. I have to use this because IE doesn't support the .contains
element method. Hope this will help others as well.
Below is the function:
function isChildOf(childObject, containerObject) {
var returnValue = false;
var currentObject;
if (typeof containerObject === 'string') {
containerObject = document.getElementById(containerObject);
}
if (typeof childObject === 'string') {
childObject = document.getElementById(childObject);
}
currentObject = childObject.parentNode;
while (currentObject !== undefined) {
if (currentObject === document.body) {
break;
}
if (currentObject.id == containerObject.id) {
returnValue = true;
break;
}
// Move up the hierarchy
currentObject = currentObject.parentNode;
}
return returnValue;
}
This is the way to be absolutely certain :
<!doctype html> <!-- html5 -->
<html lang="en"> <!-- lang="xx" is allowed, but NO xmlns="http://www.w3.org/1999/xhtml", lang:xml="", and so on -->
<head>
<meta http-equiv="x-ua-compatible" content="IE=Edge"/>
<!-- as the **very** first line just after head-->
..
</head>
Reason :
Whenever IE meets anything that conflicts, it turns back to "IE 7 standards mode", ignoring the x-ua-compatible
.
(I know this is an answer to a very old question, but I have struggled with this myself, and above scheme is the correct answer. It works all the way, everytime)
[[]]*3
is not the same as [[], [], []]
.
It's as if you'd said
a = []
listy = [a, a, a]
In other words, all three list references refer to the same list instance.
You can use the update()
method as well
d = {"a": 2}
d.update{"b": 4}
print(d) # {"a": 2, "b": 4}
Forward declaration just to the prevent compiler from showing error.
the compiler will know that there is class with the name you've used in your header file to declare.
You could use:
line.Replace(@"\", "");
or
line.Replace(@"\", string.Empty);
Do your databinding and then add the following:
Dim liFirst As New ListItem("", "")
drpList.Items.Insert(0, liFirst)
Just remove the backdrop, insert this code in your css file
.modal-backdrop {
/* bug fix - no overlay */
display: none;
}
Another workaround would be to make use of prettier to format the JSON. The example below is using 'json' parser but it could also use 'json5', see list of valid parsers.
const prettier = require("prettier");
console.log(prettier.format(JSON.stringify(object),{ semi: false, parser: "json" }));
If anyone is coming here looking for an answer that utilizes iframe
here it is
<iframe srcdoc="<html><body>your-html-here</body></html>" />
I've used another practice for this problem with multer dependancie.
Example:
multer = require('multer');
var uploading = multer({
limits: {fileSize: 1000000, files:1},
});
exports.uploadpictureone = function(req, res) {
cloudinary.uploader.upload(req.body.url, function(result) {
res.send(result);
});
};
module.exports = function(app) {
app.route('/api/upload', uploading).all(uploadPolicy.isAllowed)
.post(upload.uploadpictureone);
};
Generating a single random number in a program is problematic. Random number generators are only "random" in the sense that repeated invocations produce numbers from a given probability distribution.
Seeding the RNG won't help, especially if you just seed it from a low-resolution timer. You'll just get numbers that are a hash function of the time, and if you call the program often, they may not change often. You might improve a little bit by using srand(time(NULL) + getpid())
(_getpid()
on Windows), but that still won't be random.
The ONLY way to get numbers that are random across multiple invocations of a program is to get them from outside the program. That means using a system service such as /dev/random
(Linux) or CryptGenRandom()
(Windows), or from a service like random.org
.
If you are using Microsoft windows environment then you can set a variable named HTTP_PROXY
, FTP_PROXY
, or HTTPS_PROXY
depending on the requirement.
I have used following settings for allowing my commands at windows command prompt to use the browser proxy to access internet.
set HTTP_PROXY=http://proxy_userid:proxy_password@proxy_ip:proxy_port
The parameters on right must be replaced with actual values.
Once the variable HTTP_PROXY
is set, all our subsequent commands executed at windows command prompt will be able to access internet through the proxy along with the authentication provided.
Additionally if you want to use ftp and https as well to use the same proxy then you may like to the following environment variables as well.
set FTP_PROXY=%HTTP_PROXY%
set HTTPS_PROXY=%HTTP_PROXY%
Like so:
filtered_list = [i for (i, v) in zip(list_a, filter) if v]
Using zip
is the pythonic way to iterate over multiple sequences in parallel, without needing any indexing. This assumes both sequences have the same length (zip stops after the shortest runs out). Using itertools
for such a simple case is a bit overkill ...
One thing you do in your example you should really stop doing is comparing things to True, this is usually not necessary. Instead of if filter[idx]==True: ...
, you can simply write if filter[idx]: ...
.
This syntax does not exist in Java, nor is it slated to be included in any of the upcoming versions that I know of.
For Bootstrap:
<div class="navbar-fixed-bottom row-fluid">
<div class="navbar-inner">
<div class="container">
Text
</div>
</div>
</div>
Just to add to CKoenig's response. His answer will work as long as the class you're dealing with is a reference type (like a class). If the custom object were a struct, this is a value type, and the results of .FirstOrDefault
will give you a local copy of that, which will mean it won't persist back to the collection, as this example shows:
struct MyStruct
{
public int TheValue { get; set; }
}
Test code:
List<MyStruct> coll = new List<MyStruct> {
new MyStruct {TheValue = 10},
new MyStruct {TheValue = 1},
new MyStruct {TheValue = 145},
};
var found = coll.FirstOrDefault(c => c.TheValue == 1);
found.TheValue = 12;
foreach (var myStruct in coll)
{
Console.WriteLine(myStruct.TheValue);
}
Console.ReadLine();
The output is 10,1,145
Change the struct to a class and the output is 10,12,145
HTH
Keeping your code human readable not just machine readable. A lot of devices still can only show 80 characters at a time. Also it makes it easier for people with larger screens to multi-task by being able to set up multiple windows to be side by side.
Readability is also one of the reasons for enforced line indentation.
For Windows Server® 2008, Windows 7, Windows Server 2003, Windows Vista®, or Windows XP run "control userpasswords2"
Click the Start button, then click Run (Windows XP, Server 2003 or below)
Type control userpasswords2 and press Enter on your keyboard.
Note: For Windows 7 and Windows Vista, this command will not run by typing it in the Serach box on the Start Menu - it must be run using the Run option. To add the Run command to your Start menu, right-click on it and choose the option to customize it, then go to the Advanced options. Check to option to add the Run command.
You will see a window of user details!
Here's an example:
#Create a data frame
> d<- data.frame(a=1:3, b=2:4)
> d
a b
1 1 2
2 2 3
3 3 4
#currently, there are no levels in the `a` column, since it's numeric as you point out.
> levels(d$a)
NULL
#Convert that column to a factor
> d$a <- factor(d$a)
> d
a b
1 1 2
2 2 3
3 3 4
#Now it has levels.
> levels(d$a)
[1] "1" "2" "3"
You can also handle this when reading in your data. See the colClasses
and stringsAsFactors
parameters in e.g. readCSV()
.
Note that, computationally, factoring such columns won't help you much, and may actually slow down your program (albeit negligibly). Using a factor will require that all values are mapped to IDs behind the scenes, so any print of your data.frame requires a lookup on those levels -- an extra step which takes time.
Factors are great when storing strings which you don't want to store repeatedly, but would rather reference by their ID. Consider storing a more friendly name in such columns to fully benefit from factors.
the Conda Package Manager is almost ready for beta testing, but it will not be fully integrated until the release of Spyder 2.4 (https://github.com/spyder-ide/spyder/wiki/Roadmap). As soon as we have it ready for testing we will post something on the mailing list (https://groups.google.com/forum/#!forum/spyderlib). Be sure to subscribe
Cheers!
Solution
Angular2 developed on the ground of modern technologies like TypeScript and ES6.
So you can just do let copy = Object.assign({}, myObject)
.
Object assign - nice examples.
For nested objects :
let copy = JSON.parse(JSON.stringify(myObject))
Make the script executable by the user "Kev" and then remove the try it running through the command
sh kev@server1 /test/foo.sh
Consider removing the .gitignore file if you want to remove any trace of Git in your project.
** Consider leaving the .gitignore file if you would ever want reincorporate Git into the project.
Some frameworks may automatically produce the .gitignore file so you may want to leave it.
Open a terminal and navigate to the directory of your project, i.e. - cd path_to_your_project
.
Run this command:
rm -rf .git*
This will remove the Git tracking and metadata from your project. If you want to keep the metadata (such as .gitignore and .gitkeep), you can delete only the tracking by running rm -rf .git
.
The rmdir
or rd
command will not delete/remove any hidden files or folders within the directory you specify, so you should use the del
command to be sure that all files are removed from the .git
folder.
Open the command prompt
Either click Start
then Run
or hit the key and r at the same time.
Type cmd
and hit enter
Navigate to the project directory, i.e. - cd path_to_your_project
Run these commands
del /F /S /Q /A .git
rmdir .git
The first command removes all files and folder within the .git
folder. The second removes the .git
folder itself.
Open the file explorer and navigate to your project
Show hidden files and folders - refer to this article for a visual guide
In the view menu on the toolbar, select Options
In the Advanced Settings
section, find Hidden files and Folders
under the Files and Folders
list and select Show hidden files and folders
Close the options menu and you should see all hidden folders and files including the .git
folder.
Delete the
.git
folder Delete the.gitignore
file ** (see note at the top of this answer)
Yet another/simple alternative (model identifier reference found at https://www.theiphonewiki.com/wiki/Models):
Updated answer for Swift 3/4/5 including string trimming and simulator support:
func modelIdentifier() -> String {
if let simulatorModelIdentifier = ProcessInfo().environment["SIMULATOR_MODEL_IDENTIFIER"] { return simulatorModelIdentifier }
var sysinfo = utsname()
uname(&sysinfo) // ignore return value
return String(bytes: Data(bytes: &sysinfo.machine, count: Int(_SYS_NAMELEN)), encoding: .ascii)!.trimmingCharacters(in: .controlCharacters)
}
You can use the below simple method of sorting:
datatable.DefaultView.Sort = "Col2 ASC,Col3 ASC,Col4 ASC";
By the above method, you will be able to sort N number of columns.
No, but it's been requested many times.
Yes, presumably it wants the path to the javadoc
command line tool that comes with the JDK (in the bin directory, same as java
and javac
).
Eclipse should be able to find it automatically; are you perhaps running it on a JRE? That would explain the request.
The way you have synchronized is correct. But there is a catch
However in real world you would generally query the map before putting in the value. Hence you would need to do two operations and hence a synchronized block is needed. So the way you have used it is correct. However.
a. It has a API 'putIfAbsent' which would do the same stuff but in a more efficient manner.
b. Its Efficient: dThe CocurrentMap just locks keys hence its not blocking the whole map's world. Where as you have blocked keys as well as values.
c. You could have passed the reference of your map object somewhere else in your codebase where you/other dev in your tean may end up using it incorrectly. I.e he may just all add() or get() without locking on the map's object. Hence his call won't run mutually exclusive to your sync block. But using a concurrent implementation gives you a peace of mind that it can never be used/implemented incorrectly.
Five ways, 4 for bash and 1 addition for zsh:
type foobar &> /dev/null
hash foobar &> /dev/null
command -v foobar &> /dev/null
which foobar &> /dev/null
(( $+commands[foobar] ))
(zsh only)You can put any of them to your if
clause. According to my tests (https://www.topbug.net/blog/2016/10/11/speed-test-check-the-existence-of-a-command-in-bash-and-zsh/), the 1st and 3rd method are recommended in bash and the 5th method is recommended in zsh in terms of speed.
The permission denied error probably indicates that SSH private key authentication has failed. Assuming that you're using an image derived from the Debian or Centos images recommended by gcutil, it's likely one of the following:
-i
option.There's a script that runs every minute on the standard Compute Engine Centos and Debian images which fetches the 'sshKeys' metadata entry from the metadata server, and creates accounts (with sudoers access) as necessary. This script expects entries of the form "account:\n" in the sshKeys metadata, and can put several entries into authorized_keys for a single account. (or create multiple accounts if desired)
In recent versions of the image, this script sends its output to the serial port via syslog, as well as to the local logs on the machine. You can read the last 1MB of serial port output via gcutil getserialportoutput
, which can be handy when the machine isn't responding via SSH.
gcutil ssh
works:gcutil ssh
does the following:
$HOME/.ssh/google_compute_engine
, and calls ssh-keygen
to create one if not present.sshKeys
for an entry that looks like ${USER}:$(cat $HOME/.ssh/google_compute_engine.pub)
gcutil ssh
invokes ssh
with a few command-line arguments to connect to the VM.sshKeys
, the console and command line tool won't realize that modifying sshKeys
doesn't work, and a lot of the automatic magic above can get broken.ssh
, it may not find your .ssh/google_compute_engine
key. You can fix this by using gcutil ssh
, or by copying your ssh public key (ends in .pub
) and adding to the sshKeys
entry for the project or instance in the console. (You'll also need to put in a username, probably the same as your local-machine account name.)gcutil ssh
, you probably don't have a .ssh/google_compute_engine.pub
file. You can either use ssh-keygen
to create a new SSH public/private keypair and add it to sshKeys
, as above, or use gcutil ssh
to create them and manage sshKeys
.sshKeys
entry doesn't match your local username, you may need to supply the -l
argument to SSH.You can set a default option for the column in the migration
....
add_column :status, :string, :default => "P"
....
OR
You can use a callback, before_save
class Task < ActiveRecord::Base
before_save :default_values
def default_values
self.status ||= 'P' # note self.status = 'P' if self.status.nil? might be safer (per @frontendbeauty)
end
end
Guava Math library has a method specially designed for converting a double to a long:
long DoubleMath.roundToLong(double x, RoundingMode mode)
You can use java.math.RoundingMode
to specify the rounding behavior.
ftps -a -z -e:on -pfxfile:"S-PID.p12" -pfxpwfile:"S-PID.p12.pwd" -user:<S-PID number> -s:script <RemoteServerName> 2121
S-PID.p12 => certificate file name ;
S-PID.p12.pwd => certificate password file name ;
RemoteServerName => abcd123 ;
2121 => port number ;
ftps => command is part of ftps client software ;
In Java, you can verify using Object utils.
import static java.util.Objects.isNull;
if(IsNull(yourObject)){
//your block here
}
Active mode: -server initiates the connection.
Passive mode: -client initiates the connection.
I posted a fiddle here, showing data, remote and local images embedded in SVG, inside an HTML page:
<!DOCTYPE html>
<html>
<head>
<title>SVG embedded bitmaps in HTML</title>
<style>
body{
background-color:#999;
color:#666;
padding:10px;
}
h1{
font-weight:normal;
font-size:24px;
margin-top:20px;
color:#000;
}
h2{
font-weight:normal;
font-size:20px;
margin-top:20px;
}
p{
color:#FFF;
}
svg{
margin:20px;
display:block;
height:100px;
}
</style>
</head>
<body>
<h1>SVG embedded bitmaps in HTML</h1>
<p>The trick appears to be ensuring the image has the correct width and height atttributes</p>
<h2>Example 1: Embedded data</h2>
<svg id="example1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="5" height="5" xlink:href="data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHElEQVQI12P4//8/w38GIAXDIBKE0DHxgljNBAAO9TXL0Y4OHwAAAABJRU5ErkJggg=="/>
</svg>
<h2>Example 2: Remote image</h2>
<svg id="example2" version="1.1" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="275" height="95" xlink:href="http://www.google.co.uk/images/srpr/logo3w.png" />
</svg>
<h2>Example 3: Local image</h2>
<svg id="example3" xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink">
<image x="0" y="0" width="136" height="23" xlink:href="/img/logo.png" />
</svg>
</body>
</html>
if you are trying to use jquery in your electron app before adding jquery you should add it to your modules:
<script>
if (typeof module === 'object') {
window.module = module;
module = undefined;
}
</script>
<script src="js/jquery-3.5.1.min.js"></script>
i updated the way you can compile and run redis 5 on windows 10 using cygwin https://github.com/meiry/redis5_compiled_for_windows10
It's this simple:
var a = [[12, 'AAA'], [58, 'BBB'], [28, 'CCC'],[18, 'DDD']];
a.sort(sortFunction);
function sortFunction(a, b) {
if (a[0] === b[0]) {
return 0;
}
else {
return (a[0] < b[0]) ? -1 : 1;
}
}
I invite you to read the documentation.
If you want to sort by the second column, you can do this:
a.sort(compareSecondColumn);
function compareSecondColumn(a, b) {
if (a[1] === b[1]) {
return 0;
}
else {
return (a[1] < b[1]) ? -1 : 1;
}
}
Here's an example of an all-xaml solution. It binds to an "IsWorking" boolean in the viewmodel to show the control and start the animation.
<UserControl x:Class="MainApp.Views.SpinnerView"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
mc:Ignorable="d"
d:DesignHeight="300" d:DesignWidth="300">
<UserControl.Resources>
<BooleanToVisibilityConverter x:Key="BoolToVisConverter"/>
</UserControl.Resources>
<StackPanel Orientation="Horizontal" Margin="5"
Visibility="{Binding IsWorking, Converter={StaticResource BoolToVisConverter}}">
<Label>Wait...</Label>
<Ellipse x:Name="spinnerEllipse"
Width="20" Height="20">
<Ellipse.Fill>
<LinearGradientBrush StartPoint="1,1" EndPoint="0,0" >
<GradientStop Color="White" Offset="0"/>
<GradientStop Color="CornflowerBlue" Offset="1"/>
</LinearGradientBrush>
</Ellipse.Fill>
<Ellipse.RenderTransform>
<RotateTransform x:Name="SpinnerRotate" CenterX="10" CenterY="10"/>
</Ellipse.RenderTransform>
<Ellipse.Style>
<Style TargetType="Ellipse">
<Style.Triggers>
<DataTrigger Binding="{Binding IsWorking}" Value="True">
<DataTrigger.EnterActions>
<BeginStoryboard x:Name="SpinStoryboard">
<Storyboard TargetProperty="RenderTransform.Angle" >
<DoubleAnimation
From="0" To="360" Duration="0:0:01"
RepeatBehavior="Forever" />
</Storyboard>
</BeginStoryboard>
</DataTrigger.EnterActions>
<DataTrigger.ExitActions>
<StopStoryboard BeginStoryboardName="SpinStoryboard"></StopStoryboard>
</DataTrigger.ExitActions>
</DataTrigger>
</Style.Triggers>
</Style>
</Ellipse.Style>
</Ellipse>
</StackPanel>
</UserControl>
A couple of issues
>
in -exec
without something like bash -c '... > ...'
. Though the >
will overwrite the file, so you want to redirect the entire find
anyway rather than each -exec
. +30
is older
than 30 days, -30
would be modified in last 30 days.-exec
really isn't needed, you could list everything with various -printf
options. Something like below should work
find . -type f -mtime -30 -exec ls -l {} \; > last30days.txt
Example with -printf
find . -type f -mtime -30 -printf "%M %u %g %TR %TD %p\n" > last30days.txt
This will list files in format "permissions owner group time date filename". -printf
is generally preferable to -exec
in cases where you don't have to do anything complicated. This is because it will run faster as a result of not having to execute subshells for each -exec
. Depending on the version of find
, you may also be able to use -ls
, which has a similar format to above.
I too got this same error on my image handler that I wrote. I got it like 30 times a day on site with heavy traffic, managed to reproduce it also. You get this when a user cancels the request (closes the page or his internet connection is interrupted for example), in my case in the following row:
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
I can’t think of any way to prevent it but maybe you can properly handle this. Ex:
try
{
…
myContext.Response.OutputStream.Write(buffer, 0, bytesRead);
…
}catch (HttpException ex)
{
if (ex.Message.StartsWith("The remote host closed the connection."))
;//do nothing
else
//handle other errors
}
catch (Exception e)
{
//handle other errors
}
finally
{//close streams etc..
}
You can store and read string information in a cookie.
If it is a session id coming from the server, the server can generate this cookie. And when another request is sent to the server the cookie will come too. Without having to do anything in the browser.
However if it is javascript that creates the session Id. You can create a cookie with javascript, with a function like:
The read function work from any page or tab of the same domain that has written it, either if the cookie was created from the page in javascript or from the server.
This is the best method i think so.
$base_url = ((isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] != "off") ? "https" : "http");
$base_url .= "://".$_SERVER['HTTP_HOST'];
$base_url .= str_replace(basename($_SERVER['SCRIPT_NAME']),"",$_SERVER['SCRIPT_NAME']);
echo $base_url;
start SQL Server Agent from the command prompt using:
SQLAGENT90 -C -V>C:\SQLAGENT.OUT
I wrote this lib to find once component boundary size change (resize) in Angular, may this help other people. You may put it on the root component, will do the same thing as window resize.
Step 1: Import the module
import { BoundSensorModule } from 'angular-bound-sensor';
@NgModule({
(...)
imports: [
BoundSensorModule,
],
})
export class AppModule { }
Step 2: Add the directive like below
<simple-component boundSensor></simple-component>
Step 3: Receive the boundary size details
import { HostListener } from '@angular/core';
@Component({
selector: 'simple-component'
(...)
})
class SimpleComponent {
@HostListener('resize', ['$event'])
onResize(event) {
console.log(event.detail);
}
}
This should work !!!
file_name
= Name of the file you want to split.
10000
= Number of rows each split file would contain
file_part_
= Prefix of split file name (file_part_0,file_part_1,file_part_2..etc goes on)
split -d -l 10000 file_name.csv file_part_
Make a truth table and use SUMPRODUCT to get the values. Copy this into cell B1 on Sheet2 and copy down as far as you need:=SUMPRODUCT(--($A1 = Sheet1!$A:$A), Sheet1!$B:$B)
the part that creates the truth table is:
--($A1 = Sheet1!$A:$A)
This returns an array of 0's and 1's. 1 when the values match and a 0 when they don't. Then the comma after that will basically do what I call "funny" matrix multiplication and will return the result. I may have misunderstood your question though, are there duplicate values in Column A of Sheet1?
By useing this code below :
.classname{
background-image: url(images/paper.jpg);
background-position: center;
background-size: cover;
background-repeat: no-repeat;
}
Hope it works. Thanks
If you include the additional methods file, here's the current file for 1.7: http://ajax.microsoft.com/ajax/jquery.validate/1.7/additional-methods.js
You can use the lettersonly
rule :) The additional methods are part of the zip you download, you can always find the latest here.
Here's an example:
$("form").validate({
rules: {
myField: { lettersonly: true }
}
});
It's worth noting, each additional method is independent, you can include that specific one, just place this before your .validate()
call:
jQuery.validator.addMethod("lettersonly", function(value, element) {
return this.optional(element) || /^[a-z]+$/i.test(value);
}, "Letters only please");
If some users of the code have different language settings format might not work. Thus I use the following code that gives the time stamp in format "yyymmdd hhMMss" regardless of language.
Function TimeStamp()
Dim iNow
Dim d(1 To 6)
Dim i As Integer
iNow = Now
d(1) = Year(iNow)
d(2) = Month(iNow)
d(3) = Day(iNow)
d(4) = Hour(iNow)
d(5) = Minute(iNow)
d(6) = Second(iNow)
For i = 1 To 6
If d(i) < 10 Then TimeStamp = TimeStamp & "0"
TimeStamp = TimeStamp & d(i)
If i = 3 Then TimeStamp = TimeStamp & " "
Next i
End Function
In some languages, you can use an alternative library, For example, tampax is an implementation of YAML handling variables:
const tampax = require('tampax');
const yamlString = `
dude:
name: Arthur
weapon:
favorite: Excalibur
useless: knife
sentence: "{{dude.name}} use {{weapon.favorite}}. The goal is {{goal}}."`;
const r = tampax.yamlParseString(yamlString, { goal: 'to kill Mordred' });
console.log(r.sentence);
// output : "Arthur use Excalibur. The goal is to kill Mordred."
Editor's Note: poster is also the author of this package.
This really needs to be added to the documentation, which is why I filed an issue about it a few months ago...
You need some 32-bit binaries, and you have a 64-bit OS version (apparently). Try:
sudo apt-get install lib32z1 lib32ncurses5 lib32bz2-1.0 lib32stdc++6
That worked for me on Ubuntu 14.10.
UPDATE 2017-12-16: The details will vary by Linux distro and version. So for example, this answer covers newer Ubuntu versions.
<?php
ob_start();
system('ipconfig/all');
$mycom=ob_get_contents();
ob_clean();
$findme = "Physical";
$pmac = strpos($mycom, $findme);
$mac=substr($mycom,($pmac+36),17);
echo $mac;
?>
This prints the mac address of client machine
Also If you are using mavenised project then try to update your project by clicking Alt+F5. Or right click on the application and go to maven /update project.
It builds all your components and resolves if any import error is there.
zvolkov's answer is the perfect one to find out if there is such a customer. If you need to use the customer afterwards, you can do:
Customer customer = list.FirstOrDefault(cus => cus.FirstName == "John");
if (customer != null)
{
// Use customer
}
I know this isn't what you were asking, but I thought I'd pre-empt a follow-on question :) (Of course, this only finds the first such customer... to find all of them, just use a normal where
clause.)
Wget currently only supports x-www-form-urlencoded data. --post-file
is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example
.
--post-data
and --post-file
work the same way: the only difference is that --post-data
allows you to specify the data in the command line, while --post-file
allows you to specify the path of the file that contain the data to send.
Here's the documentation:
--post-data=string
--post-file=file
Use POST as the method for all HTTP requests and send the specified data
in the request body. --post-data sends string as data, whereas
--post-file sends the contents of file. Other than that, they work in
exactly the same way. In particular, they both expect content of the
form "key1=value1&key2=value2", with percent-encoding for special
characters; the only difference is that one expects its content as a
command-line parameter and the other accepts its content from a file. In
particular, --post-file is not for transmitting files as form
attachments: those must appear as "key=value" data (with appropriate
percent-coding) just like everything else. Wget does not currently
support "multipart/form-data" for transmitting POST data; only
"application/x-www-form-urlencoded". Only one of --post-data and
--post-file should be specified.
Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.
Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN
.
wget --post-data 'user=foo&password=bar' http://example.com/auth.php
Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.
First create a temp table :
Step 1:
create table #tblOm_Temp (
Name varchar(100),
Age Int ,
RollNumber bigint
)
**Step 2: ** Insert Some value in Temp table .
insert into #tblom_temp values('Om Pandey',102,1347)
Step 3: Declare a table Variable to hold temp table data.
declare @tblOm_Variable table(
Name Varchar(100),
Age int,
RollNumber bigint
)
Step 4: select value from temp table and insert into table variable.
insert into @tblOm_Variable select * from #tblom_temp
Finally value is inserted from a temp table to Table variable
Step 5: Can Check inserted value in table variable.
select * from @tblOm_Variable
When you use #include <filename>, the pre-processor looking for the file in directory of C\C++ header files (stdio.h\cstdio, string, vector, etc.). But, when you use #include "filename": first, the pre-processor looking for the file in the current directory, and if it doesn't here - he looking for it in the directory of C\C++ header files.
Recursive Solution with driver main()
method.
public class AllPermutationsOfString {
public static void stringPermutations(String newstring, String remaining) {
if(remaining.length()==0)
System.out.println(newstring);
for(int i=0; i<remaining.length(); i++) {
String newRemaining = remaining.replaceFirst(remaining.charAt(i)+"", "");
stringPermutations(newstring+remaining.charAt(i), newRemaining);
}
}
public static void main(String[] args) {
String string = "abc";
AllPermutationsOfString.stringPermutations("", string);
}
}
By simply subtracting by char '0'(zero) a char (of digit '0' to '9') can be converted into int(0 to 9), e.g., '5'-'0' gives int 5.
String str = "123";
int a=str.charAt(1)-'0';
It's always enlightening to do a benchmark on the various suggested answers. Here's what I found out:
#!/usr/bin/ruby require 'benchmark' ary = [] 1000.times { ary << {:bar => rand(1000)} } n = 500 Benchmark.bm(20) do |x| x.report("sort") { n.times { ary.sort{ |a,b| b[:bar] <=> a[:bar] } } } x.report("sort reverse") { n.times { ary.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } } x.report("sort_by -a[:bar]") { n.times { ary.sort_by{ |a| -a[:bar] } } } x.report("sort_by a[:bar]*-1") { n.times { ary.sort_by{ |a| a[:bar]*-1 } } } x.report("sort_by.reverse!") { n.times { ary.sort_by{ |a| a[:bar] }.reverse } } end user system total real sort 3.960000 0.010000 3.970000 ( 3.990886) sort reverse 4.040000 0.000000 4.040000 ( 4.038849) sort_by -a[:bar] 0.690000 0.000000 0.690000 ( 0.692080) sort_by a[:bar]*-1 0.700000 0.000000 0.700000 ( 0.699735) sort_by.reverse! 0.650000 0.000000 0.650000 ( 0.654447)
I think it's interesting that @Pablo's sort_by{...}.reverse!
is fastest. Before running the test I thought it would be slower than "-a[:bar]
" but negating the value turns out to take longer than it does to reverse the entire array in one pass. It's not much of a difference, but every little speed-up helps.
Please note that these results are different in Ruby 1.9
Here are results for Ruby 1.9.3p194 (2012-04-20 revision 35410) [x86_64-darwin10.8.0]:
user system total real
sort 1.340000 0.010000 1.350000 ( 1.346331)
sort reverse 1.300000 0.000000 1.300000 ( 1.310446)
sort_by -a[:bar] 0.430000 0.000000 0.430000 ( 0.429606)
sort_by a[:bar]*-1 0.420000 0.000000 0.420000 ( 0.414383)
sort_by.reverse! 0.400000 0.000000 0.400000 ( 0.401275)
These are on an old MacBook Pro. Newer, or faster machines, will have lower values, but the relative differences will remain.
Here's a bit updated version on newer hardware and the 2.1.1 version of Ruby:
#!/usr/bin/ruby
require 'benchmark'
puts "Running Ruby #{RUBY_VERSION}"
ary = []
1000.times {
ary << {:bar => rand(1000)}
}
n = 500
puts "n=#{n}"
Benchmark.bm(20) do |x|
x.report("sort") { n.times { ary.dup.sort{ |a,b| b[:bar] <=> a[:bar] } } }
x.report("sort reverse") { n.times { ary.dup.sort{ |a,b| a[:bar] <=> b[:bar] }.reverse } }
x.report("sort_by -a[:bar]") { n.times { ary.dup.sort_by{ |a| -a[:bar] } } }
x.report("sort_by a[:bar]*-1") { n.times { ary.dup.sort_by{ |a| a[:bar]*-1 } } }
x.report("sort_by.reverse") { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse } }
x.report("sort_by.reverse!") { n.times { ary.dup.sort_by{ |a| a[:bar] }.reverse! } }
end
# >> Running Ruby 2.1.1
# >> n=500
# >> user system total real
# >> sort 0.670000 0.000000 0.670000 ( 0.667754)
# >> sort reverse 0.650000 0.000000 0.650000 ( 0.655582)
# >> sort_by -a[:bar] 0.260000 0.010000 0.270000 ( 0.255919)
# >> sort_by a[:bar]*-1 0.250000 0.000000 0.250000 ( 0.258924)
# >> sort_by.reverse 0.250000 0.000000 0.250000 ( 0.245179)
# >> sort_by.reverse! 0.240000 0.000000 0.240000 ( 0.242340)
New results running the above code using Ruby 2.2.1 on a more recent Macbook Pro. Again, the exact numbers aren't important, it's their relationships:
Running Ruby 2.2.1
n=500
user system total real
sort 0.650000 0.000000 0.650000 ( 0.653191)
sort reverse 0.650000 0.000000 0.650000 ( 0.648761)
sort_by -a[:bar] 0.240000 0.010000 0.250000 ( 0.245193)
sort_by a[:bar]*-1 0.240000 0.000000 0.240000 ( 0.240541)
sort_by.reverse 0.230000 0.000000 0.230000 ( 0.228571)
sort_by.reverse! 0.230000 0.000000 0.230000 ( 0.230040)
Updated for Ruby 2.7.1 on a Mid-2015 MacBook Pro:
Running Ruby 2.7.1
n=500
user system total real
sort 0.494707 0.003662 0.498369 ( 0.501064)
sort reverse 0.480181 0.005186 0.485367 ( 0.487972)
sort_by -a[:bar] 0.121521 0.003781 0.125302 ( 0.126557)
sort_by a[:bar]*-1 0.115097 0.003931 0.119028 ( 0.122991)
sort_by.reverse 0.110459 0.003414 0.113873 ( 0.114443)
sort_by.reverse! 0.108997 0.001631 0.110628 ( 0.111532)
...the reverse method doesn't actually return a reversed array - it returns an enumerator that just starts at the end and works backwards.
The source for Array#reverse
is:
static VALUE
rb_ary_reverse_m(VALUE ary)
{
long len = RARRAY_LEN(ary);
VALUE dup = rb_ary_new2(len);
if (len > 0) {
const VALUE *p1 = RARRAY_CONST_PTR_TRANSIENT(ary);
VALUE *p2 = (VALUE *)RARRAY_CONST_PTR_TRANSIENT(dup) + len - 1;
do *p2-- = *p1++; while (--len > 0);
}
ARY_SET_LEN(dup, RARRAY_LEN(ary));
return dup;
}
do *p2-- = *p1++; while (--len > 0);
is copying the pointers to the elements in reverse order if I remember my C correctly, so the array is reversed.
You can apply custom date time format using ToString
like:
DateTime.Now.Date.ToString("MM/dd/yyyy");
Further reading on DateTime.ToString
formats pattern can be found here and here.
Edit: After your question edit, Just like what other suggested you should apply the date format at your view:
model.Returndate = DateTime.Now.Date;
@Html.EditorFor(model => model.Returndate.Date.ToString("MM/dd/yyyy"))
I use Checkstlye plugin for such a purpose. In Checkstyle configuration, I add special regexp rules to detect lines with TABs and then mark such lines as checkstyle ERROR, which is clearly visible in Eclipse editor. Works fine.
You will have to use some sort of network sniffer if you want to get at this sort of data and you're likely to run into the same problem (pulling out the relevant data from the overall network traffic) with those that you do now with Wireshark.
You will also get the same error ERROR 1114 (HY000): The table '#sql-310a_8867d7f' is full
if you try to add an index to a table that is using the storage engine MEMORY.
you must add 1 day to the end date, using: DATE_ADD('$end_date', INTERVAL 1 DAY)
Just posting in case it help someone else. The cause of this error for me was a missing do
after creating a form with form_with
. Hope that may help someone else
Try this or purpose will solve with lesser no of steps
for (int i = 0; i < a.length; i++)
{
for (int k = i+1; k < a.length; k++)
{
if (a[i] != a[k])
{
System.out.println(a[i]+"not the same with"+a[k]+"\n");
}
}
}
Here is my solution, i have been reading a lot of post and they was really helpfull, finaly i build a code for small files, with cUrl and Php, that i think its really usefull.
public function postFile()
{
$file_url = "test.txt"; //here is the file route, in this case is on same directory but you can set URL too like "http://examplewebsite.com/test.txt"
$eol = "\r\n"; //default line-break for mime type
$BOUNDARY = md5(time()); //random boundaryid, is a separator for each param on my post curl function
$BODY=""; //init my curl body
$BODY.= '--'.$BOUNDARY. $eol; //start param header
$BODY .= 'Content-Disposition: form-data; name="sometext"' . $eol . $eol; // last Content with 2 $eol, in this case is only 1 content.
$BODY .= "Some Data" . $eol;//param data in this case is a simple post data and 1 $eol for the end of the data
$BODY.= '--'.$BOUNDARY. $eol; // start 2nd param,
$BODY.= 'Content-Disposition: form-data; name="somefile"; filename="test.txt"'. $eol ; //first Content data for post file, remember you only put 1 when you are going to add more Contents, and 2 on the last, to close the Content Instance
$BODY.= 'Content-Type: application/octet-stream' . $eol; //Same before row
$BODY.= 'Content-Transfer-Encoding: base64' . $eol . $eol; // we put the last Content and 2 $eol,
$BODY.= chunk_split(base64_encode(file_get_contents($file_url))) . $eol; // we write the Base64 File Content and the $eol to finish the data,
$BODY.= '--'.$BOUNDARY .'--' . $eol. $eol; // we close the param and the post width "--" and 2 $eol at the end of our boundary header.
$ch = curl_init(); //init curl
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'X_PARAM_TOKEN : 71e2cb8b-42b7-4bf0-b2e8-53fbd2f578f9' //custom header for my api validation you can get it from $_SERVER["HTTP_X_PARAM_TOKEN"] variable
,"Content-Type: multipart/form-data; boundary=".$BOUNDARY) //setting our mime type for make it work on $_FILE variable
);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/1.0 (Windows NT 6.1; WOW64; rv:28.0) Gecko/20100101 Firefox/28.0'); //setting our user agent
curl_setopt($ch, CURLOPT_URL, "api.endpoint.post"); //setting our api post url
curl_setopt($ch, CURLOPT_COOKIEJAR, $BOUNDARY.'.txt'); //saving cookies just in case we want
curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1); // call return content
curl_setopt ($ch, CURLOPT_FOLLOWLOCATION, 1); navigate the endpoint
curl_setopt($ch, CURLOPT_POST, true); //set as post
curl_setopt($ch, CURLOPT_POSTFIELDS, $BODY); // set our $BODY
$response = curl_exec($ch); // start curl navigation
print_r($response); //print response
}
With this we shoud be get on the "api.endpoint.post" the following vars posted You can easly test with this script, and you should be recive this debugs on the function postFile() at the last row
print_r($response); //print response
public function getPostFile()
{
echo "\n\n_SERVER\n";
echo "<pre>";
print_r($_SERVER['HTTP_X_PARAM_TOKEN']);
echo "/<pre>";
echo "_POST\n";
echo "<pre>";
print_r($_POST['sometext']);
echo "/<pre>";
echo "_FILES\n";
echo "<pre>";
print_r($_FILEST['somefile']);
echo "/<pre>";
}
Here you are it should be work good, could be better solutions but this works and is really helpfull to understand how the Boundary and multipart/from-data mime works on php and curl library,
My Best Reggards,
my apologies about my english but isnt my native language.
In your code:
while(fscanf(fp,"%s %c",item,&status) == 1)
why 1 and not 2? The scanf functions return the number of objects read.
If you're trying to get C's behavior (0 == false
and everything else is true
), you could do this:
boolean uses_votes = Integer.parseInt(o.get("uses_votes")) != 0;
here's how I promote all worksheet names to global names. YMMV
For Each wsh In ActiveWorkbook.Worksheets
For Each n In wsh.Names
' Get unqualified range name
Dim s As String
s = Split(n.Name, "!")(UBound(Split(n.Name, "!")))
' Add to "Workbook" scope
n.RefersToRange.Name = s
' Remove from "Worksheet" scope
Call n.Delete
Next n
Next wsh
This cannot be done with pure HTML/JS, you will need CSS
CSS:
button {
width: 100%;
height: 100%;
}
Substitute 100% with required size
This can be done in many ways
Use DBNull.Value
Better still, make your stored procedure parameters have defaults of NULL. Or use a Nullable<DateTime>
parameter if the parameter will sometimes be a valid DateTime object
It is nothing you can do in the client side.
I added @CrossOrigin
in the controller in the server side and it works.
@RestController
@CrossOrigin(origins = "*")
public class MyController
Please refer to docs.
Lin
"before" by default implies before(:each)
. Ref The Rspec Book, copyright 2010, page 228.
before(scope = :each, options={}, &block)
I use before(:each)
to seed some data for each example group without having to call the let
method to create the data in the "it" block. Less code in the "it" block in this case.
I use let
if I want some data in some examples but not others.
Both before and let are great for DRYing up the "it" blocks.
To avoid any confusion, "let" is not the same as before(:all)
. "Let" re-evaluates its method and value for each example ("it"), but caches the value across multiple calls in the same example. You can read more about it here: https://www.relishapp.com/rspec/rspec-core/v/2-6/docs/helper-methods/let-and-let
What the OP wants to do, is delete additional properties in his Google analytics. Properties that are not his but belong to someone else.
Apparently, the only way to do this, is to contact the owner of that website who is the administrator, and asked them to remove you.
Or you can just create a new Google account, and add your properties to the new account.
None of these are real good solutions. Thank you Google for caring so much about SEO people.
To add insult to injury, if you go over 25 accounts, you must contact Google to get permission to add another.
Lesson learned: Do not add other peoples websites to your Google analytics account. Create a separate account so that if you have to start over, you don't lose any data from your websites. It's also good to have more than one Google analytics account.
Having tried the solution suggested by Zelazny on a relatively large DataFrame (~400k rows) I found it to be very slow. Here is an alternative that I found to run orders of magnitude faster on my data set.
df = pd.DataFrame({
'sp' : ['MM1', 'MM1', 'MM1', 'MM2', 'MM2', 'MM2', 'MM4', 'MM4', 'MM4'],
'mt' : ['S1', 'S1', 'S3', 'S3', 'S4', 'S4', 'S2', 'S2', 'S2'],
'val' : ['a', 'n', 'cb', 'mk', 'bg', 'dgb', 'rd', 'cb', 'uyi'],
'count' : [3,2,5,8,10,1,2,2,7]
})
df_grouped = df.groupby(['sp', 'mt']).agg({'count':'max'})
df_grouped = df_grouped.reset_index()
df_grouped = df_grouped.rename(columns={'count':'count_max'})
df = pd.merge(df, df_grouped, how='left', on=['sp', 'mt'])
df = df[df['count'] == df['count_max']]
Technically, and from Comintern's accepted workaround,
I believe you actually want to Delete all the Cells in the Sheet. Which removes Formatting (See footnote for exceptions), etc. as well as the Cells Contents.
I.e. Sheets("Zeroes").Cells.Delete
Combined also with UsedRange, ScreenUpdating and Calculation skipping it should be nearly intantaneous:
Sub DeleteCells ()
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = xlAutomatic
End Sub
Or if you prefer to respect the Calculation State Excel is currently in:
Sub DeleteCells ()
Dim SaveCalcState
SaveCalcState = Application.Calculation
Application.Calculation = XlManual
Application.ScreenUpdating = False
Sheets("Zeroes").UsedRange.Delete
Application.ScreenUpdating = True
Application.Calculation = SaveCalcState
End Sub
Footnote: If formatting was applied for an Entire Column, then it is not deleted. This includes Font Colour, Fill Colour and Borders, the Format Category (like General, Date, Text, Etc.) and perhaps other properties too, but
Conditional formatting IS deleted, as is Entire Row formatting.
(Entire Column formatting is quite useful if you are importing raw data repeatedly to a sheet as it will conform to the Formats originally applied if a simple Paste-Values-Only type import is done.)
Try this:
myscript """test"""
"" escape to a single " in the parameter.
Checkout points the head at a specific commit.
Reset points a branch at a specific commit. (A branch is a pointer to a commit.)
Incidentally, if your head doesn’t point to a commit that’s also pointed to by a branch then you have a detached head. (turned out to be wrong. See comments...)
It is quite old question but I encountered the same issue.
If you run your web on chrome, you could read through this post Background Tabs in Chrome 57
.
Basically the interval timer could run if it haven't run out of the timer budget.
The consumption of budget is based on CPU time usage of the task inside timer.
Based on my scenario, I draw video to canvas and transport to WebRTC.
The webrtc video connection would keep updating even the tab is inactive.
However you have to use setInterval
instead of requestAnimationFrame
.
it is not recommended for UI rendering though.
It would be better to listen visibilityChange
event and change render mechenism accordingly.
Besides, you could try @kaan-soral and it should works based on the documentation.
Add the git
path to the Environment-path variable (e.g. C:\Program Files\Git\cmd
) by which you can access git
from any folder using command line.
You have to add attribute newline="\n" to open function like this:
with open('file.csv','w',newline="\n") as out:
csv_out = csv.writer(out, delimiter =';')
With the following function you are just sending the pure ICMP packets using socket_create. I got the following code from a user note there. N.B. You must run the following as root.
Although you can't put this in a standard web page you can run it as a cron job and populate a database with the results.
So it's best suited if you need to monitor a site.
function twitterIsUp() {
return ping('twitter.com');
}
function ping ($host, $timeout = 1) {
/* ICMP ping packet with a pre-calculated checksum */
$package = "\x08\x00\x7d\x4b\x00\x00\x00\x00PingHost";
$socket = socket_create(AF_INET, SOCK_RAW, 1);
socket_set_option($socket, SOL_SOCKET, SO_RCVTIMEO, array('sec' => $timeout, 'usec' => 0));
socket_connect($socket, $host, null);
$ts = microtime(true);
socket_send($socket, $package, strLen($package), 0);
if (socket_read($socket, 255)) {
$result = microtime(true) - $ts;
} else {
$result = false;
}
socket_close($socket);
return $result;
}
I know this has been answered with previous entries, but for anyone else that comes to this question, I did find a way that did not require having use the "ping" process in windows and then scrubbing the output.
What I did was use JNA to invoke Window's IP helper library to do an ICMP echo
I believe the answer is very simple and it has to do with semantic rules of references and how arrays are handled in C++.
In short: References can be thought of as structs which don't have a default constructor, so all the same rules apply.
1) Semantically, references don't have a default value. References can only be created by referencing something. References don't have a value to represent the absence of a reference.
2) When allocating an array of size X, program creates a collection of default-initialized objects. Since reference doesn't have a default value, creating such an array is semantically illegal.
This rule also applies to structs/classes which don't have a default constructor. The following code sample doesn't compile:
struct Object
{
Object(int value) { }
};
Object objects[1]; // Error: no appropriate default constructor available
If you just need to make a simple call to a REST service from java you use something along these line
/*
* Stolen from http://xml.nig.ac.jp/tutorial/rest/index.html
* and http://www.dr-chuck.com/csev-blog/2007/09/calling-rest-web-services-from-java/
*/
import java.io.*;
import java.net.*;
public class Rest {
public static void main(String[] args) throws IOException {
URL url = new URL(INSERT_HERE_YOUR_URL);
String query = INSERT_HERE_YOUR_URL_PARAMETERS;
//make connection
URLConnection urlc = url.openConnection();
//use post mode
urlc.setDoOutput(true);
urlc.setAllowUserInteraction(false);
//send query
PrintStream ps = new PrintStream(urlc.getOutputStream());
ps.print(query);
ps.close();
//get result
BufferedReader br = new BufferedReader(new InputStreamReader(urlc
.getInputStream()));
String l = null;
while ((l=br.readLine())!=null) {
System.out.println(l);
}
br.close();
}
}
Try to send an e-mail through that SMTP server manually/from an interactive mailer (e.g. Mozilla Thunderbird). From the errors, it seems the server won't accept your credentials. Is that SMTP running on the port, or is it SSL+SMTP? You don't seem to be using secure connection in the code you've posted, and I'm not sure if PHPMailer actually supports SSL+SMTP.
(First result of googling your SMTP server's hostname: http://podpora.ebola.cz/idx.php/0/006/article/Strucny-technicky-popis-nastaveni-sluzeb.html seems to say "SMTPs mail sending: secure SSL connection,port: 465" . )
It looks like PHPMailer does support SSL; at least from this. So, you'll need to change this:
define('SMTP_SERVER', 'smtp.ebola.cz');
into this:
define('SMTP_SERVER', 'ssl://smtp.ebola.cz');
One approach that's both general and yields fairly-readable code is to use the filter()
function and the across()
helper functions from the {dplyr} package.
library(dplyr)
vars_to_check <- c("rnor", "cfam")
# Filter a specific list of columns to keep only non-missing entries
df %>%
filter(across(one_of(vars_to_check),
~ !is.na(.x)))
# Filter all the columns to exclude NA
df %>%
filter(across(everything(),
~ !is.na(.)))
# Filter only numeric columns
df %>%
filter(across(where(is.numeric),
~ !is.na(.)))
Similarly, there are also the variant functions in the dplyr package (filter_all
, filter_at
, filter_if
) which accomplish the same thing:
library(dplyr)
vars_to_check <- c("rnor", "cfam")
# Filter a specific list of columns to keep only non-missing entries
df %>%
filter_at(.vars = vars(one_of(vars_to_check)),
~ !is.na(.))
# Filter all the columns to exclude NA
df %>%
filter_all(~ !is.na(.))
# Filter only numeric columns
df %>%
filter_if(is.numeric,
~ !is.na(.))
jQuery:
$('#container').append('<img src="/path/to/image.jpg"
width="16" height="16" alt="Test Image" title="Test Image" />');
I've found that this works even better because you don't have to worry about HTML escaping anything (which should be done in the above code, if the values weren't hard coded). It's also easier to read (from a JS perspective):
$('#container').append($('<img>', {
src : "/path/to/image.jpg",
width : 16,
height : 16,
alt : "Test Image",
title : "Test Image"
}));
Here is my solution to smooth scroll to div / anchor using jQuery in case you have a fixed header so that it doesn't scroll underneath it. Also it works if you link it from other page.
Just replace ".site-header" to div that contains your header.
$(function() {
$('a[href*="#"]:not([href="#"])').click(function() {
var headerheight = $(".site-header").outerHeight();
if (location.pathname.replace(/^\//,'') == this.pathname.replace(/^\//,'') && location.hostname == this.hostname) {
var target = $(this.hash);
target = target.length ? target : $('[name=' + this.hash.slice(1) +']');
if (target.length) {
$('html, body').animate({
scrollTop: (target.offset().top - headerheight)
}, 1000);
return false;
}
}
});
//Executed on page load with URL containing an anchor tag.
if($(location.href.split("#")[1])) {
var headerheight = $(".site-header").outerHeight();
var target = $('#'+location.href.split("#")[1]);
if (target.length) {
$('html,body').animate({
scrollTop: target.offset().top - headerheight
}, 1);
return false;
}
}
});
To replace anything that starts with "text" until the last character:
text.+(.*)$
Example
text hsjh sdjh sd jhsjhsdjhsdj hsd ^ last character
text.+(\ 123)
Example
text fuhfh283nfnd03no3 d90d3nd 3d 123 udauhdah au dauh ej2e ^ ^ From here To here
One more option is require-dir-all combining features from most popular packages.
Most popular require-dir
does not have options to filter the files/dirs and does not have map
function (see below), but uses small trick to find module's current path.
Second by popularity require-all
has regexp filtering and preprocessing, but lacks relative path, so you need to use __dirname
(this has pros and contras) like:
var libs = require('require-all')(__dirname + '/lib');
Mentioned here require-index
is quite minimalistic.
With map
you may do some preprocessing, like create objects and pass config values (assuming modules below exports constructors):
// Store config for each module in config object properties
// with property names corresponding to module names
var config = {
module1: { value: 'config1' },
module2: { value: 'config2' }
};
// Require all files in modules subdirectory
var modules = require('require-dir-all')(
'modules', // Directory to require
{ // Options
// function to be post-processed over exported object for each require'd module
map: function(reqModule) {
// create new object with corresponding config passed to constructor
reqModule.exports = new reqModule.exports( config[reqModule.name] );
}
}
);
// Now `modules` object holds not exported constructors,
// but objects constructed using values provided in `config`.
The easiest way to do it is to link the CSV-file into the Access database as a table. Then you can work on this table as if it was an ordinary access table, for instance by creating an appropriate query based on this table that returns exactly what you want.
You can link the table either manually or with VBA like this
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
Dim db As DAO.Database
' Re-link the CSV Table
Set db = CurrentDb
On Error Resume Next: db.TableDefs.Delete "tblImport": On Error GoTo 0
db.TableDefs.Refresh
DoCmd.TransferText TransferType:=acLinkDelim, TableName:="tblImport", _
FileName:="C:\MyData.csv", HasFieldNames:=true
db.TableDefs.Refresh
' Perform the import
db.Execute "INSERT INTO someTable SELECT col1, col2, ... FROM tblImport " _
& "WHERE NOT F1 IN ('A1', 'A2', 'A3')"
db.Close: Set db = Nothing
Use -to instead of -t: -to specifies the end time, -t specifies the duration
Note: Though my original answer attracted several upvotes, I decided that I could do much better. You can find my original (simplistic and misguided) answer in the edit history.
If Microsoft had the intent of providing a means of outputting a blank line from cmd.exe
, Microsoft surely would have documented such a simple operation. It is this omission that motivated me to ask this question.
So, because a means for outputting a blank line from cmd.exe
is not documented, arguably one should consider any suggestion for how to accomplish this to be a hack. That means that there is no known method for outputting a blank line from cmd.exe
that is guaranteed to work (or work efficiently) in all situations.
With that in mind, here is a discussion of methods that have been recommended for outputting a blank line from cmd.exe
. All recommendations are based on variations of the echo
command.
echo.
While this will work in many if not most situations, it should be avoided because it is slower than its alternatives and actually can fail (see here, here, and here). Specifically, cmd.exe
first searches for a file named echo
and tries to start it. If a file named echo
happens to exist in the current working directory, echo.
will fail with:
'echo.' is not recognized as an internal or external command,
operable program or batch file.
echo:
echo\
At the end of this answer, the author argues that these commands can be slow, for instance if they are executed from a network drive location. A specific reason for the potential slowness is not given. But one can infer that it may have something to do with accessing the file system. (Perhaps because :
and \
have special meaning in a Windows file system path?)
However, some may consider these to be safe options since :
and \
cannot appear in a file name. For that or another reason, echo:
is recommended by SS64.com here.
echo(
echo+
echo,
echo/
echo;
echo=
echo[
echo]
This lengthy discussion includes what I believe to be all of these. Several of these options are recommended in this SO answer as well. Within the cited discussion, this post ends with what appears to be a recommendation for echo(
and echo:
.
My question at the top of this page does not specify a version of Windows. My experimentation on Windows 10 indicates that all of these produce a blank line, regardless of whether files named echo
, echo+
, echo,
, ..., echo]
exist in the current working directory. (Note that my question predates the release of Windows 10. So I concede the possibility that older versions of Windows may behave differently.)
In this answer, @jeb asserts that echo(
always works. To me, @jeb's answer implies that other options are less reliable but does not provide any detail as to why that might be. Note that @jeb contributed much valuable content to other references I have cited in this answer.
Conclusion: Do not use echo.
. Of the many other options I encountered in the sources I have cited, the support for these two appears most authoritative:
echo(
echo:
But I have not found any strong evidence that the use of either of these will always be trouble-free.
Example Usage:
@echo off
echo Here is the first line.
echo(
echo There is a blank line above this line.
Expected output:
Here is the first line.
There is a blank line above this line.
I know this thread is too old but recently I was wondering how to delete eclipse
app on my MacBook Pro
running macOS High Sierra
.
Bellow are the steps which I followed to delete it from my system. Added screenshots for more clear understanding.
Open the eclipse app and it will show an app icon in dock. If it is not already present in dock then please try to run the app from Spotlight Search
by pressing ?
+ space
.
Now right click on that eclipse logo from dock and click Show in Finder
under Options
.
eclipse
app in an external finder window.eclipse
) by pressing ?
+ delete
.Trash
as well if you are removing it from system completely.Thanks. Hope this helped.
nothing much to add,
1 - if you want to execute a query in a loop (more than 1 time), prepared statement can be faster, because of optimization that you mentioned.
2 - parameterized query is a good way to avoid SQL Injection. Parameterized querys are only available in PreparedStatement.
As @thomas-lotze has mentioned, currently pip tooling does not do that as there is no corresponding --user option. But what I find is that I can check in ~/.local/bin and look for the specific pip#.# which looks to me like it corresponds to the --user option.
In my case:
antho@noctil: ~/.l/bin$ pwd
/home/antho/.local/bin
antho@noctil: ~/.l/bin$ ls pip*
pip pip2 pip2.7 pip3 pip3.5
And then just uninstall with the specific pip version.
We bought a Rebex File Transfer Pack, and all is fine. The API is easy, we haven't any problem with comunications, proxy servers etc...
But I havent chance to compare it with another SFTP/FTPS component.
An elegant method would be to use the ~=
compatible release operator according to PEP 440. In your case this would amount to:
package~=0.5.0
As an example, if the following versions exist, it would choose 0.5.9
:
0.5.0
0.5.9
0.6.0
For clarification, each pair is equivalent:
~= 0.5.0
>= 0.5.0, == 0.5.*
~= 0.5
>= 0.5, == 0.*
// Two-dimensional GetLength example.
int[,] two = new int[5, 10];
Console.WriteLine(two.GetLength(0)); // Writes 5
Console.WriteLine(two.GetLength(1)); // Writes 10
Yes you can change it. but in api 22 and above, using NotificationCompat.Builder and setColorized(true) :
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context, context.getPackageName())
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon, level)
.setLargeIcon(largeIcon)
.setContentIntent(intent)
.setColorized(true)
.setDefaults(0)
.setCategory(Notification.CATEGORY_SERVICE)
.setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
.setPriority(NotificationCompat.PRIORITY_HIGH);
First, elements inside a collection print their repr. you should learn about __repr__
and __str__
.
This is the difference between print repr(1.1) and print 1.1. Let's join all those strings instead of the representations:
numbers = [9.0, 0.053, 0.0325754, 0.0108928, 0.0557025, 0.07933]
print "repr:", " ".join(repr(n) for n in numbers)
print "str:", " ".join(str(n) for n in numbers)
Here is the script that I use. With it, I avoid unnecessarily dropping and recreating the stored procs.
IF NOT EXISTS (
SELECT *
FROM sys.objects
WHERE object_id = OBJECT_ID(N'[dbo].[uspMyProcedure]')
)
BEGIN
EXEC sp_executesql N'CREATE PROCEDURE [dbo].[uspMyProcedure] AS select 1'
END
GO
ALTER PROCEDURE [dbo].[uspMyProcedure]
@variable1 INTEGER
AS
BEGIN
-- Stored procedure logic
END
A programmatic solution:
SELECT pg_encoding_to_char(encoding) FROM pg_database WHERE datname = 'yourdb';
The following should suffice:
[^ ]
If you want to expand that to anything but white-space (line breaks, tabs, spaces, hard spaces):
[^\s]
or
\S # Note this is a CAPITAL 'S'!
I rely on NDEBUG
, because it's the only one whose behavior is standardized across compilers and implementations (see documentation for the standard assert macro). The negative logic is a small readability speedbump, but it's a common idiom you can quickly adapt to.
To rely on something like _DEBUG
would be to rely on an implementation detail of a particular compiler and library implementation. Other compilers may or may not choose the same convention.
The third option is to define your own macro for your project, which is quite reasonable. Having your own macro gives you portability across implementations and it allows you to enable or disable your debugging code independently of the assertions. Though, in general, I advise against having different classes of debugging information that are enabled at compile time, as it causes an increase in the number of configurations you have to build (and test) for arguably small benefit.
With any of these options, if you use third party code as part of your project, you'll have to be aware of which convention it uses.
See attribute value in console on click event
//...
alertMessage (cEvent){
console.log(cEvent.target.getAttribute('customEvent')); /*display attribute value */
}
//...
simple add customAttribute as your wish in render method
render(){
return <div>
//..
<button customAttribute="My Custom Event Message" onClick={this.alertMessage.bind(this) } >Click Me</button>
</div>
}
//...
Oracle 11g provides a PIVOT
operation that does what you want.
Oracle 11g solution
select * from
(select id, k, v from _kv)
pivot(max(v) for k in ('name', 'age', 'gender', 'status')
(Note: I do not have a copy of 11g to test this on so I have not verified its functionality)
I obtained this solution from: http://orafaq.com/wiki/PIVOT
EDIT -- pivot xml option (also Oracle 11g)
Apparently there is also a pivot xml
option for when you do not know all the possible column headings that you may need. (see the XML TYPE section near the bottom of the page located at http://www.oracle.com/technetwork/articles/sql/11g-pivot-097235.html)
select * from
(select id, k, v from _kv)
pivot xml (max(v)
for k in (any) )
(Note: As before I do not have a copy of 11g to test this on so I have not verified its functionality)
Edit2: Changed v
in the pivot
and pivot xml
statements to max(v)
since it is supposed to be aggregated as mentioned in one of the comments. I also added the in
clause which is not optional for pivot
. Of course, having to specify the values in the in
clause defeats the goal of having a completely dynamic pivot/crosstab query as was the desire of this question's poster.
Here is a simpler solution to list all files in a directory and to download it.
In your index.php file
<?php
$dir = "./";
$allFiles = scandir($dir);
$files = array_diff($allFiles, array('.', '..')); // To remove . and ..
foreach($files as $file){
echo "<a href='download.php?file=".$file."'>".$file."</a><br>";
}
The scandir() function list all files and directories inside the specified path. It works with both PHP 5 and PHP 7.
Now in the download.php
<?php
$filename = basename($_GET['file']);
// Specify file path.
$path = ''; // '/uplods/'
$download_file = $path.$filename;
if(!empty($filename)){
// Check file is exists on given path.
if(file_exists($download_file))
{
header('Content-Disposition: attachment; filename=' . $filename);
readfile($download_file);
exit;
}
else
{
echo 'File does not exists on given path';
}
}
In sass (scss):
button {
color: white;
cursor: pointer;
border-radius: 4px;
&:disabled{
opacity: 0.4;
&:hover{
opacity: 0.4; //this is what you want
}
}
&:hover{
opacity: 0.9;
}
}
One you convert your image to gray-scale you cannot got back. You have gone from three channel to one, when you try to go back all three numbers will be the same. So the short answer is no you cannot go back. The reason your backtorgb function this throwing that error is because it needs to be in the format:
CvtColor(input, output, CV_GRAY2BGR)
OpenCV use BGR not RGB, so if you fix the ordering it should work, though your image will still be gray.
In Server 2008 the startup folder for individual users is here:
C:\Users\username\AppData\Roaming\Microsoft\Windows\Start Menu\Programs\Startup
For All Users it's here:
C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Startup
Hope that helps
But why would you use excel when you could do it all online and have your boss check your dynamic link.
We are using this new tool since last week. http://www.burndown-charts.com/
What I do is I send my boss the link to my chart and he plays around with the links to see if we will be on time...
http://www.burndown-charts.com/teams/dreamteam/sprints/prototype-x
Override method authenticationManagerBean
in WebSecurityConfigurerAdapter
to expose the AuthenticationManager built using configure(AuthenticationManagerBuilder)
as a Spring bean:
For example:
@Bean(name = BeanIds.AUTHENTICATION_MANAGER)
@Override
public AuthenticationManager authenticationManagerBean() throws Exception {
return super.authenticationManagerBean();
}
If you want to pass data between two actions during a redirect without include any data in the query string, put the model in the TempData object.
ACTION
TempData["datacontainer"] = modelData;
VIEW
var modelData= TempData["datacontainer"] as ModelDataType;
TempData is meant to be a very short-lived instance, and you should only use it during the current and the subsequent requests only! Since TempData works this way, you need to know for sure what the next request will be, and redirecting to another view is the only time you can guarantee this.
Therefore, the only scenario where using TempData will reliably work is when you are redirecting.
This error would happen when the number of guesses (so_far) is less than the length of the word. Did you miss an initialization for the variable so_far somewhere, that sets it to something like
so_far = " " * len(word)
?
Edit:
try something like
print "%d / %d" % (new, so_far)
before the line that throws the error, so you can see exactly what goes wrong. The only thing I can think of is that so_far is in a different scope, and you're not actually using the instance you think.
Something in the lines of
myString.split("\\s+");
This groups all white spaces as a delimiter.
So if I have the string:
"Hello[space character][tab character]World"
This should yield the strings "Hello"
and "World"
and omit the empty space between the [space]
and the [tab]
.
As VonC pointed out, the backslash should be escaped, because Java would first try to escape the string to a special character, and send that to be parsed. What you want, is the literal "\s"
, which means, you need to pass "\\s"
. It can get a bit confusing.
The \\s
is equivalent to [ \\t\\n\\x0B\\f\\r]
.
These steps work for me:
Good to go!!!
library(Rcpp)
library(ggplot2)
Update April 2013: Don't do this. It wasn't a good idea in 2009 when I first answered the question and it really isn't a good idea now. See this answer by hackbod for reasons:
Avoid reloading activity with asynctask on orientation change in android
Add android:configChanges="keyboardHidden|orientation"
to your AndroidManifest.xml. This tells the system what configuration changes you are going to handle yourself - in this case by doing nothing.
<activity android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation">
See Developer reference configChanges for more details.
However, your application can be interrupted at any time, e.g. by a phone call, so you really should add code to save the state of your application when it is paused.
Update: As of Android 3.2, you also need to add "screenSize":
<activity
android:name="MainActivity"
android:screenOrientation="portrait"
android:configChanges="keyboardHidden|orientation|screenSize">
From Developer guide Handling the Configuration Change Yourself
Caution: Beginning with Android 3.2 (API level 13), the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher (as declared by the minSdkVersion and targetSdkVersion attributes), you must include the "screenSize" value in addition to the "orientation" value. That is, you must declare
android:configChanges="orientation|screenSize"
. However, if your application targets API level 12 or lower, then your activity always handles this configuration change itself (this configuration change does not restart your activity, even when running on an Android 3.2 or higher device).
You can do it like this:
alert(parseFloat("1.1531531414")); // alerts the float
parseFloat = function(input) { return 1; };
alert(parseFloat("1.1531531414")); // alerts '1'
Check out a working example here: http://jsfiddle.net/LtjzW/1/
If you develop in Visual Studio 2013 and 2015 versions, you can use their GPU Usage tool:
Moreover, it seems you can diagnose any application with it, not only Visual Studio Projects:
In addition to Visual Studio projects you can also collect GPU usage data on any loose .exe applications that you have sitting around. Just open the executable as a solution in Visual Studio and then start up a diagnostics session and you can target it with GPU usage. This way if you are using some type of engine or alternative development environment you can still collect data on it as long as you end up with an executable.
Source: http://blogs.msdn.com/b/ianhu/archive/2014/12/16/gpu-usage-for-directx-in-visual-studio.aspx
I solved this issue by doing this:
instead of
<Route path="/" component={HomePage} />
do this
<Route
path="/" component={props => <HomePage {...props} />} />
I quote Andrew Dunstan on the pgsql-hackers list:
At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.
Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.
Offers an arsenal of new functions and operators to add "json-processing".
The answer to the original question in Postgres 9.3:
SELECT *
FROM json_array_elements(
'[{"name": "Toby", "occupation": "Software Engineer"},
{"name": "Zaphod", "occupation": "Galactic President"} ]'
) AS elem
WHERE elem->>'name' = 'Toby';
Advanced example:
For bigger tables you may want to add an expression index to increase performance:
Adds jsonb
(b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb
also supports GIN, btree and hash indexes, GIN being the most potent of these.
json
and jsonb
data types and functions.The manual goes as far as suggesting:
In general, most applications should prefer to store JSON data as
jsonb
, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.
Bold emphasis mine.
Performance benefits from general improvements to GIN indexes.
Complete jsonb
functions and operators. Add more functions to manipulate jsonb
in place and for display.
Sample from apache conf:
#Default value is 2 minutes
**Timeout 600**
ProxyRequests off
ProxyPass /app balancer://MyApp stickysession=JSESSIONID lbmethod=bytraffic nofailover=On
ProxyPassReverse /app balancer://MyApp
ProxyTimeout 600
<Proxy balancer://MyApp>
BalancerMember http://node1:8080/ route=node1 retry=1 max=25 timeout=600
.........
</Proxy>
XSD files are used to validate that XML files conform to a certain format.
In that respect they are similar to DTDs that existed before them.
The main difference between XSD and DTD is that XSD is written in XML and is considered easier to read and understand.
Asynchronous way to achieve it.
void inputStreamToOutputStream(final InputStream inputStream, final OutputStream out) {
Thread t = new Thread(new Runnable() {
public void run() {
try {
int d;
while ((d = inputStream.read()) != -1) {
out.write(d);
}
} catch (IOException ex) {
//TODO make a callback on exception.
}
}
});
t.setDaemon(true);
t.start();
}
More simple,
echo $line | sed 's/\s/\n/g'
\s --> whitespace character (space, tab, NL, FF, VT, CR). In many systems also valid [:space:]
\n --> new line
If you're using Vim, see :h retab
.
*:ret* *:retab* :[range]ret[ab][!] [new_tabstop] Replace all sequences of white-space containing a <Tab> with new strings of white-space using the new tabstop value given. If you do not specify a new tabstop size or it is zero, Vim uses the current value of 'tabstop'. The current value of 'tabstop' is always used to compute the width of existing tabs. With !, Vim also replaces strings of only normal spaces with tabs where appropriate. With 'expandtab' on, Vim replaces all tabs with the appropriate number of spaces. This command sets 'tabstop' to the new value given, and if performed on the whole file, which is default, should not make any visible change. Careful: This command modifies any <Tab> characters inside of strings in a C program. Use "\t" to avoid this (that's a good habit anyway). ":retab!" may also change a sequence of spaces by <Tab> characters, which can mess up a printf(). {not in Vi} Not available when |+ex_extra| feature was disabled at compile time.
For example, if you simply type
:ret
all your tabs will be expanded into spaces.
You may want to
:se et " shorthand for :set expandtab
to make sure that any new lines will not use literal tabs.
If you're not using Vim,
perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py
will replace tabs with spaces, assuming tab stops every 8 characters, in file.py
(with the original going to file.py.bak
, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.
Even if POST
gives no real security benefit versus GET
, for login forms or any other form with relatively sensitive information, make sure you are using POST
as:
POST
ed will not be saved in the user's history.GET
, it will be visible in the history and the URL bar).Also, GET
has a theorical limit of data. POST
doesn't.
For real sensitive info, make sure to use SSL
(HTTPS
)
Import
import android.net.Uri;
Intent openURL = new Intent(android.content.Intent.ACTION_VIEW);
openURL.setData(Uri.parse("http://www.example.com"));
startActivity(openURL);
or it can be done using,
TextView textView = (TextView)findViewById(R.id.yourID);
textView.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
intent.addCategory(Intent.CATEGORY_BROWSABLE);
intent.setData(Uri.parse("http://www.typeyourURL.com"));
startActivity(intent);
} });
Why not have a setSize method.
A* arrayOfAs = new A[5];
for (int i = 0; i < 5; ++i)
{
arrayOfAs[i].SetSize(3);
}
I like the "copy" but in this case the default constructor isn't really doing anything.
The SetSize could copy the data out of the original m_array (if it exists).. You'd have to store the size of the array within the class to do that.
OR
The SetSize could delete the original m_array.
void SetSize(unsigned int p_newSize)
{
//I don't care if it's null because delete is smart enough to deal with that.
delete myArray;
myArray = new int[p_newSize];
ASSERT(myArray);
}
Sometimes you need the extension,
adb push file.zip /sdcard/file.zip
check if string(word/sentence...) contains specific word/character
if ( "write something here".indexOf("write som") > -1 ) { alert( "found it" ); }
I think the problem is with the spaces. I had my variable at the System variables but it didn't work. When I changed variable Progra~1 = 'Program Files'
everything works fine.
M2_HOME C:\Progra~1\Maven\apache-maven-3.1.1
I also moved my M2_HOME
at the end of the PATH(%M2_HOME%\bin)
I'm not sure if this has any difference.
Try LIKE
construction, e.g. (assuming StudentId
is of type Char
, VarChar
etc.)
select *
from Students
where StudentId like '%' || TEXT || '%' -- <- TEXT - text to contain
See the documentation on ?merge
, which states:
By default the data frames are merged on the columns with names they both have,
but separate specifications of the columns can be given by by.x and by.y.
This clearly implies that merge
will merge data frames based on more than one column. From the final example given in the documentation:
x <- data.frame(k1=c(NA,NA,3,4,5), k2=c(1,NA,NA,4,5), data=1:5)
y <- data.frame(k1=c(NA,2,NA,4,5), k2=c(NA,NA,3,4,5), data=1:5)
merge(x, y, by=c("k1","k2")) # NA's match
This example was meant to demonstrate the use of incomparables
, but it illustrates merging using multiple columns as well. You can also specify separate columns in each of x
and y
using by.x
and by.y
.