If anyone is getting this error using Nginx, try adding the following to your server config:
server {
listen 443 ssl;
...
}
The issue stems from Nginx serving an HTTP server to a client expecting HTTPS on whatever port you're listening on. When you specify ssl
in the listen
directive, you clear this up on the server side.
I think it has to do with your second element in storbinary
. You are trying to open file
, but it is already a pointer to the file you opened in line file = open(local_path,'rb')
. So, try to use ftp.storbinary("STOR " + i, file)
.
If you are using curl versions curl-7.19.7-46.el6.x86_64 or older. Please provide an option as -k1 (small K1).
It usually happens when the certificate does not match with the host name.
The solution would be to contact the host and ask it to fix its certificate.
Otherwise you can turn off cURL's verification of the certificate, use the -k
(or --insecure
) option.
Please note that as the option said, it is insecure. You shouldn't use this option because it allows man-in-the-middle attacks and defeats the purpose of HTTPS.
More can be found in here: http://curl.haxx.se/docs/sslcerts.html
Invoke-WebRequest can download HTTP, HTTPS, and FTP links.
$source = 'ftp://Blah.com/somefile.txt'
$target = 'C:\Users\someuser\Desktop\BlahFiles\somefile.txt'
$password = Microsoft.PowerShell.Security\ConvertTo-SecureString -String 'mypassword' -AsPlainText -Force
$credential = New-Object -TypeName System.Management.Automation.PSCredential -ArgumentList myuserid, $password
# Download
Invoke-WebRequest -Uri $source -OutFile $target -Credential $credential -UseBasicParsing
Since the cmdlet uses IE parsing you may need the -UseBasicParsing switch. Test to make sure.
This happened to me as well. The fix was wrapping it in HTML tags. Then I saved the file as /var/www/html/info.php and ran http://localhost/info.php in the browser. That's it.
<html>
<body>
<?php
phpinfo();
?>
</body>
</html>
Try to add auth method explicitly as below, because sometimes it is required:
session.setConfig("PreferredAuthentications", "password");
Windows users, add this to PHP.ini:
curl.cainfo = "C:/cacert.pem";
Path needs to be changed to your own and you can download cacert.pem from a google search
(yes I know its a CentOS question)
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 ;
What about something like this:
for /f %%f in ('curl -s -l -u user:pass ftp://ftp.myftpsite.com/') do curl -O -u user:pass ftp://ftp.myftpsite.com/%%f
[function.fopen]: failed to open stream
If you have access to your php.ini file, try enabling Fopen. Find the respective line and set it to be "on": & if in wp e.g localhost/wordpress/function.fopen in the php.ini :
allow_url_fopen = off
should bee this
allow_url_fopen = On
And add this line below it:
allow_url_include = off
should bee this
allow_url_include = on
Github has page dedicated to troubleshooting this error:
https://help.github.com/articles/https-cloning-errors
In my case it turned out that using a new version of git (1.8.5.2) solved this problem.
Your Apache is probably not compiled with SSL support. Use cURL instead of file_get_contents anyway. Try this code, if it fails then I am right.
function curl_get_contents($url)
{
$curl = curl_init($url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, 0);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, 0);
$data = curl_exec($curl);
curl_close($curl);
return $data;
}
The way to solve your problem is to use a Win32 API called WNetUseConnection.
Use this function to connect to a UNC path with authentication, NOT to map a drive.
This will allow you to connect to a remote machine, even if it is not on the same domain, and even if it has a different username and password.
Once you have used WNetUseConnection you will be able to access the file via a UNC path as if you were on the same domain. The best way is probably through the administrative built in shares.
Example: \\computername\c$\program files\Folder\file.txt
Here is some sample C# code that uses WNetUseConnection.
Note, for the NetResource, you should pass null for the lpLocalName and lpProvider. The dwType should be RESOURCETYPE_DISK. The lpRemoteName should be \\ComputerName.
using System;
using System.Runtime.InteropServices ;
using System.Threading;
namespace ExtremeMirror
{
public class PinvokeWindowsNetworking
{
#region Consts
const int RESOURCE_CONNECTED = 0x00000001;
const int RESOURCE_GLOBALNET = 0x00000002;
const int RESOURCE_REMEMBERED = 0x00000003;
const int RESOURCETYPE_ANY = 0x00000000;
const int RESOURCETYPE_DISK = 0x00000001;
const int RESOURCETYPE_PRINT = 0x00000002;
const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;
const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
const int RESOURCEUSAGE_CONTAINER = 0x00000002;
const int CONNECT_INTERACTIVE = 0x00000008;
const int CONNECT_PROMPT = 0x00000010;
const int CONNECT_REDIRECT = 0x00000080;
const int CONNECT_UPDATE_PROFILE = 0x00000001;
const int CONNECT_COMMANDLINE = 0x00000800;
const int CONNECT_CMD_SAVECRED = 0x00001000;
const int CONNECT_LOCALDRIVE = 0x00000100;
#endregion
#region Errors
const int NO_ERROR = 0;
const int ERROR_ACCESS_DENIED = 5;
const int ERROR_ALREADY_ASSIGNED = 85;
const int ERROR_BAD_DEVICE = 1200;
const int ERROR_BAD_NET_NAME = 67;
const int ERROR_BAD_PROVIDER = 1204;
const int ERROR_CANCELLED = 1223;
const int ERROR_EXTENDED_ERROR = 1208;
const int ERROR_INVALID_ADDRESS = 487;
const int ERROR_INVALID_PARAMETER = 87;
const int ERROR_INVALID_PASSWORD = 1216;
const int ERROR_MORE_DATA = 234;
const int ERROR_NO_MORE_ITEMS = 259;
const int ERROR_NO_NET_OR_BAD_PATH = 1203;
const int ERROR_NO_NETWORK = 1222;
const int ERROR_BAD_PROFILE = 1206;
const int ERROR_CANNOT_OPEN_PROFILE = 1205;
const int ERROR_DEVICE_IN_USE = 2404;
const int ERROR_NOT_CONNECTED = 2250;
const int ERROR_OPEN_FILES = 2401;
private struct ErrorClass
{
public int num;
public string message;
public ErrorClass(int num, string message)
{
this.num = num;
this.message = message;
}
}
// Created with excel formula:
// ="new ErrorClass("&A1&", """&PROPER(SUBSTITUTE(MID(A1,7,LEN(A1)-6), "_", " "))&"""), "
private static ErrorClass[] ERROR_LIST = new ErrorClass[] {
new ErrorClass(ERROR_ACCESS_DENIED, "Error: Access Denied"),
new ErrorClass(ERROR_ALREADY_ASSIGNED, "Error: Already Assigned"),
new ErrorClass(ERROR_BAD_DEVICE, "Error: Bad Device"),
new ErrorClass(ERROR_BAD_NET_NAME, "Error: Bad Net Name"),
new ErrorClass(ERROR_BAD_PROVIDER, "Error: Bad Provider"),
new ErrorClass(ERROR_CANCELLED, "Error: Cancelled"),
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
new ErrorClass(ERROR_INVALID_ADDRESS, "Error: Invalid Address"),
new ErrorClass(ERROR_INVALID_PARAMETER, "Error: Invalid Parameter"),
new ErrorClass(ERROR_INVALID_PASSWORD, "Error: Invalid Password"),
new ErrorClass(ERROR_MORE_DATA, "Error: More Data"),
new ErrorClass(ERROR_NO_MORE_ITEMS, "Error: No More Items"),
new ErrorClass(ERROR_NO_NET_OR_BAD_PATH, "Error: No Net Or Bad Path"),
new ErrorClass(ERROR_NO_NETWORK, "Error: No Network"),
new ErrorClass(ERROR_BAD_PROFILE, "Error: Bad Profile"),
new ErrorClass(ERROR_CANNOT_OPEN_PROFILE, "Error: Cannot Open Profile"),
new ErrorClass(ERROR_DEVICE_IN_USE, "Error: Device In Use"),
new ErrorClass(ERROR_EXTENDED_ERROR, "Error: Extended Error"),
new ErrorClass(ERROR_NOT_CONNECTED, "Error: Not Connected"),
new ErrorClass(ERROR_OPEN_FILES, "Error: Open Files"),
};
private static string getErrorForNumber(int errNum)
{
foreach (ErrorClass er in ERROR_LIST)
{
if (er.num == errNum) return er.message;
}
return "Error: Unknown, " + errNum;
}
#endregion
[DllImport("Mpr.dll")] private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
[DllImport("Mpr.dll")] private static extern int WNetCancelConnection2(
string lpName,
int dwFlags,
bool fForce
);
[StructLayout(LayoutKind.Sequential)] private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
public static string connectToRemote(string remoteUNC, string username, string password)
{
return connectToRemote(remoteUNC, username, password, false);
}
public static string connectToRemote(string remoteUNC, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE();
nr.dwType = RESOURCETYPE_DISK;
nr.lpRemoteName = remoteUNC;
// nr.lpLocalName = "F:";
int ret;
if (promptUser)
ret = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
else
ret = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
if (ret == NO_ERROR) return null;
return getErrorForNumber(ret);
}
public static string disconnectRemote(string remoteUNC)
{
int ret = WNetCancelConnection2(remoteUNC, CONNECT_UPDATE_PROFILE, false);
if (ret == NO_ERROR) return null;
return getErrorForNumber(ret);
}
}
}
hierynomus/sshj has a complete implementation of SFTP version 3 (what OpenSSH implements)
Example code from SFTPUpload.java
package net.schmizz.sshj.examples;
import net.schmizz.sshj.SSHClient;
import net.schmizz.sshj.sftp.SFTPClient;
import net.schmizz.sshj.xfer.FileSystemFile;
import java.io.File;
import java.io.IOException;
/** This example demonstrates uploading of a file over SFTP to the SSH server. */
public class SFTPUpload {
public static void main(String[] args)
throws IOException {
final SSHClient ssh = new SSHClient();
ssh.loadKnownHosts();
ssh.connect("localhost");
try {
ssh.authPublickey(System.getProperty("user.name"));
final String src = System.getProperty("user.home") + File.separator + "test_file";
final SFTPClient sftp = ssh.newSFTPClient();
try {
sftp.put(new FileSystemFile(src), "/tmp");
} finally {
sftp.close();
}
} finally {
ssh.disconnect();
}
}
}
frame = a view's location and size using the parent view's coordinate system
bounds = a view's location and size using its own coordinate system
To help me remember frame, I think of a picture frame on a wall. The picture frame is like the border of a view. I can hang the picture anywhere I want on the wall. In the same way, I can put a view anywhere I want inside a parent view (also called a superview). The parent view is like the wall. The origin of the coordinate system in iOS is the top left. We can put our view at the origin of the superview by setting the view frame's x-y coordinates to (0, 0), which is like hanging our picture in the very top left corner of the wall. To move it right, increase x, to move it down increase y.
To help me remember bounds, I think of a basketball court where sometimes the basketball gets knocked out of bounds. You are dribbling the ball all over the basketball court, but you don't really care where the court itself is. It could be in a gym, or outside at a high school, or in front of your house. It doesn't matter. You just want to play basketball. In the same way, the coordinate system for a view's bounds only cares about the view itself. It doesn't know anything about where the view is located in the parent view. The bounds' origin (point (0, 0) by default) is the top left corner of the view. Any subviews that this view has are laid out in relation to this point. It is like taking the basketball to the front left corner of the court.
Now the confusion comes when you try to compare frame and bounds. It actually isn't as bad as it seems at first, though. Let's use some pictures to help us understand.
In the first picture on the left we have a view that is located at the top left of its parent view. The yellow rectangle represents the view's frame. On the right we see the view again but this time the parent view is not shown. That's because the bounds don't know about the parent view. The green rectangle represents the view's bounds. The red dot in both images represents the origin of the frame or bounds.
Frame
origin = (0, 0)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
So the frame and bounds were exactly the same in that picture. Let's look at an example where they are different.
Frame
origin = (40, 60) // That is, x=40 and y=60
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
So you can see that changing the x-y coordinates of the frame moves it in the parent view. But the content of the view itself still looks exactly the same. The bounds have no idea that anything is different.
Up to now the width and height of both the frame and the bounds have been exactly the same. That isn't always true, though. Look what happens if we rotate the view 20 degrees clockwise. (Rotation is done using transforms. See the the documentation and these view and layer examples for more information.)
Frame
origin = (20, 52) // These are just rough estimates.
width = 118
height = 187
Bounds
origin = (0, 0)
width = 80
height = 130
You can see that the bounds are still the same. They still don't know anything has happened! The frame values have all changed, though.
Now it is a little easier to see the difference between frame and bounds, isn't it? The article You Probably Don't Understand frames and bounds defines a view frame as
...the smallest bounding box of that view with respect to it’s parents coordinate system, including any transformations applied to that view.
It is important to note that if you transform a view, then the frame becomes undefined. So actually, the yellow frame that I drew around the rotated green bounds in the image above never actually exists. That means if you rotate, scale or do some other transformation then you shouldn't use the frame values any more. You can still use the bounds values, though. The Apple docs warn:
Important: If a view’s
transform
property does not contain the identity transform, the frame of that view is undefined and so are the results of its autoresizing behaviors.
Rather unfortunate about the autoresizing.... There is something you can do, though.
When modifying the
transform
property of your view, all transformations are performed relative to the center point of the view.
So if you do need to move a view around in the parent after a transformation has been done, you can do it by changing the view.center
coordinates. Like frame
, center
uses the coordinate system of the parent view.
Ok, let's get rid of our rotation and focus on the bounds. So far the bounds origin has always stayed at (0, 0). It doesn't have to, though. What if our view has a large subview that is too big to display all at once? We'll make it a UIImageView
with a large image. Here is our second picture from above again, but this time we can see what the whole content of our view's subview would look like.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (0, 0)
width = 80
height = 130
Only the top left corner of the image can fit inside the view's bounds. Now look what happens if we change the bounds' origin coordinates.
Frame
origin = (40, 60)
width = 80
height = 130
Bounds
origin = (280, 70)
width = 80
height = 130
The frame hasn't moved in the superview but the content inside the frame has changed because the origin of the bounds rectangle starts at a different part of the view. This is the whole idea behind a UIScrollView
and it's subclasses (for example, a UITableView
). See Understanding UIScrollView for more explanation.
Since frame
relates a view's location in its parent view, you use it when you are making outward changes, like changing its width or finding the distance between the view and the top of its parent view.
Use the bounds
when you are making inward changes, like drawing things or arranging subviews within the view. Also use the bounds to get the size of the view if you have done some transfomation on it.
Apple docs
Related StackOverflow questions
Other resources
In addition to reading the above articles, it helps me a lot to make a test app. You might want to try to do something similar. (I got the idea from this video course but unfortunately it isn't free.)
Here is the code for your reference:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var myView: UIView!
// Labels
@IBOutlet weak var frameX: UILabel!
@IBOutlet weak var frameY: UILabel!
@IBOutlet weak var frameWidth: UILabel!
@IBOutlet weak var frameHeight: UILabel!
@IBOutlet weak var boundsX: UILabel!
@IBOutlet weak var boundsY: UILabel!
@IBOutlet weak var boundsWidth: UILabel!
@IBOutlet weak var boundsHeight: UILabel!
@IBOutlet weak var centerX: UILabel!
@IBOutlet weak var centerY: UILabel!
@IBOutlet weak var rotation: UILabel!
// Sliders
@IBOutlet weak var frameXSlider: UISlider!
@IBOutlet weak var frameYSlider: UISlider!
@IBOutlet weak var frameWidthSlider: UISlider!
@IBOutlet weak var frameHeightSlider: UISlider!
@IBOutlet weak var boundsXSlider: UISlider!
@IBOutlet weak var boundsYSlider: UISlider!
@IBOutlet weak var boundsWidthSlider: UISlider!
@IBOutlet weak var boundsHeightSlider: UISlider!
@IBOutlet weak var centerXSlider: UISlider!
@IBOutlet weak var centerYSlider: UISlider!
@IBOutlet weak var rotationSlider: UISlider!
// Slider actions
@IBAction func frameXSliderChanged(sender: AnyObject) {
myView.frame.origin.x = CGFloat(frameXSlider.value)
updateLabels()
}
@IBAction func frameYSliderChanged(sender: AnyObject) {
myView.frame.origin.y = CGFloat(frameYSlider.value)
updateLabels()
}
@IBAction func frameWidthSliderChanged(sender: AnyObject) {
myView.frame.size.width = CGFloat(frameWidthSlider.value)
updateLabels()
}
@IBAction func frameHeightSliderChanged(sender: AnyObject) {
myView.frame.size.height = CGFloat(frameHeightSlider.value)
updateLabels()
}
@IBAction func boundsXSliderChanged(sender: AnyObject) {
myView.bounds.origin.x = CGFloat(boundsXSlider.value)
updateLabels()
}
@IBAction func boundsYSliderChanged(sender: AnyObject) {
myView.bounds.origin.y = CGFloat(boundsYSlider.value)
updateLabels()
}
@IBAction func boundsWidthSliderChanged(sender: AnyObject) {
myView.bounds.size.width = CGFloat(boundsWidthSlider.value)
updateLabels()
}
@IBAction func boundsHeightSliderChanged(sender: AnyObject) {
myView.bounds.size.height = CGFloat(boundsHeightSlider.value)
updateLabels()
}
@IBAction func centerXSliderChanged(sender: AnyObject) {
myView.center.x = CGFloat(centerXSlider.value)
updateLabels()
}
@IBAction func centerYSliderChanged(sender: AnyObject) {
myView.center.y = CGFloat(centerYSlider.value)
updateLabels()
}
@IBAction func rotationSliderChanged(sender: AnyObject) {
let rotation = CGAffineTransform(rotationAngle: CGFloat(rotationSlider.value))
myView.transform = rotation
updateLabels()
}
private func updateLabels() {
frameX.text = "frame x = \(Int(myView.frame.origin.x))"
frameY.text = "frame y = \(Int(myView.frame.origin.y))"
frameWidth.text = "frame width = \(Int(myView.frame.width))"
frameHeight.text = "frame height = \(Int(myView.frame.height))"
boundsX.text = "bounds x = \(Int(myView.bounds.origin.x))"
boundsY.text = "bounds y = \(Int(myView.bounds.origin.y))"
boundsWidth.text = "bounds width = \(Int(myView.bounds.width))"
boundsHeight.text = "bounds height = \(Int(myView.bounds.height))"
centerX.text = "center x = \(Int(myView.center.x))"
centerY.text = "center y = \(Int(myView.center.y))"
rotation.text = "rotation = \((rotationSlider.value))"
}
}
If you store the jQuery object in a variable you can do this:
var obj = $("#example").text('this\n has\n newlines');_x000D_
obj.html(obj.html().replace(/\n/g,'<br/>'));
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p id="example"></p>
_x000D_
If you prefer, you can also create a function to do this with a simple call, just like jQuery.text() does:
$.fn.multiline = function(text){_x000D_
this.text(text);_x000D_
this.html(this.html().replace(/\n/g,'<br/>'));_x000D_
return this;_x000D_
}_x000D_
_x000D_
// Now you can do this:_x000D_
$("#example").multiline('this\n has\n newlines');
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<p id="example"></p>
_x000D_
You're using the declarative style of specifying your pipeline, so you must not use try/catch blocks (which are for Scripted Pipelines), but the post section. See: https://jenkins.io/doc/book/pipeline/syntax/#post-conditions
Use the following:
type file.txt | findstr /v ERROR | findstr /v REFERENCE
This has the advantage of using standard tools in the Windows OS, rather than having to find and install sed/awk/perl and such.
See the following transcript for it in operation:
C:\>type file.txt Good Line of data bad line of C:\Directory\ERROR\myFile.dll Another good line of data bad line: REFERENCE Good line C:\>type file.txt | findstr /v ERROR | findstr /v REFERENCE Good Line of data Another good line of data Good line
You can achieve that by using positioning.
Try
position: absolute;
to get the 100% height.
Note that you have to be careful if your row contains a factor. Here is an example:
df_1 = data.frame(V1 = factor(11:15),
V2 = 21:25)
df_1[1,] %>% as.numeric() # you expect 11 21 but it returns
[1] 1 21
Here is another example (by default data.frame() converts characters to factors)
df_2 = data.frame(V1 = letters[1:5],
V2 = 1:5)
df_2[3,] %>% as.numeric() # you expect to obtain c 3 but it returns
[1] 3 3
df_2[3,] %>% as.character() # this won't work neither
[1] "3" "3"
To prevent this behavior, you need to take care of the factor, before extracting it:
df_1$V1 = df_1$V1 %>% as.character() %>% as.numeric()
df_2$V1 = df_2$V1 %>% as.character()
df_1[1,] %>% as.numeric()
[1] 11 21
df_2[3,] %>% as.character()
[1] "c" "3"
From Save MySQL query results into a text or CSV file:
MySQL provides an easy mechanism for writing the results of a select statement into a text file on the server. Using extended options of the INTO OUTFILE nomenclature, it is possible to create a comma separated value (CSV) which can be imported into a spreadsheet application such as OpenOffice or Excel or any other application which accepts data in CSV format.
Given a query such as
SELECT order_id,product_name,qty FROM orders
which returns three columns of data, the results can be placed into the file /tmp/orders.txt using the query:
SELECT order_id,product_name,qty FROM orders INTO OUTFILE '/tmp/orders.txt'
This will create a tab-separated file, each row on its own line. To alter this behavior, it is possible to add modifiers to the query:
SELECT order_id,product_name,qty FROM orders INTO OUTFILE '/tmp/orders.csv' FIELDS TERMINATED BY ',' ENCLOSED BY '"' LINES TERMINATED BY '\n'
In this example, each field will be enclosed in double quotes, the fields will be separated by commas, and each row will be output on a new line separated by a newline (\n). Sample output of this command would look like:
"1","Tech-Recipes sock puppet","14.95" "2","Tech-Recipes chef's hat","18.95"
Keep in mind that the output file must not already exist and that the user MySQL is running as has write permissions to the directory MySQL is attempting to write the file to.
Syntax
SELECT Your_Column_Name
FROM Your_Table_Name
INTO OUTFILE 'Filename.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
LINES TERMINATED BY '\n'
Or you could try to grab the output via the client:
You could try executing the query from the your local client and redirect the output to a local file destination:
mysql -user -pass -e "select cols from table where cols not null" > /tmp/output
Hint: If you don't specify an absoulte path but use something like INTO OUTFILE 'output.csv'
or INTO OUTFILE './output.csv'
, it will store the output file to the directory specified by show variables like 'datadir';
.
This error means that file was not found. Either path is wrong or file is not present where you want it to be. Try to access it by entering source address in your browser to check if it really is there. Browse the directories on server to ensure the path is correct. You may even copy and paste the relative path to be certain it is alright.
I found 2 things worth mentioning while uploading files using webdav and http web request. First, for the provider I was using, I had to append the filename at the end of the provider url. Ihad to append the port number in the url. And I also set the Request method to PUT instead of POST.
example:
string webdavUrl = "https://localhost:443/downloads/test.pdf";
request.Method = "PUT";
This issue happened in my project because of an ajax GET call with a long xml string as a parameter value. Solved by the following approach: Making it as ajax post call to Java Spring MVC controller class method like this.
$.ajax({
url: "controller_Method_Name.html?variable_name="+variable_value,
type: "POST",
data:{
"xmlMetaData": xmlMetaData // This variable contains a long xml string
},
success: function(response)
{
console.log(response);
}
});
Inside Spring MVC Controller class method:
@RequestMapping(value="/controller_Method_Name")
public void controller_Method_Name(@RequestParam("xmlMetaData") String metaDataXML, HttpServletRequest request)
{
System.out.println(metaDataXML);
}
Here's what I currently use. The triple comment ( / * / * / * ) is for an integration that picks out header comments from the object definition.
/*/*/*
Name: pr_ProcName
Author: Joe Smith
Written: 6/15/16
Purpose: Short description about the proc.
Edit History: 6/15/16 - Joe Smith
+ Initial creation.
6/22/16 - Jaden Smith
+ Change source to blahblah
+ Optimized JOIN
6/30/16 - Joe Smith
+ Reverted changes made by Jaden.
*/*/*/
for throttle
or debounce
the best way is to create a function creator so you can use it any where, for example:
updateUserProfileField(fieldName) {
const handler = throttle(value => {
console.log(fieldName, value);
}, 400);
return evt => handler(evt.target.value.trim());
}
and in your render
method you can do:
<input onChange={this.updateUserProfileField("givenName").bind(this)}/>
the updateUserProfileField
method will create a separated function each time you call it.
Note don't try to return the handler directly for example this will not work:
updateUserProfileField(fieldName) {
return evt => throttle(value => {
console.log(fieldName, value);
}, 400)(evt.target.value.trim());
}
the reason why this will not work because this will generate a new throttle function each time the event called instead of using the same throttle function, so basically the throttle will be useless ;)
Also if you use debounce
or throttle
you don't need setTimeout
or clearTimeout
, this is actually why we use them :P
Assign the members directly without the .Value
part:
DateTimeExtended(DateTimeExtended myNewDT)
{
this.MyDateTime = myNewDT.MyDateTime;
this.otherdata = myNewDT.otherdata;
}
Before we try to solve the invalid character problem, the lack of curly braces around the if
and else if
statements is wreaking havoc on your program's logic. Change it to this:
if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
}
else
System.out.println("Invalid user input.");
Much clearer! It's now actually a piece of cake to catch the bad characters. You need to move the else
statement to somewhere that will catch the errors before you attempt to process anything else. So change everything to:
if( /* insert your check for bad characters here */ ) {
System.out.println("Invalid user input.");
}
else if (personPlay.equals(computerPlay)) {
System.out.println("It's a tie!");
}
else if (personPlay.equals("R")) {
if (computerPlay.equals("S"))
System.out.println("Rock crushes scissors. You win!!");
else if (computerPlay.equals("P"))
System.out.println("Paper eats rock. You lose!!");
}
else if (personPlay.equals("P")) {
if (computerPlay.equals("S"))
System.out.println("Scissor cuts paper. You lose!!");
else if (computerPlay.equals("R"))
System.out.println("Paper eats rock. You win!!");
}
else if (personPlay.equals("S")) {
if (computerPlay.equals("P"))
System.out.println("Scissor cuts paper. You win!!");
else if (computerPlay.equals("R"))
System.out.println("Rock breaks scissors. You lose!!");
}
DotNetCoders has a starter article on it: http://www.dotnetcoders.com/web/Articles/ShowArticle.aspx?article=50. They talk about how to set up the switches in the configuration file and how to write the code, but it is pretty old (2002).
There's another article on CodeProject: A Treatise on Using Debug and Trace classes, including Exception Handling, but it's the same age.
CodeGuru has another article on custom TraceListeners: Implementing a Custom TraceListener
json.loads
take a string as input and returns a dictionary as output.
json.dumps
take a dictionary as input and returns a string as output.
With json.loads({"('Hello',)": 6, "('Hi',)": 5})
,
You are calling json.loads
with a dictionary as input.
You can fix it as follows (though I'm not quite sure what's the point of that):
d1 = {"('Hello',)": 6, "('Hi',)": 5}
s1 = json.dumps(d1)
d2 = json.loads(s1)
This issue often happens when we try to merge another branch changes from a wrong directory.
Ex:
Branch2\Branch1_SubDir$ svn merge -rStart:End Branch1
^^^^^^^^^^^^
Merging at wrong location
A conflict that gets thrown on its execution is :
Tree conflict on 'Branch1_SubDir'
> local missing or deleted or moved away, incoming dir edit upon merge
And when you select q to quit resolution, you get status as:
M .
! C Branch1_SubDir
> local missing or deleted or moved away, incoming dir edit upon merge
! C Branch1_AnotherSubDir
> local missing or deleted or moved away, incoming dir edit upon merge
which clearly means that the merge contains changes related to Branch1_SubDir
and Branch1_AnotherSubDir
, and these folders couldn't be found inside Branch1_SubDir
(obviously a directory can't be inside itself).
How to avoid this issue at first place:
Branch2$ svn merge -rStart:End Branch1
^^^^
Merging at root location
The simplest fix for this issue that worked for me :
svn revert -R .
Or you can use
<select [(ngModel)]="Answers[''+question.Name+'']" ng-options="option for option in question.Options">
</select>
For referential integtity :
insert into main_tbl (col1, ref1, ref2, createdby)
values ('col1_val',
(select ref1 from ref1_tbl where lookup_val = 'lookup1'),
(select ref2 from ref2_tbl where lookup_val = 'lookup2'),
'init-load'
);
There are a few options
Using the host : guest
format you can do any of the following:
volumes:
# Just specify a path and let the Engine create a volume
- /var/lib/mysql
# Specify an absolute path mapping
- /opt/data:/var/lib/mysql
# Path on the host, relative to the Compose file
- ./cache:/tmp/cache
# User-relative path
- ~/configs:/etc/configs/:ro
# Named volume
- datavolume:/var/lib/mysql
As of docker-compose v3.2 you can use long syntax which allows the configuration of additional fields that can be expressed in the short form such as mount type
(volume, bind or tmpfs) and read_only
.
version: "3.2"
services:
web:
image: nginx:alpine
ports:
- "80:80"
volumes:
- type: volume
source: mydata
target: /data
volume:
nocopy: true
- type: bind
source: ./static
target: /opt/app/static
networks:
webnet:
volumes:
mydata:
Check out https://docs.docker.com/compose/compose-file/#long-syntax-3 for more info.
You must perform a terminal operation on the Stream in order for any of the filters to be applied. Therefore you can't know if it will be empty until you consume it.
Best you can do is terminate the Stream with a findAny()
terminal operation, which will stop when it finds any element, but if there are none, it will have to iterate over all the input list to find that out.
This would only help you if the input list has many elements, and one of the first few passes the filters, since only a small subset of the list would have to be consumed before you know the Stream is not empty.
Of course you'll still have to create a new Stream in order to produce the output list.
Recursions are always faster than loops!
Shortest and best:
public static long sumDigits(long i) {
return i == 0 ? 0 : i % 10 + sumDigits(i / 10);
}
2 solutions for a random string consisting of 3 ranges:
(('a'..'z').to_a + ('A'..'Z').to_a + (0..9).to_a).sample(8).join
([*(48..57),*(65..90),*(97..122)]).sample(8).collect(&:chr)*""
And if you need at least one character from each range, such as creating a random password that has one uppercase, one lowercase letter and one digit, you can do something like this:
( ('a'..'z').to_a.sample(8) + ('A'..'Z').to_a.sample(8) + (0..9).to_a.sample(8) ).shuffle.join
#=> "Kc5zOGtM0H796QgPp8u2Sxo1"
You should post a message from frame to parent, after loaded.
frame script:
$(document).ready(function() {
window.parent.postMessage("I'm loaded", "*");
});
And listen it in parent:
function listenMessage(msg) {
alert(msg);
}
if (window.addEventListener) {
window.addEventListener("message", listenMessage, false);
} else {
window.attachEvent("onmessage", listenMessage);
}
Use this link for more info: http://en.wikipedia.org/wiki/Web_Messaging
Here are the basic instructions:-
%CATALINA_HOME%/conf/server.xml
).<Connector
.protocol="HTTP/1.1"
.connectionTimeout
value is set on the connector, it may need to be increased - e.g. from 20000 milliseconds (= 20 seconds) to 120000 milliseconds (= 2 minutes). If no connectionTimeout
property value is set on the connector, the default is 60 seconds - if this is insufficient, the property may need to be added.Considering everyone is posting older ways of hiding the ActionBar here is the proper way of implementing it within styles for AppCompat support library. Which I highly suggest moving toward if you haven't already.
Simply removing the ActionBar
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
</style>
If you are using the appcompat support libraries, this is the easiest and recommended way of hiding the ActionBar to make full screen or start implementing to toolbar within your layouts.
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Your Toolbar Color-->
<item name="colorPrimary">@color/primary</item>
<!-- colorPrimaryDark is used for the status bar -->
<item name="colorPrimaryDark">@color/primary_dark</item>
<!-- colorAccent is used as the default value for colorControlActivated,
which is used to tint widgets -->
<item name="colorAccent">@color/accent</item>
<!-- You can also set colorControlNormal, colorControlActivated
colorControlHighlight, and colorSwitchThumbNormal. -->
</style>
Then to change your toolbar color
<android.support.v7.widget.Toolbar
android:id=”@+id/my_awesome_toolbar”
android:layout_height=”wrap_content”
android:layout_width=”match_parent”
android:minHeight=”?attr/actionBarSize”
android:background=”?attr/primary” />
Last note: Your Activity class should extend AppCompatActivity
public class MainActivity extends AppCompatActivity {
<!--Activity Items -->
}
// at class level;
[System.Runtime.InteropServices.DllImport("gdi32.dll")]
public static extern bool DeleteObject(IntPtr hObject); // https://stackoverflow.com/a/1546121/194717
/// <summary>
/// Converts a <see cref="System.Drawing.Bitmap"/> into a WPF <see cref="BitmapSource"/>.
/// </summary>
/// <remarks>Uses GDI to do the conversion. Hence the call to the marshalled DeleteObject.
/// </remarks>
/// <param name="source">The source bitmap.</param>
/// <returns>A BitmapSource</returns>
public static System.Windows.Media.Imaging.BitmapSource ToBitmapSource(this System.Drawing.Bitmap source)
{
var hBitmap = source.GetHbitmap();
var result = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(hBitmap, IntPtr.Zero, System.Windows.Int32Rect.Empty, System.Windows.Media.Imaging.BitmapSizeOptions.FromEmptyOptions());
DeleteObject(hBitmap);
return result;
}
You can use this code to get your desire output
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'color': ['red','red','red','blue','blue','blue'], 'x': [0,1,2,3,4,5],'y': [0,1,2,9,16,25]})
print df
color x y
0 red 0 0
1 red 1 1
2 red 2 2
3 blue 3 9
4 blue 4 16
5 blue 5 25
To plot graph
a = df.iloc[[i for i in xrange(0,len(df)) if df['x'][i]==df['y'][i]]].plot(x='x',y='y',color = 'red')
df.iloc[[i for i in xrange(0,len(df)) if df['y'][i]== df['x'][i]**2]].plot(x='x',y='y',color = 'blue',ax=a)
plt.show()
Output
A standard Maven
settings.xml
file is as follows:
<settings xmlns="http://maven.apache.org/SETTINGS/1.1.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.1.0 http://maven.apache.org/xsd/settings-1.1.0.xsd">
<localRepository/>
<interactiveMode/>
<usePluginRegistry/>
<offline/>
<proxies>
<proxy>
<active/>
<protocol/>
<username/>
<password/>
<port/>
<host/>
<nonProxyHosts/>
<id/>
</proxy>
</proxies>
<servers>
<server>
<username/>
<password/>
<privateKey/>
<passphrase/>
<filePermissions/>
<directoryPermissions/>
<configuration/>
<id/>
</server>
</servers>
<mirrors>
<mirror>
<mirrorOf/>
<name/>
<url/>
<layout/>
<mirrorOfLayouts/>
<id/>
</mirror>
</mirrors>
<profiles>
<profile>
<activation>
<activeByDefault/>
<jdk/>
<os>
<name/>
<family/>
<arch/>
<version/>
</os>
<property>
<name/>
<value/>
</property>
<file>
<missing/>
<exists/>
</file>
</activation>
<properties>
<key>value</key>
</properties>
<repositories>
<repository>
<releases>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</releases>
<snapshots>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</snapshots>
<id/>
<name/>
<url/>
<layout/>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<releases>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</releases>
<snapshots>
<enabled/>
<updatePolicy/>
<checksumPolicy/>
</snapshots>
<id/>
<name/>
<url/>
<layout/>
</pluginRepository>
</pluginRepositories>
<id/>
</profile>
</profiles>
<activeProfiles/>
<pluginGroups/>
</settings>
To access a proxy
, you can find detailed information on the official Maven
page here:
I hope it helps for someone.
var html = "<p>Hello, <b>World</b>";
var div = document.createElement("div");
div.innerHTML = html;
alert(div.innerText); // Hello, World
That pretty much the best way of doing it, you're letting the browser do what it does best -- parse HTML.
Edit: As noted in the comments below, this is not the most cross-browser solution. The most cross-browser solution would be to recursively go through all the children of the element and concatenate all text nodes that you find. However, if you're using jQuery, it already does it for you:
alert($("<p>Hello, <b>World</b></p>").text());
Check out the text method.
The accepted answer didn't work for me but the following did:
>PsExec.exe \\<SERVER FQDN> -u <DOMAIN\USER> -p <PASSWORD> /accepteula cmd
/c "powershell -noninteractive -command gci c:\"
Example from here
With the link provided by @mattdlockyer as reference, this worked for me:
var mongo = require('mongodb');
var server = new mongo.Server(host, port, options);
db = new mongo.Db(mydb, server, {fsync:true});
db.open(function(err, db) {
if(!err) {
console.log("Connected to database");
db.authenticate(user, password, function(err, res) {
if(!err) {
console.log("Authenticated");
} else {
console.log("Error in authentication.");
console.log(err);
}
});
} else {
console.log("Error in open().");
console.log(err);
};
});
exports.testMongo = function(req, res){
db.collection( mycollection, function(err, collection) {
collection.find().toArray(function(err, items) {
res.send(items);
});
});
};
if (!secondaryPassword.equals(initialPassword))
Here's a trick if you want constants and don't care their values:
Just define empty classes.
e.g:
class RED:
pass
class BLUE:
pass
These are two different modes in which your computer can operate. Prior to this, when computers were like a big room, if something crashes – it halts the whole computer. So computer architects decide to change it. Modern microprocessors implement in hardware at least 2 different states.
User mode:
Kernel mode:
How the switch occurs.
The switch from user mode to kernel mode is not done automatically by CPU. CPU is interrupted by interrupts (timers, keyboard, I/O). When interrupt occurs, CPU stops executing the current running program, switch to kernel mode, executes interrupt handler. This handler saves the state of CPU, performs its operations, restore the state and returns to user mode.
http://en.wikibooks.org/wiki/Windows_Programming/User_Mode_vs_Kernel_Mode
http://tldp.org/HOWTO/KernelAnalysis-HOWTO-3.html
Here is what I used to call something I couldn't change using NSInvocation:
SEL theSelector = NSSelectorFromString(@"setOrientation:animated:");
NSInvocation *anInvocation = [NSInvocation
invocationWithMethodSignature:
[MPMoviePlayerController instanceMethodSignatureForSelector:theSelector]];
[anInvocation setSelector:theSelector];
[anInvocation setTarget:theMovie];
UIInterfaceOrientation val = UIInterfaceOrientationPortrait;
BOOL anim = NO;
[anInvocation setArgument:&val atIndex:2];
[anInvocation setArgument:&anim atIndex:3];
[anInvocation performSelector:@selector(invoke) withObject:nil afterDelay:1];
1) Your existing web.config: you have declared rewrite map .. but have not created any rules that will use it. RewriteMap on its' own does absolutely nothing.
2) Below is how you can do it (it does not utilise rewrite maps -- rules only, which is fine for small amount of rewrites/redirects):
This rule will do SINGLE EXACT rewrite (internal redirect) /page
to /page.html
. URL in browser will remain unchanged.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRewrite" stopProcessing="true">
<match url="^page$" />
<action type="Rewrite" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
This rule #2 will do the same as above, but will do 301 redirect (Permanent Redirect) where URL will change in browser.
<system.webServer>
<rewrite>
<rules>
<rule name="SpecificRedirect" stopProcessing="true">
<match url="^page$" />
<action type="Redirect" url="/page.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
Rule #3 will attempt to execute such rewrite for ANY URL if there are such file with .html extension (i.e. for /page
it will check if /page.html
exists, and if it does then rewrite occurs):
<system.webServer>
<rewrite>
<rules>
<rule name="DynamicRewrite" stopProcessing="true">
<match url="(.*)" />
<conditions>
<add input="{REQUEST_FILENAME}\.html" matchType="IsFile" />
</conditions>
<action type="Rewrite" url="/{R:1}.html" />
</rule>
</rules>
</rewrite>
</system.webServer>
The solution given by luschn and pillravi works fine unless you receive a Strict-Transport-Security header in the response.
Adding withCredentials: true will solve that issue.
axios.post(session_url, {
withCredentials: true,
headers: {
"Accept": "application/json",
"Content-Type": "application/json"
}
},{
auth: {
username: "USERNAME",
password: "PASSWORD"
}}).then(function(response) {
console.log('Authenticated');
}).catch(function(error) {
console.log('Error on Authentication');
});
After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003
Young generation garbage collection algorithms
The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.
The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.
The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).
From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.
On Windows 7, the Program Files directory is protected so apps can't automatically write there. The simplest solution I've heard is just to install Eclipse into a user-writable location instead. For example, C:\Java\Eclipse
You should be able to just move your entire eclipse directory, there's no registry entries or anything else that ties Eclipse to the place where you extracted it.
[Edit] Have you checked that the directory it is complaining about i actually writable? Other than that, I really don't have any ideas. I haven't worked on Windows in several years and never with Win7. My only other suggestion is to just download the latest Eclipse, install it to a new location (do NOT intall it over top of your existing Eclipse), and point it to your existing workspace.
The MySQL daemon should not be executed as the system user root
which (normally) do not has any restrictions.
According to your cli, I suppose you wanted to execute the initscript instead:
sudo /etc/init.d/mysql stop
Another way would be to use the mysqladmin tool (note, root
is the MySQL root user here, not the system root
user):
/usr/local/mysql/bin/mysqladmin --port=8889 -u root shutdown
If you want all the dependencies in a single file at the end within two steps.
Add this to your build.gradle.kts
in the root of your project:
project.rootProject.allprojects {
apply(plugin="project-report")
this.task("allDependencies", DependencyReportTask::class) {
evaluationDependsOnChildren()
this.setRenderer(AsciiDependencyReportRenderer())
}
}
Then apply:
./gradlew allDependencies | grep '\-\-\-' | grep -Po '\w+.*$' | awk -F ' ' '{ print $1 }' | sort | grep -v '\{' | grep -v '\[' | uniq | grep '.\+:.\+:.\+'
This will give you all the dependencies in your project and sub-projects along with all the 3rd party dependencies.
If you want to get this done in a programmatic way, then you'll need a custom renderer of the dependencies - you can start by extending the AsciiDependencyReportRenderer
that prints an ascii graph of the dependencies by default.
If you want a HTML only solution, we can just use the pre
tag. It defines "preformatted text" which means that it does not format word-wrapping. Here is a quick example to explain:
div {
width: 200px;
height: 200px;
padding: 20px;
background: #adf;
}
pre {
width: 200px;
height: 200px;
padding: 20px;
font: inherit;
background: #fda;
}
_x000D_
<div>Look at this, this text is very neat, isn't it? But it's not quite what we want, though, is it? This text shouldn't be here! It should be all the way over there! What can we do?</div>
<pre>The pre tag has come to the rescue! Yay! However, we apologise in advance for any horizontal scrollbars that may be caused. If you need support, please raise a support ticket.</pre>
_x000D_
You can find/debug XPath/CSS locators in the IE as well as in different browsers with the tool called SWD Page Recorder
The only restrictions/limitations:
IEDriverServer.exe
- should be downloaded separately and placed near SwdPageRecorder.exe
Completely nothing worked out for me from these answers. Had to create the project again by running cordova platform add ios
. What I've noticed, even freshly generated project with (in my case) Firebase pods caused the error message over and over again. In my opinion looks like a bug for some (Firebase, RestKit) pods in Xcode
or CocoaPods
. To have the pods included I could simply edit my config.xml
and run cordova platform add iOS
, which did everything for me automatically. Not sure if it will work in all scenarios though.
Edit: I had a Podfile
from previous iOS
/Xcode
, but the newest as of today have # DO NOT MODIFY -- auto-generated by Apache Cordova
in the Podfile
. This turned on a light in my head to try the approach. Looks a bit trivial, but works and my Firebase
features worked out.
For those, who wonder how it goes in VS.
MSVC 2015 Update 1, cl.exe version 19.00.24215.1:
#include <iostream>
template<typename X, typename Y>
struct A
{
template<typename Z>
static void f()
{
std::cout << "from A::f():" << std::endl
<< __FUNCTION__ << std::endl
<< __func__ << std::endl
<< __FUNCSIG__ << std::endl;
}
};
void main()
{
std::cout << "from main():" << std::endl
<< __FUNCTION__ << std::endl
<< __func__ << std::endl
<< __FUNCSIG__ << std::endl << std::endl;
A<int, float>::f<bool>();
}
output:
from main(): main main int __cdecl main(void) from A::f(): A<int,float>::f f void __cdecl A<int,float>::f<bool>(void)
Using of __PRETTY_FUNCTION__
triggers undeclared identifier error, as expected.
Thought I would share my solution using a function component... 'this' not needed!
React 16.12.0 and React Native 0.61.5
Here is an example of my component:
import React, { useRef } from 'react'
...
const MyFormComponent = () => {
const ref_input2 = useRef();
const ref_input3 = useRef();
return (
<>
<TextInput
placeholder="Input1"
autoFocus={true}
returnKeyType="next"
onSubmitEditing={() => ref_input2.current.focus()}
/>
<TextInput
placeholder="Input2"
returnKeyType="next"
onSubmitEditing={() => ref_input3.current.focus()}
ref={ref_input2}
/>
<TextInput
placeholder="Input3"
ref={ref_input3}
/>
</>
)
}
This is a dynamic solution which works with all value types including objects :
class Session extends Map {
set(id, value) {
if (typeof value === 'object') value = JSON.stringify(value);
sessionStorage.setItem(id, value);
}
get(id) {
const value = sessionStorage.getItem(id);
try {
return JSON.parse(value);
} catch (e) {
return value;
}
}
}
Then :
const session = new Session();
session.set('name', {first: 'Ahmed', last : 'Toumi'});
session.get('name');
Update Feb. 2021, as noted by Abhishek Singh in the comments, and Nat Friedman on Twitter:
You can now – finally! – drop images and videos (mp4, gif) onto the Markdown file editor on GitHub.
Paste works too, if you're into that kind of thing.
It's worked in issues and PRs for a while; what's new here is support in markdown files.GitHub Enterprise Server tends to lag http://github.com by a couple of months, but it will get there in a future release.
Kyle Daigle (Senior Director of Special Projects at GitHub) adds:
Currently, the file is stored as an asset outside the repository (sort of like an image uploaded to an image).
(Uploads to githubusercontent and stores it there. Then makes a link in the markdown to that uploaded image.)The team is interested in exploring adding the image to the repo too... would you want something like that?
Sven-Michael Stübe comments:
I usually add the images to my repo. Especially if you host your blog as github page w/ a custom domain.
But I think this feature would also add a lot of complexity. It's not a big pain to add the image manually. For PRs+Comments the drag&drop is more essential
Kyle answers:
For the blog case (which is what made us think about image upload to the repo) you're totally right.
This type of drag and drop is helpful when adding an image to aREADME
or other in-repo documentation though (when you don't want to upload to the repo).
That feature has come a long way since its initial proposal... back in 2012(!)
Update Dec. 2020: see "Video upload public beta ", which embeds video (embedding only, not link/reference)
2010: The "Github Flavored Markdown" doesn't support this kind of feature for any page:
An old support thread "Embed YouTube videos in markdown files" stated:
With
pages.github.io
, yes, everywhere else, no.
(Note: as detailed in "Github Top-Level Project Page", github.io is the new domain for user and organization pages since April 2013.
The page GitHub publication is presented here)
This could be a feature request like the syntax highlighting was.
For instance: "HTML5 video in markdown" (August 2010):
Is there any way to implement a HTML5 video into the
README.markdown
file?Not currently but we might be expanding what you can do with the READMEs in the future.
In the meantime, you can do this with GitHub Pages and our Wikis.
Benjamin Oakes confirms in the comments (May 2012):
I sent in a support request. The response was that embedding videos is not supported.
Thanks @Vincent Robert, I ended up using your basic example, though it's actually newBegin + oldEnd - oldBegin
. Here's the simplified end solution:
// don't update end date if there's already an end date but not an old start date
if (!oldEnd || oldBegin) {
var selectedDateSpan = 1800000; // 30 minutes
if (oldEnd) {
selectedDateSpan = oldEnd - oldBegin;
}
newEnd = new Date(newBegin.getTime() + selectedDateSpan));
}
If the string you're pulling in happens to be a hex number such as E01, then Excel will translate it as 0 even if you use the CStr function, and even if you first deposit it in a String variable type. One way around the issue is to append ' to the beginning of the value.
For example, when pulling values out of a Word table, and bringing them to Excel:
strWr = "'" & WorksheetFunction.Clean(.cell(iRow, iCol).Range.Text)
I had a similar problem which I solved by changing the Port Settings in the port driver (located in Ports in device manager) to fit the device I was using.
For me it was that wrong Bits per second value was set.
Create the Tensorboard callback:
from keras.callbacks import TensorBoard
from datetime import datetime
logDir = "./Graph/" + datetime.now().strftime("%Y%m%d-%H%M%S") + "/"
tb = TensorBoard(log_dir=logDir, histogram_freq=2, write_graph=True, write_images=True, write_grads=True)
Pass the Tensorboard callback to the fit call:
history = model.fit(X_train, y_train, epochs=200, callbacks=[tb])
When running the model, if you get a Keras error of
"You must feed a value for placeholder tensor"
try reseting the Keras session before the model creation by doing:
import keras.backend as K
K.clear_session()
Reiterating what others said, its not possible to check the values without running the graph.
A simple snippet for anyone looking for an easy example to print values is as below. The code can be executed without any modification in ipython notebook
import tensorflow as tf
#define a variable to hold normal random values
normal_rv = tf.Variable( tf.truncated_normal([2,3],stddev = 0.1))
#initialize the variable
init_op = tf.initialize_all_variables()
#run the graph
with tf.Session() as sess:
sess.run(init_op) #execute init_op
#print the random values that we sample
print (sess.run(normal_rv))
Output:
[[-0.16702934 0.07173464 -0.04512421]
[-0.02265321 0.06509651 -0.01419079]]
When using barrel imports - consider importing injectables first as a rule of thumb.
Usually, all you need to do is to "Add CORS Configuration" in your bucket properties.
The <CORSConfiguration>
comes with some default values. That's all I needed to solve your problem. Just click "Save" and try again to see if it worked. If it doesn't, you could also try the code below (from alxrb answer) which seems to have worked for most of the people.
<?xml version="1.0" encoding="UTF-8"?>
<CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/">
<CORSRule>
<AllowedOrigin>*</AllowedOrigin>
<AllowedMethod>GET</AllowedMethod>
<AllowedMethod>HEAD</AllowedMethod>
<MaxAgeSeconds>3000</MaxAgeSeconds>
<AllowedHeader>Authorization</AllowedHeader>
</CORSRule>
</CORSConfiguration>
For further info, you can read this article on Editing Bucket Permission.
As Matt has said, use Console.Write
. I would also recommend explicitly flushing the output, however - I believe WriteLine
does this automatically, but I'd seen oddities when just using Console.Write
and then waiting. So Matt's code becomes:
Console.Write("What is your name? ");
Console.Out.Flush();
var name = Console.ReadLine();
It will become easy to store files after converting in string you just have to convert string in image in your frontend
convert image in to base64 string using this code in your api and also don't forgot to delete file from upload folder
"img": new Buffer.from(fs.readFileSync(req.file.path)).toString("base64")
to delete the file
let resultHandler = function (err) {
if (err) {
console.log("unlink failed", err);
} else {
console.log("file deleted");
}
}
fs.unlink(req.file.path, resultHandler);
at your routes import multer
`multer const multer = require('multer');
const upload = multer({ dest: __dirname + '/uploads/images' });`
Add upload.single('img') in your request
router.post('/fellows-details', authorize([Role.ADMIN, Role.USER]),
upload.single('img'), usersController.fellowsdetails);
OR
If you want save images in localstorage
and want save path in database you can try following approach
you have to install first the fs-extra which will create folder. I am creating separate folders by id's if you want to remove it you can remove it. and to save path of image where it is uploaded add this code in your api or controller you are using to save image and and add it in database with other data
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
create separate folder for multer
like multerHelper.js
const multer = require('multer');
let fs = require('fs-extra');
let storage = multer.diskStorage({
destination: function (req, file, cb) {
let Id = req.body.id;
let path = `tmp/daily_gasoline_report/${Id}`;
fs.mkdirsSync(path);
cb(null, path);
},
filename: function (req, file, cb) {
// console.log(file);
let extArray = file.mimetype.split("/");
let extension = extArray[extArray.length - 1];
cb(null, file.fieldname + '-' + Date.now() + "." + extension);
}
})
let upload = multer({ storage: storage });
let createUserImage = upload.array('images', 100);
let multerHelper = {
createUserImage,
}
module.exports = multerHelper;
In your routes import multerhelper
file
const multerHelper = require("../helpers/multer_helper");
router.post(multerHelper. createUserImage , function(req, res, next) {
//Here accessing the body datas.
})
Jarrett's answer creates a new table.
Scott's answer inserts into an existing table with the same structure.
You can also insert into a table with different structure:
INSERT Table2
(columnX, columnY)
SELECT column1, column2 FROM Table1
WHERE [Conditions]
Here's short sub without error handling that creates subdirectories:
Public Function CreateSubDirs(ByVal vstrPath As String)
Dim marrPath() As String
Dim mint As Integer
marrPath = Split(vstrPath, "\")
vstrPath = marrPath(0) & "\"
For mint = 1 To UBound(marrPath) 'walk down directory tree until not exists
If (Dir(vstrPath, vbDirectory) = "") Then Exit For
vstrPath = vstrPath & marrPath(mint) & "\"
Next mint
MkDir vstrPath
For mint = mint To UBound(marrPath) 'create directories
vstrPath = vstrPath & marrPath(mint) & "\"
MkDir vstrPath
Next mint
End Function
Objects in Python can have attributes -- data attributes and functions to work with those (methods). Actually, every object has built-in attributes.
For example you have an object person
, that has several attributes: name
, gender
, etc.
You access these attributes (be it methods or data objects) usually writing: person.name
, person.gender
, person.the_method()
, etc.
But what if you don't know the attribute's name at the time you write the program? For example you have attribute's name stored in a variable called attr_name
.
if
attr_name = 'gender'
then, instead of writing
gender = person.gender
you can write
gender = getattr(person, attr_name)
Some practice:
Python 3.4.0 (default, Apr 11 2014, 13:05:11)
>>> class Person():
... name = 'Victor'
... def say(self, what):
... print(self.name, what)
...
>>> getattr(Person, 'name')
'Victor'
>>> attr_name = 'name'
>>> person = Person()
>>> getattr(person, attr_name)
'Victor'
>>> getattr(person, 'say')('Hello')
Victor Hello
getattr
will raise AttributeError
if attribute with the given name does not exist in the object:
>>> getattr(person, 'age')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: 'Person' object has no attribute 'age'
But you can pass a default value as the third argument, which will be returned if such attribute does not exist:
>>> getattr(person, 'age', 0)
0
You can use getattr
along with dir
to iterate over all attribute names and get their values:
>>> dir(1000)
['__abs__', '__add__', ..., '__trunc__', '__xor__', 'bit_length', 'conjugate', 'denominator', 'from_bytes', 'imag', 'numerator', 'real', 'to_bytes']
>>> obj = 1000
>>> for attr_name in dir(obj):
... attr_value = getattr(obj, attr_name)
... print(attr_name, attr_value, callable(attr_value))
...
__abs__ <method-wrapper '__abs__' of int object at 0x7f4e927c2f90> True
...
bit_length <built-in method bit_length of int object at 0x7f4e927c2f90> True
...
>>> getattr(1000, 'bit_length')()
10
A practical use for this would be to find all methods whose names start with test
and call them.
Similar to getattr
there is setattr
which allows you to set an attribute of an object having its name:
>>> setattr(person, 'name', 'Andrew')
>>> person.name # accessing instance attribute
'Andrew'
>>> Person.name # accessing class attribute
'Victor'
>>>
val - Immutable(once initialized can't be reassigned)
var - Mutable(can able to change value)
Example
in Kotlin - val n = 20 & var n = 20
In Java - final int n = 20; & int n = 20;
In this case, random is actually pseudo-random. Given a seed, it will generate numbers with an equal distribution. But with the same seed, it will generate the same number sequence every time. If you want it to change, you'll have to change your seed. A lot of people like to generate a seed based on the current time or something.
If you don't have Homebrew or don't know what is it
/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
brew update && brew upgrade
brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
Or if you already have Homebrew installed
brew update && brew upgrade
brew uninstall openssl; brew uninstall openssl; brew install https://github.com/tebelorg/Tump/releases/download/v1.0.0/openssl.rb
This works for me on Mac 10.15
Use List.Insert(0, ...)
. But are you sure a LinkedList
isn't a better fit? Each time you insert an item into an array at a position other than the array end, all existing items will have to be copied to make space for the new one.
To hide the arrow:
input::-webkit-calendar-picker-indicator{
display: none;
}
And to hide the prompt:
input[type="date"]::-webkit-input-placeholder{
visibility: hidden !important;
}
You didn't mention how your backup was made, so the generic answer is: Usually with the psql
tool.
Depending on what pg_dump
was instructed to dump, the SQL file can have different sets of SQL commands.
For example, if you instruct pg_dump
to dump a database using --clean
and --schema-only
, you can't expect to be able to restore the database from that dump as there will be no SQL commands for COPYing (or INSERTing if --inserts
is used ) the actual data in the tables. A dump like that will contain only DDL SQL commands, and will be able to recreate the schema but not the actual data.
A typical SQL dump is restored with psql
:
psql (connection options here) database < yourbackup.sql
or alternatively from a psql
session,
psql (connection options here) database
database=# \i /path/to/yourbackup.sql
In the case of backups made with pg_dump -Fc
("custom format"), which is not a plain SQL file but a compressed file, you need to use the pg_restore
tool.
If you're working on a unix-like, try this:
man psql
man pg_dump
man pg_restore
otherwise, take a look at the html docs. Good luck!
//best way to deal with this is sqlbulkcopy
//but if you dont like it you can do it like this
//read current sql table in an adapter
//add rows of datatable , I have mentioned a simple way of it
//and finally updating changes
Dim cnn As New SqlConnection("connection string")
cnn.Open()
Dim cmd As New SqlCommand("select * from sql_server_table", cnn)
Dim da As New SqlDataAdapter(cmd)
Dim ds As New DataSet()
da.Fill(ds, "sql_server_table")
Dim cb As New SqlCommandBuilder(da)
//for each datatable row
ds.Tables("sql_server_table").Rows.Add(COl1, COl2)
da.Update(ds, "sql_server_table")
When importing your project/module be sure to check these two boxes:
In my case I had to remove React Dev Tools from Chrome to stop seeing the strange errors during development of React app using a local Express server with a create-react-app client (which uses Webpack). In the interest of community I did a sanity check and quit everything - server/client server/Chrome - and then I opened Chrome and reinstalled React Dev Tools... Started things back up and am seeing this funky address and error again:
Let me offer another solution. If you have just installed Git 1.8.2.2 or thereabouts, and you want to enable SSH, follow the well-writen directions.
Everything through to Step 5.6 where you might encounter a slight snag. If an SSH agent is already be running you could get the following error message when you restart bash
Could not open a connection to your authentication agent
If you do, use the following command to see if more than one ssh-agent process is running
ps aux | grep ssh
If you see more than one ssh-agent service, you will need to kill all of these processes. Use the kill command as follows (the PID will be unique on your computer)
kill <PID>
Example:
kill 1074
After you have removed all of the ssh-agent processes, run the px aux | grep ssh command again to be sure they are gone, then restart Bash.
Voila, you should now get something like this:
Initializing new SSH agent...
succeeded
Enter passphrase for /c/Users/username/.ssh/id_rsa:
Now you can continue on Step 5.7 and beyond.
Super key is the combination of fields by which the row is uniquely identified and the candidate key is the minimal super key.
You can convert CSV string to Array with this function.
function csv2array(
$csv_string,
$delimiter = ",",
$skip_empty_lines = true,
$trim_fields = true,
$FirstLineTitle = false
) {
$arr = array_map(
function ( $line ) use ( &$result, &$FirstLine, $delimiter, $trim_fields, $FirstLineTitle ) {
if ($FirstLineTitle && !$FirstLine) {
$FirstLine = explode( $delimiter, $result[0] );
}
$lineResult = array_map(
function ( $field ) {
return str_replace( '!!Q!!', '"', utf8_decode( urldecode( $field ) ) );
},
$trim_fields ? array_map( 'trim', explode( $delimiter, $line ) ) : explode( $delimiter, $line )
);
return $FirstLineTitle ? array_combine( $FirstLine, $lineResult ) : $lineResult;
},
($result = preg_split(
$skip_empty_lines ? ( $trim_fields ? '/( *\R)+/s' : '/\R+/s' ) : '/\R/s',
preg_replace_callback(
'/"(.*?)"/s',
function ( $field ) {
return urlencode( utf8_encode( $field[1] ) );
},
$enc = preg_replace( '/(?<!")""/', '!!Q!!', $csv_string )
)
))
);
return $FirstLineTitle ? array_splice($arr, 1) : $arr;
}
If you have ruby on your system, how about a small Ruby Proxy using Sinatra (make sure to install the Sinatra Gem). This should be easier than setting up apache. The code can be found here.
In my experience all the files which i have downloaded from internet,gmail
are stored in
/sdcard/download
on ics
/sdcard/Download
You can access it using
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS);
This solution will work until CSS4 is globally supported by all browsers. When that day comes just use CSS4. but until then, this works for current browsers.
browser-util.js
export const isMobile = {
android: () => navigator.userAgent.match(/Android/i),
blackberry: () => navigator.userAgent.match(/BlackBerry/i),
ios: () => navigator.userAgent.match(/iPhone|iPad|iPod/i),
opera: () => navigator.userAgent.match(/Opera Mini/i),
windows: () => navigator.userAgent.match(/IEMobile/i),
any: () => (isMobile.android() || isMobile.blackberry() ||
isMobile.ios() || isMobile.opera() || isMobile.windows())
};
onload:
old way:
isMobile.any() ? document.getElementsByTagName("body")[0].className += 'is-touch' : null;
newer way:
isMobile.any() ? document.body.classList.add('is-touch') : null;
The above code will add the "is-touch" class to the body tag if the device has a touch screen. Now any location in your web application where you would have css for :hover you can call body:not(.is-touch) the_rest_of_my_css:hover
for example:
button:hover
becomes:
body:not(.is-touch) button:hover
This solution avoids using modernizer as the modernizer lib is a very big library. If all you're trying to do is detect touch screens, This will be best when the size of the final compiled source is a requirement.
If you change from using a lambda with one argument to a function with one argument, you will get this error.
For example:
You had:
foobar = lambda do |baz|
puts baz
end
and you changed the definition to
def foobar(baz)
puts baz
end
And you left your invocation as:
foobar.call(baz)
And then you got the message
ArgumentError: wrong number of arguments (0 for 1)
when you really meant:
foobar(baz)
A while
loop can be simulated in cmd.exe
with:
:still_more_files
if %countfiles% leq 21 (
rem change countfile here
goto :still_more_files
)
For example, the following script:
@echo off
setlocal enableextensions enabledelayedexpansion
set /a "x = 0"
:more_to_process
if %x% leq 5 (
echo %x%
set /a "x = x + 1"
goto :more_to_process
)
endlocal
outputs:
0
1
2
3
4
5
For your particular case, I would start with the following. Your initial description was a little confusing. I'm assuming you want to delete files in that directory until there's 20 or less:
@echo off
set backupdir=c:\test
:more_files_to_process
for /f %%x in ('dir %backupdir% /b ^| find /v /c "::"') do set num=%%x
if %num% gtr 20 (
cscript /nologo c:\deletefile.vbs %backupdir%
goto :more_files_to_process
)
Swift 3
If you add a tag to your view you can remove a specific view.
for v in (view?.subviews)!
{
if v.tag == 321
{
v.removeFromSuperview()
}
}
Try this:
this.getSupportActionBar().hide();
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try
{
this.getSupportActionBar().hide();
}
catch (NullPointerException e){}
setContentView(R.layout.activity_main);
}
Clearly the parent directory is given by simply appending the dot-dot filename:
/home/smith/Desktop/Test/.. # unresolved path
But you must want the resolved path (an absolute path without any dot-dot path components):
/home/smith/Desktop # resolved path
The problem with the top answers that use dirname
, is that they don't work when you enter a path with dot-dots:
$ dir=~/Library/../Desktop/../..
$ parentdir="$(dirname "$dir")"
$ echo $parentdir
/Users/username/Library/../Desktop/.. # not fully resolved
This is more powerful:
dir=/home/smith/Desktop/Test
parentdir=$(builtin cd $dir; pwd)
You can feed it /home/smith/Desktop/Test/..
, but also more complex paths like:
$ dir=~/Library/../Desktop/../..
$ parentdir=$(builtin cd $dir; pwd)
$ echo $parentdir
/Users # the fully resolved path!
NOTE: use of builtin
ensures no user defined function variant of cd
is called, but rather the default utility form which has no output.
Yes, just delete the branch by running git push origin :branchname
. To fix a new issue later, branch off from master again.
1. First should understand the error meaning
Error not enough values to unpack (expected 3, got 2)
means:
a 2 part tuple, but assign to 3 values
and I have written demo code to show for you:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Function: Showing how to understand ValueError 'not enough values to unpack (expected 3, got 2)'
# Author: Crifan Li
# Update: 20191212
def notEnoughUnpack():
"""Showing how to understand python error `not enough values to unpack (expected 3, got 2)`"""
# a dict, which single key's value is two part tuple
valueIsTwoPartTupleDict = {
"name1": ("lastname1", "email1"),
"name2": ("lastname2", "email2"),
}
# Test case 1: got value from key
gotLastname, gotEmail = valueIsTwoPartTupleDict["name1"] # OK
print("gotLastname=%s, gotEmail=%s" % (gotLastname, gotEmail))
# gotLastname, gotEmail, gotOtherSomeValue = valueIsTwoPartTupleDict["name1"] # -> ValueError not enough values to unpack (expected 3, got 2)
# Test case 2: got from dict.items()
for eachKey, eachValues in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValues=%s" % (eachKey, eachValues))
# same as following:
# Background knowledge: each of dict.items() return (key, values)
# here above eachValues is a tuple of two parts
for eachKey, (eachValuePart1, eachValuePart2) in valueIsTwoPartTupleDict.items():
print("eachKey=%s, eachValuePart1=%s, eachValuePart2=%s" % (eachKey, eachValuePart1, eachValuePart2))
# but following:
for eachKey, (eachValuePart1, eachValuePart2, eachValuePart3) in valueIsTwoPartTupleDict.items(): # will -> ValueError not enough values to unpack (expected 3, got 2)
pass
if __name__ == "__main__":
notEnoughUnpack()
using VSCode
debug effect:
2. For your code
for name, email, lastname in unpaidMembers.items():
but error
ValueError: not enough values to unpack (expected 3, got 2)
means each item(a tuple value) in unpaidMembers
, only have 1 parts:email
, which corresponding above code
unpaidMembers[name] = email
so should change code to:
for name, email in unpaidMembers.items():
to avoid error.
But obviously you expect extra lastname
, so should change your above code to
unpaidMembers[name] = (email, lastname)
and better change to better syntax:
for name, (email, lastname) in unpaidMembers.items():
then everything is OK and clear.
I found myself needing the same thing for a recent project. Building on Levi's solution, here's a cleaner and faster method:
Rack::Utils.parse_nested_query 'param1=value1¶m2=value2¶m3=value3'
# => {"param1"=>"value1", "param2"=>"value2", "param3"=>"value3"}
As of Select2 4.1, they've removed support for .enable
$("select").prop("disabled", true); // instead of $("select").enable(false);
My EAR project had 2 modules *.ear and *.war and I got this dependency error on *.war
project when trying mvn eclipse:eclipse
. Resolved it by fixing utf-8 encoding issue in the *.war
project. mvn
-X
or -e
options weren't of help here.
Make sure that you are importing the correct BuildConfig class And yes, you will have no problems using:
if (BuildConfig.DEBUG) {
//It's not a release version.
}
For starters ignore all answers with tell you to use $watch. Angular works off of a listener already. I guarantee you that you are complicating things by merely thinking in this direction.
Ignore all answers that tell you to user $timeout. You cannot know how long the page will take to load, therefore this is not the best solution.
You only need to know when the page is done rendering.
<div ng-app='myApp'>
<div ng-controller="testctrl">
<label>{{total}}</label>
<table>
<tr ng-repeat="item in items track by $index;" ng-init="end($index);">
<td>{{item.number}}</td>
</tr>
</table>
</div>
var app = angular.module('myApp', ["testctrl"]);
var controllers = angular.module("testctrl", []);
controllers.controller("testctrl", function($scope) {
$scope.items = [{"number":"one"},{"number":"two"},{"number":"three"}];
$scope.end = function(index){
if(index == $scope.items.length -1
&& typeof $scope.endThis == 'undefined'){
/// DO STUFF HERE
$scope.total = index + 1;
$scop.endThis = true;
}
}
});
Track the ng-repeat by $index and when the length of array equals the index stop the loop and do your logic.
Just to add to the other examples, there are inner(nested) classes that appear with the $
sign. For example:
public class Test {
private static void privateMethod() {
throw new RuntimeException();
}
public static void main(String[] args) throws Exception {
Runnable runnable = new Runnable() {
@Override public void run() {
privateMethod();
}
};
runnable.run();
}
}
Will result in this stack trace:
Exception in thread "main" java.lang.RuntimeException
at Test.privateMethod(Test.java:4)
at Test.access$000(Test.java:1)
at Test$1.run(Test.java:10)
at Test.main(Test.java:13)
A simple solution.
l = [1, 2, 3, 4, 5, 6] for i in range(0, len(l), 2): print str(l[i]), '+', str(l[i + 1]), '=', str(l[i] + l[i + 1])
I really wanted to comment, not answer. But just to be precise, OSX is not based on BSD, it is an evolution of NeXTStep. The NeXTStep OS utilizes the Mach kernel developed by CMU. It was originally designed as a MicroKernel, but due to performance constraints, they eventually decided they needed to include the Unix portion of the API into the kernel itself and so a BSD-compatible "server" (originally intended to process requests for BSD-compatible kernel messages) was moved into the kernel, making it a Monolithic kernel. It may be BSD compatible in the programming API, but it is NOT BSD.
The rest of the OS involved ObjectiveC (under arrangements between Stepstone and Richard Stallman of GNU/GCC) with a GUI based on a technology called "Display Postscript" ... sort of like an X Server, but with postscript commands. OS X changed Display Postscript to Display PDF, and increased the general hardware requirements 1000 fold (NeXT could run in 8-16MB, now you need GB).
Due to the close marriage of GCC and Objective C and NeXT, your best bet at running XCode natively under Linux would be to do a port (if you can get ahold of the source - good luck) utilizing the GNUStep libraries. Originally designed for NextStep and then OpenStep compatibility, I've heard they are now more-or-less Cocoa compatible, but I've not played with any of it in almost 2 decades. Of course that only gets you as far as ObjC, not Swift, and I don't know if Apple is going to OpenSource it.
Have you thought about using mouseOver and mouseOut to simulate this. Also look into mouseEnter and mouseLeave
$ git --version
git version 1.7.3.4
git help
and man git
both hint at the available arguments you can pass to the command-line tool
Let's assume you have the following simple filter, which converts a string to uppercase, with a parameter for the first character only.
app.filter('uppercase', function() {
return function(string, firstCharOnly) {
return (!firstCharOnly)
? string.toUpperCase()
: string.charAt(0).toUpperCase() + string.slice(1);
}
});
Directly through $filter
app.controller('MyController', function($filter) {
// HELLO
var text = $filter('uppercase')('hello');
// Hello
var text = $filter('uppercase')('hello', true);
});
Note: this gives you access to all your filters.
Assign $filter
to a variable
This option allows you to use the $filter
like a function
.
app.controller('MyController', function($filter) {
var uppercaseFilter = $filter('uppercase');
// HELLO
var text = uppercaseFilter('hello');
// Hello
var text = uppercaseFilter('hello', true);
});
Load only a specific Filter
You can load only a specific filter by appending the filter name with Filter
.
app.controller('MyController', function(uppercaseFilter) {
// HELLO
var text = uppercaseFilter('hello');
// Hello
var text = uppercaseFilter('hello', true);
});
Which one you use comes to personal preference, but I recommend using the third, because it's the most readable option.
Without getting into the code first, the logic/algorithm goes below:
Go to the transaction
table with multiple records for the same client
.
Select records of clientID
and the latestDate
of client's activity using group by clientID
and max(transactionDate)
select clientID, max(transactionDate) as latestDate
from transaction
group by clientID
inner join
the transaction
table with the outcome from Step 2, then you will have the full records of the transaction
table with only each client's latest record.
select * from
transaction t
inner join (
select clientID, max(transactionDate) as latestDate
from transaction
group by clientID) d
on t.clientID = d.clientID and t.transactionDate = d.latestDate)
You can use the result from step 3 to join any table you want to get different results.
You can use the USER root command in your Dockerfile.
None of the answers posted here worked for me. Here is what did work:
java.nio.file.Paths.get(
getClass().getProtectionDomain().getCodeSource().getLocation().toURI()
);
Edit: The final version in my code:
URL myURL = getClass().getProtectionDomain().getCodeSource().getLocation();
java.net.URI myURI = null;
try {
myURI = myURL.toURI();
} catch (URISyntaxException e1)
{}
return java.nio.file.Paths.get(myURI).toFile().toString()
What we have in our table:-
Primary Key
Event type (e.g. "UPDATED", "APPROVED")
Description ("Frisbar was added to blong")
User Id
User Id of second authoriser
Amount
Date/time
Generic Id
Table Name
The generic id points at a row in the table that was updated and the table name is the name of that table as a string. Not a good DB design, but very usable. All our tables have a single surrogate key column so this works well.
Simple: enum names into a List:
List<String> NameList = Enum.GetNames(typeof(YourEnumName)).Cast<string>().ToList()
There's a nice workaround for this in the sitepoint forums:
<div onclick="this.nextElementSibling.style.display='block'; this.style.display='none'">
<img src="my_thumbnail.png" style="cursor:pointer" />
</div>
<div style="display:none">
<!-- Embed code here -->
</div>
Note: To prevent having to click twice to make the video play, use autoplay=1
in the video embed code. It will start playing when the second div is displayed.
1. Create a class
public class Test {
public static void main(String[] args) {
// TODO Auto-generated method stub
String s[] = {"app","amm","abb","akk","all"};
doForAllTabs(s);
}
public static void doForAllTabs(String[] tablist){
for(int i = 0; i<tablist.length;i++){
System.out.println(tablist[i]);
}
}
}
2. Right click on left side of System.out.println(tablist[i]); in Eclipse --> select Toggle Breakpoint
3. Right click on toggle point --> select Breakpoint properties
4. Check the Conditional Check Box --> write tablist[i].equalsIgnoreCase("amm") in text field --> Click on OK
5. Right click on class --> Debug As --> Java Application
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
Yes, \
in Python string literals denotes the start of an escape sequence. In your path you have a valid two-character escape sequence \a
, which is collapsed into one character that is ASCII Bell:
>>> '\a'
'\x07'
>>> len('\a')
1
>>> 'C:\meshes\as'
'C:\\meshes\x07s'
>>> print('C:\meshes\as')
C:\meshess
Other common escape sequences include \t
(tab), \n
(line feed), \r
(carriage return):
>>> list('C:\test')
['C', ':', '\t', 'e', 's', 't']
>>> list('C:\nest')
['C', ':', '\n', 'e', 's', 't']
>>> list('C:\rest')
['C', ':', '\r', 'e', 's', 't']
As you can see, in all these examples the backslash and the next character in the literal were grouped together to form a single character in the final string. The full list of Python's escape sequences is here.
There are a variety of ways to deal with that:
Python will not process escape sequences in string literals prefixed with r
or R
:
>>> r'C:\meshes\as'
'C:\\meshes\\as'
>>> print(r'C:\meshes\as')
C:\meshes\as
Python on Windows should handle forward slashes, too.
You could use os.path.join
...
>>> import os
>>> os.path.join('C:', os.sep, 'meshes', 'as')
'C:\\meshes\\as'
... or the newer pathlib
module
>>> from pathlib import Path
>>> Path('C:', '/', 'meshes', 'as')
WindowsPath('C:/meshes/as')
By using @ModelAttribute we can pass the model from one controller to another controller
[ Input to the first Controller][1]
[]: https://i.stack.imgur.com/rZQe5.jpg from jsp page first controller binds the form data with the @ModelAttribute to the User Bean
@Controller
public class FirstController {
@RequestMapping("/fowardModel")
public ModelAndView forwardModel(@ModelAttribute("user") User u) {
ModelAndView m = new ModelAndView("forward:/catchUser");
m.addObject("usr", u);
return m;
}
}
@Controller
public class SecondController {
@RequestMapping("/catchUser")
public ModelAndView catchModel(@ModelAttribute("user") User u) {
System.out.println(u); //retrive the data passed by the first contoller
ModelAndView mv = new ModelAndView("userDetails");
return mv;
}
}
This is the cleanest solution for me
import { Component, OnInit } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
export class MyComponent {
constructor(
private route: ActivatedRoute
) {}
ngOnInit() {
const firstParam: string = this.route.snapshot.queryParamMap.get('firstParamKey');
const secondParam: string = this.route.snapshot.queryParamMap.get('secondParamKey');
}
}
In my case, it was unable to find the .eslintrc
file so I copied from node_modules/.bin to root.
Here's another dodge that I came up with for my base repository class where I needed to order by an arbitrary number of columns:
public function findAll(array $where = [], array $with = [], array $orderBy = [], int $limit = 10)
{
$result = $this->model->with($with);
$dataSet = $result->where($where)
// Conditionally use $orderBy if not empty
->when(!empty($orderBy), function ($query) use ($orderBy) {
// Break $orderBy into pairs
$pairs = array_chunk($orderBy, 2);
// Iterate over the pairs
foreach ($pairs as $pair) {
// Use the 'splat' to turn the pair into two arguments
$query->orderBy(...$pair);
}
})
->paginate($limit)
->appends(Input::except('page'));
return $dataSet;
}
Now, you can make your call like this:
$allUsers = $userRepository->findAll([], [], ['name', 'DESC', 'email', 'ASC'], 100);
I found this related question: Directory Listing in S3 Static Website
As it turns out, if you enable public read for the whole bucket, S3 can serve directory listings. Problem is they are in XML instead of HTML, so not very user-friendly.
There are three ways you could go for generating listings:
Generate index.html files for each directory on your own computer, upload them to s3, and update them whenever you add new files to a directory. Very low-tech. Since you're saying you're uploading build files straight from Travis, this may not be that practical since it would require doing extra work there.
Use a client-side S3 browser tool.
Use a server-side browser tool.
You can loop through the keys:
foo = {one:1, two:2, three:3};
for (key in foo){
console.log("foo["+ key +"]="+ foo[key]);
}
will output:
foo[one]=1
foo[two]=2
foo[three]=3
This memory technic helps me a lot:
[ <RETURNED_VALUE> <OUTER_LOOP1> <INNER_LOOP2> <INNER_LOOP3> ... <OPTIONAL_IF> ]
And now you can think about Return + Outer-loop as the only Right Order
Knowing above, the order in list comprehensive even for 3 loops seem easy:
c=[111, 222, 333]
b=[11, 22, 33]
a=[1, 2, 3]
print(
[
(i, j, k) # <RETURNED_VALUE>
for i in a for j in b for k in c # in order: loop1, loop2, loop3
if i < 2 and j < 20 and k < 200 # <OPTIONAL_IF>
]
)
[(1, 11, 111)]
because the above is just a:
for i in a: # outer loop1 GOES SECOND
for j in b: # inner loop2 GOES THIRD
for k in c: # inner loop3 GOES FOURTH
if i < 2 and j < 20 and k < 200:
print((i, j, k)) # returned value GOES FIRST
for iterating one nested list/structure, technic is the same:
for a
from the question:
a = [[1,2],[3,4]]
[i2 for i1 in a for i2 in i1]
which return [1, 2, 3, 4]
for one another nested level
a = [[[1, 2], [3, 4]], [[5, 6], [7, 8, 9]], [[10]]]
[i3 for i1 in a for i2 in i1 for i3 in i2]
which return [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
and so on
Well, this solution will help you select only current month, current week and only today
SELECT * FROM games WHERE games.published_gm = 1 AND YEAR(addedon_gm) = YEAR(NOW()) AND MONTH(addedon_gm) = MONTH(NOW()) AND DAY(addedon_gm) = DAY(NOW()) ORDER BY addedon_gm DESC;
For Weekly added posts:
WEEKOFYEAR(addedon_gm) = WEEKOFYEAR(NOW())
For Monthly added posts:
MONTH(addedon_gm) = MONTH(NOW())
For Yearly added posts:
YEAR(addedon_gm) = YEAR(NOW())
you'll get the accurate results where show only the games added today, otherwise you may display: "No New Games Found For Today". Using ShowIF recordset is empty transaction.
Update PHP 7.4
Curly brace access syntax is deprecated since PHP 7.4
Update 2019
Moving on to the best practices of OOPS, @MrTrick's answer must be marked as correct, although my answer provides a hacked solution its not the best method.
Simply iterate its using {}
Example:
$videos{0}->id
This way your object is not destroyed and you can easily iterate through object.
For PHP 5.6 and below use this
$videos{0}['id']
Both array() and the stdClass objects can be accessed using the
current()
key()
next()
prev()
reset()
end()
functions.
So, if your object looks like
object(stdClass)#19 (3) {
[0]=>
object(stdClass)#20 (22) {
["id"]=>
string(1) "123"
etc...
Then you can just do;
$id = reset($obj)->id; //Gets the 'id' attr of the first entry in the object
If you need the key for some reason, you can do;
reset($obj); //Ensure that we're at the first element
$key = key($obj);
Hope that works for you. :-) No errors, even in super-strict mode, on PHP 5.4
2022 Update:
After PHP 7.4, using current()
, end()
, etc functions on objects is deprecated.
In newer versions of PHP, use the ArrayIterator class:
$objIterator = new ArrayIterator($obj);
$id = $objIterator->current()->id; // Gets the 'id' attr of the first entry in the object
$key = $objIterator->key(); // and gets the key
Safety check to only select if an item is matched.
//try to find item in list.
ListItem oItem = DDL.Items.FindByValue("PassedValue"));
//if exists, select it.
if (oItem != null) oItem.Selected = true;
So, it turns out that X11 wasn't actually installed on the centOS. There didn't seem to be any indication anywhere of it not being installed. I did the following command and now firefox opens:
yum groupinstall 'X Window System'
Hope this answer will help others that are confused :)
You cannot "convert" an existing column into an IDENTITY
column - you will have to create a new column as INT IDENTITY
:
ALTER TABLE ProductInProduct
ADD NewId INT IDENTITY (1, 1);
Update:
OK, so there is a way of converting an existing column to IDENTITY
. If you absolutely need this - check out this response by Martin Smith with all the gory details.
Here you can use following code as a function:
def drawProgressBar(percent, barLen = 20):
sys.stdout.write("\r")
progress = ""
for i in range(barLen):
if i < int(barLen * percent):
progress += "="
else:
progress += " "
sys.stdout.write("[ %s ] %.2f%%" % (progress, percent * 100))
sys.stdout.flush()
With use of .format:
def drawProgressBar(percent, barLen = 20):
# percent float from 0 to 1.
sys.stdout.write("\r")
sys.stdout.write("[{:<{}}] {:.0f}%".format("=" * int(barLen * percent), barLen, percent * 100))
sys.stdout.flush()
brew install imagemagick
Don't forget to install also gs
which is a dependency if you want to convert pdf to images for example :
brew install ghostscript
select *
from blah
where DatetimeField between '22/02/2009 09:00:00.000' and '23/05/2009 10:30:00.000'
Depending on the country setting for the login, the month/day may need to be swapped around.
As another person posted this can be caused by saving the project on a network share. I found that if I switched from using a network path to a mapped network drive everything worked fine.
from: "\\SERVER\Programming\SolutionFolder"
to: "Z:\Programming\SolutionFolder" (exact mapping optional)
It should be this:
if (myString!="-1")
{
//Do things
}
Your equals and exclamation are the wrong way round.
Tested on a Huawei P20:
Reinstall Google Play: (Source)
Restart device.
Note: before finding this solution, I followed the instructions from some of the other answers here: removed my Google account from my device and added it again, cleared data and cache from various google play apps. This may or may not be necessary; feedback is welcome.
SELECT * FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Update : for better performance and faster query its good to add e1
before *
SELECT e1.* FROM employees e1, employees e2
WHERE e1.phoneNumber = e2.phoneNumber
AND e1.id != e2.id;
Hello was looking for the same, and it could be also
unlist(lapply(mtcars,class))
Here is a picture that shows the difference between add()
and replace()
So add()
method keeps on adding fragments on top of the previous fragment in FragmentContainer.
While replace()
methods clears all the previous Fragment from Containers and then add it in FragmentContainer.
What is addToBackStack
addtoBackStack
method can be used with add() and replace methods. It serves a different purpose in Fragment API.
What is the purpose?
Fragment API unlike Activity API does not come with Back Button navigation by default. If you want to go back to the previous Fragment then the we use addToBackStack() method in Fragment. Let's understand both
Case 1:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.addToBackStack("TAG")
.commit();
Case 2:
getSupportFragmentManager()
.beginTransaction()
.add(R.id.fragmentContainer, fragment, "TAG")
.commit();
if (list.Count > desiredIndex && list[desiredIndex] != null)
{
// logic
}
@user2302510 solution works not as good as you may expected. Full workaround for both orientations and dynamically data changes is:
public class MyLinearLayoutManager extends LinearLayoutManager {
public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
private int[] mMeasuredDimension = new int[2];
@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
int widthSpec, int heightSpec) {
final int widthMode = View.MeasureSpec.getMode(widthSpec);
final int heightMode = View.MeasureSpec.getMode(heightSpec);
final int widthSize = View.MeasureSpec.getSize(widthSpec);
final int heightSize = View.MeasureSpec.getSize(heightSpec);
int width = 0;
int height = 0;
for (int i = 0; i < getItemCount(); i++) {
measureScrapChild(recycler, i,
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
View.MeasureSpec.makeMeasureSpec(i, View.MeasureSpec.UNSPECIFIED),
mMeasuredDimension);
if (getOrientation() == HORIZONTAL) {
width = width + mMeasuredDimension[0];
if (i == 0) {
height = mMeasuredDimension[1];
}
} else {
height = height + mMeasuredDimension[1];
if (i == 0) {
width = mMeasuredDimension[0];
}
}
}
switch (widthMode) {
case View.MeasureSpec.EXACTLY:
width = widthSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
switch (heightMode) {
case View.MeasureSpec.EXACTLY:
height = heightSize;
case View.MeasureSpec.AT_MOST:
case View.MeasureSpec.UNSPECIFIED:
}
setMeasuredDimension(width, height);
}
private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
int heightSpec, int[] measuredDimension) {
View view = recycler.getViewForPosition(position);
if (view != null) {
RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
getPaddingLeft() + getPaddingRight(), p.width);
int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
getPaddingTop() + getPaddingBottom(), p.height);
view.measure(childWidthSpec, childHeightSpec);
measuredDimension[0] = view.getMeasuredWidth() + p.leftMargin + p.rightMargin;
measuredDimension[1] = view.getMeasuredHeight() + p.bottomMargin + p.topMargin;
recycler.recycleView(view);
}
}
}
Try to replace the
padding: 2px 30px 2px 2px;
with
padding: 2px 2px 2px 2px;
It should work.
Now Android provides ViewModels for saving state, you should try to use that instead of saveInstanceState.
You can use postgresql Cursors
BEGIN;
DECLARE C CURSOR FOR where * FROM msgtable where cdate='18/07/2012';
Then use
FETCH 10 FROM C;
to fetch 10 rows.
Finnish with
COMMIT;
to close the cursor.
But if you need to make a query in different processes, LIMIT and OFFSET as suggested by @Praveen Kumar is better
The simplest answer is what Paul H said:
d = []
for p in game.players.passing():
d.append(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
pd.DataFrame(d)
But if you really want to "build and fill a dataframe from a loop", (which, btw, I wouldn't recommend), here's how you'd do it.
d = pd.DataFrame()
for p in game.players.passing():
temp = pd.DataFrame(
{
'Player': p,
'Team': p.team,
'Passer Rating': p.passer_rating()
}
)
d = pd.concat([d, temp])
print('<tr><td>%04d</td>' % (i+1), file=Html_file)
yourstring = '#Please send_an_information_pack_to_the_following_address:';
replace '#' with '' and replace '_' with a space
var newstring1 = yourstring.split('#').join('');
var newstring2 = newstring1.split('_').join(' ');
newstring2 is your result
Varies... One such example would be an anonymous classes (you'll encounter those alot when using event listeners and such).
//assuming you have a map called 'map'
var infowindow = new google.maps.InfoWindow();
var latlng1 = new google.maps.LatLng(0,0);
var marker1 = new google.maps.Marker({position:latlng1, map:map});
google.maps.event.addListener(marker1, 'click',
function(){
infowindow.close();//hide the infowindow
infowindow.setContent('Marker #1');//update the content for this marker
infowindow.open(map, marker1);//"move" the info window to the clicked marker and open it
}
);
var latlng2 = new google.maps.LatLng(10,10);
var marker2 = new google.maps.Marker({position:latlng2, map:map});
google.maps.event.addListener(marker2, 'click',
function(){
infowindow.close();//hide the infowindow
infowindow.setContent('Marker #2');//update the content for this marker
infowindow.open(map, marker2);//"move" the info window to the clicked marker and open it
}
);
This will "move" the info window around to each clicked marker, in effect closing itself, then reopening (and panning to fit the viewport) in its new location. It changes its contents before opening to give the desired effect. Works for n markers.
I would like to present another answer to this as the currently accepted answer doesn't work for me (I use LibreOffice). This solution should work in Excel, LibreOffice and OpenOffice:
First, insert a new row at the beginning of the sheet. Within that row, define the names you need:
Then, in the menu bar, go to View -> Freeze Cells -> Freeze First Row. It'll look like this now:
Now whenever you scroll down in the document, the first row will be "pinned" to the top:
You can do a couple of things to troubleshoot this issue. First, use Windows file search to search your hard drive for your assembly (.dll). Once you have a list of results, do View->Choose Details... and then check "File Version". This will display the version number in the list of results, so you can see where the old version might be coming from.
Also, like Lars said, check your GAC to see what version is listed there. This Microsoft article states that assemblies found in the GAC are not copied locally during a build, so you might need to remove the old version before doing a rebuild all. (See my answer to this question for notes on creating a batch file to do this for you)
If you still can't figure out where the old version is coming from, you can use the fuslogvw.exe application that ships with Visual Studio to get more information about the binding failures. Microsoft has information about this tool here. Note that you'll have to enable logging by setting the HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion\EnableLog
registry key to 1.
$ man tr
NAME
tr - translate or delete characters
SYNOPSIS
tr [OPTION]... SET1 [SET2]
DESCRIPTION
Translate, squeeze, and/or delete characters from standard
input, writing to standard output.
In order to wipe all whitespace including newlines you can try:
cat file.txt | tr -d " \t\n\r"
You can also use the character classes defined by tr (credits to htompkins comment):
cat file.txt | tr -d "[:space:]"
For example, in order to wipe just horizontal white space:
cat file.txt | tr -d "[:blank:]"
=(A1/86400)+25569
...and the format of the cell should be date.
#####
you probably don't have a real Unix time. Check your
timestamps in https://www.epochconverter.com/. Try to divide your input by 10, 100, 1000 or 10000**A1
with the cell containing the timestamp ;-pUnix system represent a point in time as a number. Specifically the number of seconds* since a zero-time called the Unix epoch which is 1/1/1970 00:00 UTC/GMT
. This number of seconds is called "Unix timestamp" or "Unix time" or "POSIX time" or just "timestamp" and sometimes (confusingly) "Unix epoch".
In the case of Excel they chose a different zero-time and step (because who wouldn't like variety in technical details?). So Excel counts days
since 24 hours before 1/1/0000 UTC/GMT
. So 25569 corresponds to 1/1/1970 00:00 UTC/GMT
and 25570 to 2/1/1970 00:00
.
Now please note that we have 86400 seconds per day (24 hours x60 minutes each x60 seconds) and you can understand what this formula does: A1/86400
converts seconds to days and +25569
adjusts for the offset between what is time-zero for Unix and what is time-zero for Excel.
By the way DATE(1970,1,1)
will helpfully return 25569 for you in case you forget all this so a more "self-documenting" way to write our formula is:
=A1/(24*60*60) + DATE(1970,1,1)
P.S.: All these were already present in other answers and comments just not laid out as I like them and I don't feel it's OK to edit the hell out of another answer.
*: that's almost correct because you should not count leap seconds
**: E.g. in the case of this question the number was number of milliseconds since the the Unix epoch.
You can use array_agg
function for that:
SELECT "Movie",
array_to_string(array_agg(distinct "Actor"),',') AS Actor
FROM Table1
GROUP BY "Movie";
Result:
MOVIE | ACTOR |
---|---|
A | 1,2,3 |
B | 4 |
See this SQLFiddle
For more See 9.18. Aggregate Functions
The following example executes a query as part of the Boolean expression and then executes slightly different statement blocks based on the result of the Boolean expression. Each statement block starts with BEGIN and completes with END.
USE AdventureWorks2012;
GO
DECLARE @AvgWeight decimal(8,2), @BikeCount int
IF
(SELECT COUNT(*) FROM Production.Product WHERE Name LIKE 'Touring-3000%' ) > 5
BEGIN
SET @BikeCount =
(SELECT COUNT(*)
FROM Production.Product
WHERE Name LIKE 'Touring-3000%');
SET @AvgWeight =
(SELECT AVG(Weight)
FROM Production.Product
WHERE Name LIKE 'Touring-3000%');
PRINT 'There are ' + CAST(@BikeCount AS varchar(3)) + ' Touring-3000 bikes.'
PRINT 'The average weight of the top 5 Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.';
END
ELSE
BEGIN
SET @AvgWeight =
(SELECT AVG(Weight)
FROM Production.Product
WHERE Name LIKE 'Touring-3000%' );
PRINT 'Average weight of the Touring-3000 bikes is ' + CAST(@AvgWeight AS varchar(8)) + '.' ;
END ;
GO
Using nested IF...ELSE statements The following example shows how an IF … ELSE statement can be nested inside another. Set the @Number variable to 5, 50, and 500 to test each statement.
DECLARE @Number int
SET @Number = 50
IF @Number > 100
PRINT 'The number is large.'
ELSE
BEGIN
IF @Number < 10
PRINT 'The number is small'
ELSE
PRINT 'The number is medium'
END ;
GO
If this is a Windows app, try checking for a duplicate in the Global Assembly Cache (GAC). Something is overriding your bin / debug version.
If this is a web app, you may need to delete on server and re-upload. If you are publishing you may want to check the Delete all existing files prior to publish check box. Depending on Visual Studio version it should be located in Publish > Settings > File Publish Options
You can solve this by using Data Transfer Objects (DTO's).
These are a bit like viewmodels where you put in the properties you need and you can map them manually in your controller or by using third-party solutions like AutoMapper.
With DTO's you can :
I've been learning this in school this year and it's a very useful tool.
here: http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.framework.adonet/2006-10/msg00064.html
You can read also that Thomas Weingartner wrote:
Timeout: SqlException.Number == -2 (This is an ADO.NET error code)
General Network Error: SqlException.Number == 11
Deadlock: SqlException.Number == 1205 (This is an SQL Server error code)
...
We handle the "General Network Error" as a timeout exception too. It only occurs under rare circumstances e.g. when your update/insert/delete query will raise a long running trigger.
I converted the pandas dataframe
to list
and then used the basic list.index()
. Something like this:
dd = list(zone[0]) #Where zone[0] is some specific column of the table
idx = dd.index(filename[i])
You have you index value as idx
.
Besides the other answers, it's also possible to use single line comments just before and after the JSX begines or ends. Here is a complete summary:
(
// this is a valid comment
<div>
...
</div>
// this is also a valid comment
/* this is also valid */
)
If we were to use comments inside the JSX rendering logic:
(
<div>
{/* <h1>Valid comment</h1> */}
</div>
)
When declaring props single line comments can be used:
(
<div
className="content" /* valid comment */
onClick={() => {}} // valid comment
>
...
</div>
)
When using single line or multiline comments inside the JSX without wrapping them in { }
, the comment will be rendered to the UI:
(
<div>
// invalid comment, renders in the UI
</div>
)
You may use this formula to get the path of the file:
=LEFT(CELL("filename"),FIND("[",CELL("filename"),1)-1)
This question's answer was posted so long ago and I stumbled upon it via a Google search. HTML5 provides the HTMLInputElement API that includes the setRangeText() method, which replaces a range of text in an <input>
or <textarea>
element with a new string:
element.setRangeText('abc');
The above would replace the selection made inside element
with abc
. You can also specify which part of the input value to replace:
element.setRangeText('abc', 3, 5);
The above would replace the 4th till 6th characters of the input value with abc
. You can also specify how the selection should be set after the text has been replaced by providing one of the following strings as the 4th parameter:
'preserve'
attempts to preserve the selection. This is the default.'select'
selects the newly inserted text.'start'
moves the selection to just before the inserted text.'end'
moves the selection to just after the inserted text.Browser compatibility
The MDN page for setRangeText doesn't provide browser compatibility data, but I guess it'd be the same as HTMLInputElement.setSelectionRange(), which is basically all modern browsers, IE 9 and above, Edge 12 and above.
Something like this would work
#!/bin/sh
if [ -fe FILE ]
then
rm FILE
fi
-f checks if it's a regular file
-e checks if the file exist
Introduction to if for more information
EDIT : -e used with -f is redundant, fo using -f alone should work too
With CSS properties, we can only control the thickness of border; not length.
However we can mimic border effect and control its width
and height
as we want with some other ways.
We can use linear-gradient()
to create a background image(s) and control its size and position with CSS so that it looks like a border. As we can apply multiple background images to an element, we can use this feature to create multiple border like images and apply on different sides of element. We can also cover the remaining available area with some solid color, gradient or background image.
Required HTML:
All we need is one element only (possibly having some class).
<div class="box"></div>
Steps:
linear-gradient()
.background-size
to adjust the width
/ height
of above created image(s) so that it looks like a border.background-position
to adjust position (like left
, right
, left bottom
etc.) of the above created border(s).Necessary CSS:
.box {
background-image: linear-gradient(purple, purple),
// Above css will create background image that looks like a border.
linear-gradient(steelblue, steelblue);
// This will create background image for the container.
background-repeat: no-repeat;
/* First sizing pair (4px 50%) will define the size of the border i.e border
will be of having 4px width and 50% height. */
/* 2nd pair will define the size of stretched background image. */
background-size: 4px 50%, calc(100% - 4px) 100%;
/* Similar to size, first pair will define the position of the border
and 2nd one for the container background */
background-position: left bottom, 4px 0;
}
Examples:
With linear-gradient()
we can create borders of solid color as well as having gradients. Below are some examples of border created with this method.
Example with border applied on one side only:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
background-image: linear-gradient(purple, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
background-repeat: no-repeat;_x000D_
background-size: 4px 50%, calc(100% - 4px) 100%;_x000D_
background-position: left bottom, 4px 0;_x000D_
_x000D_
height: 160px;_x000D_
width: 160px;_x000D_
margin: 20px;_x000D_
}_x000D_
.gradient-border {_x000D_
background-image: linear-gradient(red, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
_x000D_
<div class="box gradient-border"></div>_x000D_
</div>
_x000D_
Example with border applied on two sides:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
background-image: linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
background-repeat: no-repeat;_x000D_
background-size: 4px 50%, 4px 50%, calc(100% - 8px) 100%;_x000D_
background-position: left bottom, right top, 4px 0;_x000D_
_x000D_
height: 160px;_x000D_
width: 160px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.gradient-border {_x000D_
background-image: linear-gradient(red, purple),_x000D_
linear-gradient(purple, red),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
_x000D_
<div class="box gradient-border"></div>_x000D_
</div>
_x000D_
Example with border applied on all sides:
.container {_x000D_
display: flex;_x000D_
}_x000D_
.box {_x000D_
background-image: linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(purple, purple),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
background-repeat: no-repeat;_x000D_
background-size: 4px 50%, 50% 4px, 4px 50%, 50% 4px, calc(100% - 8px) calc(100% - 8px);_x000D_
background-position: left bottom, left bottom, right top, right top, 4px 4px;_x000D_
_x000D_
height: 160px;_x000D_
width: 160px;_x000D_
margin: 20px;_x000D_
}_x000D_
_x000D_
.gradient-border {_x000D_
background-image: linear-gradient(red, purple),_x000D_
linear-gradient(to right, purple, red),_x000D_
linear-gradient(to bottom, purple, red),_x000D_
linear-gradient(to left, purple, red),_x000D_
linear-gradient(steelblue, steelblue);_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="box"></div>_x000D_
_x000D_
<div class="box gradient-border"></div>_x000D_
</div>
_x000D_
Screenshot:
In similar case I used: white-space: nowrap;
I think that I also faced this problem, and the best solution I found was to look at my console and figure out the error that was being thrown. So, I read it carefully and found that the problem was that I didn't specify my repo, description, and valid name in my package.json
. I added those pieces of information and everything was okay.
Yes you can! For a simple repository that only publish/retrieve artifacts, you can use nginx.
Make sure nginx has http dav module enabled, it should, but nonetheless verify it.
Configure nginx http dav module:
In Windows: d:\servers\nginx\nginx.conf
location / {
# maven repository
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
In Linux (Ubuntu): /etc/nginx/sites-available/default
location / {
# First attempt to serve request as file, then
# as directory, then fall back to displaying a 404.
# try_files $uri $uri/ =404; # IMPORTANT comment this
dav_methods PUT DELETE MKCOL COPY MOVE;
create_full_put_path on;
dav_access user:rw group:rw all:r;
}
Don't forget to give permissions to the directory where the repo will be located:
sudo chmod +777 /var/www/html/repository
In your project's pom.xml
add the respective configuration:
Retrieve artifacts:
<repositories>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</repositories>
Publish artifacts:
<build>
<extensions>
<extension>
<groupId>org.apache.maven.wagon</groupId>
<artifactId>wagon-http</artifactId>
<version>3.2.0</version>
</extension>
</extensions>
</build>
<distributionManagement>
<repository>
<id>repository</id>
<url>http://<your.ip.or.hostname>/repository</url>
</repository>
</distributionManagement>
To publish artifacts use mvn deploy
. To retrieve artifacts, maven will do it automatically.
And there you have it a simple maven repo.
In pyspark 2.4.4
1) group_by_dataframe.count().filter("`count` >= 10").orderBy('count', ascending=False)
2) from pyspark.sql.functions import desc
group_by_dataframe.count().filter("`count` >= 10").orderBy('count').sort(desc('count'))
No need to import in 1) and 1) is short & easy to read,
So I prefer 1) over 2)
If your purpose is the isolation, I think Docker is what you want.
Vagrant is a virtual machine manager. It allows you to script the virtual machine configuration as well as the provisioning. However, it is still a virtual machine depending on VirtualBox (or others) with a huge overhead. It requires you to have a hard drive file that can be huge, it takes a lot of ram, and performance may be not very good.
Docker on the other hand uses kernel cgroup and namespacing via LXC. It means that you are using the same kernel as the host and the same file system.
You can use Dockerfile with the docker build
command in order to handle the provisioning and configuration of your container. You have an example at docs.docker.com on how to make your Dockerfile; it is very intuitive.
The only reason you could want to use Vagrant is if you need to do BSD, Windows or other non-Linux development on your Ubuntu box. Otherwise, go for Docker.
From the documentation:
It is necessary to keep in mind that the browsers do not know how to correctly show this error.
I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.
You can find your team id here:
https://developer.apple.com/account/#/membership
This will get you to your Membership Details, just scroll down to Team ID
You can use SUBSTRING
and CONVERT
:
SELECT stuff
FROM table
WHERE conditions
ORDER BY CONVERT(SUBSTRING(name_column, 6), SIGNED INTEGER);
Where name_column
is the column with the "name-" values. The SUBSTRING
removes everything up before the sixth character (i.e. the "name-" prefix) and then the CONVERT
converts the left over to a real integer.
UPDATE: Given the changing circumstances in the comments (i.e. the prefix can be anything), you'll have to throw a LOCATE
in the mix:
ORDER BY CONVERT(SUBSTRING(name_column, LOCATE('-', name_column) + 1), SIGNED INTEGER);
This of course assumes that the non-numeric prefix doesn't have any hyphens in it but the relevant comment says that:
name
can be any sequence of letters
so that should be a safe assumption.
Well, file_exists
does not say if a file exists, it says if a path exists. ???????
So, to check if it is a file then you should use is_file
together with file_exists
to know if there is really a file behind the path, otherwise file_exists
will return true
for any existing path.
Here is the function i use :
function fileExists($filePath)
{
return is_file($filePath) && file_exists($filePath);
}
Bit late to the party here, but another way to do it would be to use a Deferred object. You essentially have the same amount of boilerplate, but it's handy if you want to pass them around and possibly resolve outside of their definition.
Naive Implementation:
class Deferred {
constructor() {
this.promise = new Promise((resolve, reject)=> {
this.reject = reject
this.resolve = resolve
})
}
}
function asyncAction() {
var dfd = new Deferred()
setTimeout(()=> {
dfd.resolve(42)
}, 500)
return dfd.promise
}
asyncAction().then(result => {
console.log(result) // 42
})
ES5 Version:
function Deferred() {
var self = this;
this.promise = new Promise(function(resolve, reject) {
self.reject = reject
self.resolve = resolve
})
}
function asyncAction() {
var dfd = new Deferred()
setTimeout(function() {
dfd.resolve(42)
}, 500)
return dfd.promise
}
asyncAction().then(function(result) {
console.log(result) // 42
})
XMLStarlet or another XPath engine is the correct tool for this job.
For instance, with data.xml
containing the following:
<root>
<item>
<title>15:54:57 - George:</title>
<description>Diane DeConn? You saw Diane DeConn!</description>
</item>
<item>
<title>15:55:17 - Jerry:</title>
<description>Something huh?</description>
</item>
</root>
...you can extract only the first title with the following:
xmlstarlet sel -t -m '//title[1]' -v . -n <data.xml
Trying to use sed for this job is troublesome. For instance, the regex-based approaches won't work if the title has attributes; won't handle CDATA sections; won't correctly recognize namespace mappings; can't determine whether a portion of the XML documented is commented out; won't unescape attribute references (such as changing Brewster & Jobs
to Brewster & Jobs
), and so forth.
All you have to do is write an IF condition in the column d like this:
=IF(A1=C1;B1;" ")
After that just apply this formula to all rows above that one.
Always double check httpd.conf to see if document root is correctly pointing to an existing folder
#if you have c:\your-main-folder\www\
DocumentRoot "c:/your-main-folder/www/"
#if you have c:\your-main-folder\www\sub-folder\
DocumentRoot "c:/your-main-folder/www/sub-folder/"
DocumentRoot
points to a folder that must exist in your drive.
The min sdk version is the minimum version of the Android operating system required to run your application.
The target sdk version is the version of Android that your app was created to run on.
The compile sdk version is the the version of Android that the build tools uses to compile and build the application in order to release, run, or debug.
Usually the compile sdk version and the target sdk version are the same.
Not sure why SSMS doesn’t take into account execution order but it just doesn’t. This is not an issue for small databases but what if your database has 200 objects? In that case order of execution does matter because it’s not really easy to go through all of these.
For unordered scripts generated by SSMS you can go following
a) Execute script (some objects will be inserted some wont, there will be some errors)
b) Remove all objects from the script that have been added to database
c) Go back to a) until everything is eventually executed
Alternative option is to use third party tool such as ApexSQL Script or any other tools already mentioned in this thread (SSMS toolpack, Red Gate and others).
All of these will take care of the dependencies for you and save you even more time.
scrollView.postDelayed(new Runnable() {
@Override
public void run() {
scrollView.fullScroll(ScrollView.FOCUS_DOWN);
}
},1000);
We don't need to plt.ioff()
or plt.show()
(if we use %matplotlib inline
). You can test above code without plt.ioff()
. plt.close()
has the essential role. Try this one:
%matplotlib inline
import pylab as plt
# It doesn't matter you add line below. You can even replace it by 'plt.ion()', but you will see no changes.
## plt.ioff()
# Create a new figure, plot into it, then close it so it never gets displayed
fig = plt.figure()
plt.plot([1,2,3])
plt.savefig('test0.png')
plt.close(fig)
# Create a new figure, plot into it, then don't close it so it does get displayed
fig2 = plt.figure()
plt.plot([1,3,2])
plt.savefig('test1.png')
If you run this code in iPython, it will display a second plot, and if you add plt.close(fig2)
to the end of it, you will see nothing.
In conclusion, if you close figure by plt.close(fig)
, it won't be displayed.
Before importing just make sure you have max_allowed_pack value set some thing large else you will get an error: Error 2006 MySQL server gone away.
Then try the command: mysql -u root -p database_name < file.sql
In windows this command does not work for me..I have tried the following command and it works..using this command I created session in couchdb sync gate way for the specific user...
curl -v -H "Content-Type: application/json" -X POST -d "{ \"name\": \"abc\",\"password\": \"abc123\" }" http://localhost:4984/todo/_session
To the great answers that already included here I want to add something that missing in my perspective - an illustration.
As you already JVM divides the allocated memory to a Java program into two parts. one is stack and another one is heap. Stack is used for execution purpose and heap is used for storage purpose. In that heap memory, JVM allocates some memory specially meant for string literals. This part of the heap memory is called string constants pool.
So for example, if you init the following objects:
String s1 = "abc";
String s2 = "123";
String obj1 = new String("abc");
String obj2 = new String("def");
String obj3 = new String("456);
String literals s1
and s2
will go to string constant pool, objects obj1, obj2, obj3 to the heap. All of them, will be referenced from the Stack.
Also, please note that "abc" will appear in heap and in string constant pool. Why is String s1 = "abc"
and String obj1 = new String("abc")
will be created this way? It's because String obj1 = new String("abc")
explicitly creates a new and referentially distinct instance of a String object and String s1 = "abc"
may reuse an instance from the string constant pool if one is available. For a more elaborate explanation: https://stackoverflow.com/a/3298542/2811258
How about using the CSS3 flex model:
HTML Code:
<div id="wrapper">
<div id="c1">c1</div>
<div id="c2">c2</div>
<div id="c3">c3</div>
</div>
CSS Code:
*{
margin:0;
padding:0;
}
#wrapper{
display:-webkit-flex;
-webkit-justify-content:center;
display:flex;
justify-content:center;
}
#wrapper div{
-webkit-flex:1;
flex:1;
border:thin solid #777;
}
This is a function based on @DamienFennelly's answer above. If you give me a thumbs up, give him a thumbs up too! :P
Function outColLetterFromNumber(iCol as Integer) as String
sAddr = Cells(1, iCol).Address
aSplit = Split(sAddr, "$")
outColLetterFromNumber = aSplit(1)
End Function
There is a much easier way to run JavaScript, no configuration needed:
Run Code
, the code will run and the output will be shown in the Output Window.Besides, you could select part of the JavaScript code and run the code snippet. The extension also works with unsaved files, so you can just create a file, change it to Javascript and write code fast (for when you just need to try something quick). Very convenient!
I have used in Google Sheets
={sheetname!columnnamefrom:columnnameto}
Example:
={sheet1!A:A}
={sheet2!A4:A20}
I had the same problem, I removed "@ManagedBean" from my bean class now working.
If you are using CentOS linux system the Maven local repositary will be:
/root/.m2/repository/
You can remove .m2 and build your maven project in dev tool will fix the issue.
Microsoft SQL Server 2005 Express Edition Service Pack 4 on Windows Server 2012 R2
Those steps are based on previous howto from https://stackoverflow.com/users/2385/eduardo-molteni
This works with Microsoft SQL Server 2005 Express Edition Service Pack 4 http://www.microsoft.com/en-us/download/details.aspx?id=184
It is possible to use the DataFrame style property to highlight the background color of the cells where there is a difference.
Using the example data from the original question
The first step is to concatenate the DataFrames horizontally with the concat
function and distinguish each frame with the keys
parameter:
df_all = pd.concat([df.set_index('id'), df2.set_index('id')],
axis='columns', keys=['First', 'Second'])
df_all
It's probably easier to swap the column levels and put the same column names next to each other:
df_final = df_all.swaplevel(axis='columns')[df.columns[1:]]
df_final
Now, its much easier to spot the differences in the frames. But, we can go further and use the style
property to highlight the cells that are different. We define a custom function to do this which you can see in this part of the documentation.
def highlight_diff(data, color='yellow'):
attr = 'background-color: {}'.format(color)
other = data.xs('First', axis='columns', level=-1)
return pd.DataFrame(np.where(data.ne(other, level=0), attr, ''),
index=data.index, columns=data.columns)
df_final.style.apply(highlight_diff, axis=None)
This will highlight cells that both have missing values. You can either fill them or provide extra logic so that they don't get highlighted.
Yes, you should try to serve valid code if possible.
Most browsers will silently correct this error, but there is a problem with relying on the error handling in the browsers. There is no standard for how to handle incorrect code, so it's up to each browser vendor to try to figure out what to do with each error, and the results may vary.
Some examples where browsers are likely to react differently is if you put elements inside a table but outside the table cells, or if you nest links inside each other.
For your specific example it's not likely to cause any problems, but error correction in the browser might for example cause the browser to change from standards compliant mode into quirks mode, which could make your layout break down completely.
So, you should correct errors like this in the code, if not for anything else so to keep the error list in the validator short, so that you can spot more serious problems.
I had the same problem on Windows and used a different solution. I used the Composer_Setup.exe installation file supplied by the composer website and it does a global install.
After installing, make sure your PATH variable points to the directory where composer.phar is stored. This is usually C:\ProgramData\ComposerSetup\bin
(ProgramData might be a hidden directory). It goes without saying, but also be sure that the PHP executable is also in your PATH variable.
You can then simply call
composer install
instead of
php composer.phar install
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--example', nargs='?', const=1, type=int)
args = parser.parse_args()
print(args)
% test.py
Namespace(example=None)
% test.py --example
Namespace(example=1)
% test.py --example 2
Namespace(example=2)
nargs='?'
means 0-or-1 argumentsconst=1
sets the default when there are 0 argumentstype=int
converts the argument to intIf you want test.py
to set example
to 1 even if no --example
is specified, then include default=1
. That is, with
parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
then
% test.py
Namespace(example=1)
Old but still valid question, so heres what I created based on the info provided by others here.
create function fnLastIndexOf(@text varChar(max),@char varchar(1))
returns int
as
begin
return len(@text) - charindex(@char, reverse(@text)) -1
end
Remove -Werror
from your Make or CMake files, as suggested in this post
For 2.3 seconds you should do:
System.Threading.Thread.Sleep(2300);
JSmooth .exe wrapper
JSmooth is a Java Executable Wrapper. It creates native Windows launchers (standard .exe) for your Java applications. It makes java deployment much smoother and user-friendly, as it is able to find any installed Java VM by itself. When no VM is available, the wrapper can automatically download and install a suitable JVM, or simply display a message or redirect the user to a website.
JSmooth provides a variety of wrappers for your java application, each of them having their own behavior: Choose your flavor!
Download: http://jsmooth.sourceforge.net/
JarToExe 1.8 Jar2Exe is a tool to convert jar files into exe files. Following are the main features as describe on their website:
Can generate “Console”, “Windows GUI”, “Windows Service” three types of .exe files.
Generated .exe files can add program icons and version information. Generated .exe files can encrypt and protect java programs, no temporary files will be generated when the program runs.
Generated .exe files provide system tray icon support. Generated .exe files provide record system event log support. Generated windows service .exe files are able to install/uninstall itself, and support service pause/continue.
Executor
Package your Java application as a jar, and Executor will turn the jar into a Windows .exe file, indistinguishable from a native application. Simply double-clicking the .exe file will invoke the Java Runtime Environment and launch your application.
Just put
export HOME=/blah/whatever
at the point in the script where you want the change to happen. Since each process has its own set of environment variables, this definition will automatically cease to have any significance when the script terminates (and with it the instance of bash that has a changed environment).
I think you were planning to use Angular template reference variable based on your html template.
// in html
<input #nameInput type="text" class="form-control" placeholder=''/>
// in add-player.ts file
import { OnInit, ViewChild, ElementRef } from '@angular/core';
export class AddPlayerComponent implements OnInit {
@ViewChild('nameInput') nameInput: ElementRef;
constructor() { }
ngOnInit() { }
addPlayer() {
// you can access the input value via the following syntax.
console.log('player name: ', this.nameInput.nativeElement.value);
}
}
If checkout master
was the last thing you did, then the reflog entry HEAD@{1}
will contain your commits (otherwise use git reflog
or git log -p
to find them). Use git merge HEAD@{1}
to fast forward them into master.
EDIT:
As noted in the comments, Git Ready has a great article on this.
git reflog
and git reflog --all
will give you the commit hashes of the mis-placed commits.
Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
There is an extension for that, but I have no usage experience yet:
http://ipython.scipy.org/ipython/ipython/attachment/ticket/154/ipy_autoreload.py
From my experience with tutorials, and other things number 2 always seems preferred, but it's a personal preference choice more than anything else.
Option Explicit
Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"
Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"
'C:\Users\BARON\Desktop\Test.accdb
Sub ModifyingExistingDataOnAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
'.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Do Until .EOF
If .Fields("Emp_Age").Value > 40 Then
.Fields("Emp_Age").Value = 40
.Update
End If
.MoveNext
Loop
.MoveFirst
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.CancelUpdate
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
Sub AddingDataToAccessDB()
Dim TableConn As ADODB.Connection
Dim TableData As ADODB.Recordset
Dim r As Range
Set TableConn = New ADODB.Connection
Set TableData = New ADODB.Recordset
TableConn.ConnectionString = ConnectionStrngAccess
TableConn.Open
On Error GoTo CloseConnection
With TableData
.ActiveConnection = TableConn
.Source = "Roster"
.LockType = adLockOptimistic
.CursorType = adOpenForwardOnly
.Open
On Error GoTo CloseRecordset
Sheet3.Activate
For Each r In Range("B3", Range("B3").End(xlDown))
MsgBox "Adding " & r.Offset(0, 1)
.AddNew
.Fields("Emp_ID").Value = r.Offset(0, 0).Value
.Fields("Emp_Name").Value = r.Offset(0, 1).Value
.Fields("Emp_DOB").Value = r.Offset(0, 2).Value
.Fields("Emp_SOD").Value = r.Offset(0, 3).Value
.Fields("Emp_EOD").Value = r.Offset(0, 4).Value
.Fields("Emp_Age").Value = r.Offset(0, 5).Value
.Fields("Emp_Gender").Value = r.Offset(0, 6).Value
.Update
Next r
MsgBox "Update Complete"
End With
CloseRecordset:
TableData.Close
CloseConnection:
TableConn.Close
Set TableConn = Nothing
Set TableData = Nothing
End Sub
This last error is caused by the library SLF4J not being found. HikariCP has two dependencies: slf4j and javassist. BTW, HikariDataSource does have a default constructor and does not need HikariConfig, see this link. So that was never the problem.
/// <summary>
/// Returns a string With count chars Left or Right value
/// </summary>
/// <param name="val"></param>
/// <param name="count"></param>
/// <param name="space"></param>
/// <param name="right"></param>
/// <returns></returns>
public static string Formating(object val, int count, char space = ' ', bool right = false)
{
var value = val.ToString();
for (int i = 0; i < count - value.Length; i++) value = right ? value + space : space + value;
return value;
}
try this method given below, modify to suit your need.
SELECT
employment_status.staff_type,
COUNT(monthly_pay_register.age),
monthly_pay_register.BASIC_SALARY,
monthly_pay_register.TOTAL_MONTHLY_ALLOWANCES,
monthly_pay_register.MONTHLY_GROSS,
monthly_pay_register.TOTAL_MONTHLY_DEDUCTIONS,
monthly_pay_register.MONTHLY_PAY
FROM
(monthly_pay_register INNER JOIN deduction_logs
ON
monthly_pay_register.employee_info_employee_no = deduction_logs.employee_no)
INNER JOIN
employment_status ON deduction_logs.employee_no = employment_status.employee_no
WHERE
monthly_pay_register.`YEAR`=2017
and
monthly_pay_register.`MONTH`='may'
Yes you can do somthing simulair, here you have to know the different argument lists you can get but you have the same function to handle then all.
typedef enum { my_input_set1 = 0, my_input_set2, my_input_set3} INPUT_SET;
typedef struct{
INPUT_SET type;
char* text;
} input_set1;
typedef struct{
INPUT_SET type;
char* text;
int var;
} input_set2;
typedef struct{
INPUT_SET type;
int text;
} input_set3;
typedef union
{
INPUT_SET type;
input_set1 set1;
input_set2 set2;
input_set3 set3;
} MY_INPUT;
void my_func(MY_INPUT input)
{
switch(input.type)
{
case my_input_set1:
break;
case my_input_set2:
break;
case my_input_set3:
break;
default:
// unknown input
break;
}
}
HTTP is an application protocol. REST is a set of rules, that when followed, enable you to build a distributed application that has a specific set of desirable constraints.
If you are looking for the most significant constraints of REST that distinguish a RESTful application from just any HTTP application, I would say the "self-description" constraint and the hypermedia constraint (aka Hypermedia as the Engine of Application State (HATEOAS)) are the most important.
The self-description constraint requires a RESTful request to be completely self descriptive in the users intent. This allows intermediaries (proxies and caches) to act on the message safely.
The HATEOAS constraint is about turning your application into a web of links where the client's current state is based on its place in that web. It is a tricky concept and requires more time to explain than I have right now.
It's all about trying all those answers, for me, nothing works except the next solution: Google font suggested
@import 'https://fonts.googleapis.com/css?family=Assistant';
But, I'm using here foreign language fonts, and it didn't work on IE11 only. I found out this solution that worked:
@import 'https://fonts.googleapis.com/css?family=Assistant&subset=hebrew';
Hope that save someone precious time
For those of us that learn by example...
Write text to a file like this:
IO.write('/tmp/msg.txt', 'hi')
BONUS INFO ...
Read it back like this
IO.read('/tmp/msg.txt')
Frequently, I want to read a file into my clipboard ***
Clipboard.copy IO.read('/tmp/msg.txt')
And other times, I want to write what's in my clipboard to a file ***
IO.write('/tmp/msg.txt', Clipboard.paste)
*** Assumes you have the clipboard gem installed