in regard of answer from @Perception, its true to be very memory-consuming when working with byte arrays, but you could also simply write back into the outputstream
@Path("/picture")
public class ProfilePicture {
@GET
@Path("/thumbnail")
@Produces("image/png")
public StreamingOutput getThumbNail() {
return new StreamingOutput() {
@Override
public void write(OutputStream os) throws IOException, WebApplicationException {
//... read your stream and write into os
}
};
}
}
According to the GF Administration Guide:
For a valid JVM installation, locations are checked in the following order: a. domain.xml (java-home inside java-config) b. asenv.conf (setting AS_JAVA="path to java home")
I had to add both these settings to make it work. Otherwise 'asadmin stop-domain domain1' wouldn't work. I guess that GF uses a. and asadmin uses b.
(On Windows: b. asenv.bat)
Your description is a little bit strange because the GlassFish server can even start if port 1527 is occupied, because the Java Derby database is a separate java process. So one option could be to just ignore the message in case that the real GlassFish server is indeed starting correctly (NetBeans displays the output for the GlassFish server and the Derby server in different tabs).
Nevertheless you can try to disable starting the registered Derby server for your GlassFish instance.
Make sure that the Derby server is shut down, it can even still run if you have closed NetBeans. If you are not sure kill every java process via the task manager and restart NetBeans.
Right-click your GlassFish instance in the Services tab and choose Properties.
If instead the real problem is that either port 8080 or 443 (if you activated the HTTPS listener) is in use (which would really prevent GlassFish from starting), you have to find out which application is using this port (maybe Tomcat or something similar) and shut it down.
The error message
'Could not start GlassFish Server 4.1: HTTP or HTTPS listener port is occupied while server is not running'
just points a little bit more in this direction...
Your standard project setup will have a project structure something like:
src/main/java
src/main/resources
You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist
For Eclipse Luna
Go to Help>Eclipse MarketPlace> Search for GlassFish Tools and install it.
Restart Eclipse.
Now go to servers>new>server and you will find Glassfish server.
In general the logs are in /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/
.
In NetBeans go to the "Services" tab open "Servers", right-click on your Glassfish instance and click "View Domain Server Log".
If this doesn't work right-click on the Glassfish instance and click "Properties", you can see the folder with the domains under "Domains folder". Go to this folder -> your-domain -> logs
If the server is already running you should see an Output
tab in NetBeans which is named similar to GlassFish Server x.x.x
You can also use cat
or tail -F
on /YOUR_GLASSFISH_INSTALL/glassfish/domains/domain1/logs/server.log
. If you are using a different domain then domain1
you have to adjust the path for that.
Try to use classpath*:
prefix instead.
Also please try to deploy exploded war, to ensure that all files are there.
Your local port 443 / 8181 / 3820 is used.
If you are on linux/unix:
netstat -an
and lsof -n
to check who is using this portIf you are on windows
netstat -an
and tcpview
to check.An authority is a portion of a URI. Your error suggests that it was not expecting one. The authority section is shown below, it is what is known as the website part of the url.
From RFC3986 on URIs:
The following is an example URI and its component parts:
foo://example.com:8042/over/there?name=ferret#nose
\_/ \______________/\_________/ \_________/ \__/
| | | | |
scheme authority path query fragment
| _____________________|__
/ \ / \
urn:example:animal:ferret:nose
So there are two formats, one with an authority and one not. Regarding slashes:
"When authority is not present, the path cannot begin with two slash
characters ("//")."
Source: https://tools.ietf.org/rfc/rfc3986.txt (search for text 'authority is not present, the path cannot begin with two slash')
The jersey-container-servlet
actually uses the jersey-container-servlet-core
dependency. But if you use maven, that does not really matter. If you just define the jersey-container-servlet
usage, it will automatically download the dependency as well.
But for those who add jar files to their project manually (i.e. without maven) It is important to know that you actually need both jar files. The org.glassfish.jersey.servlet.ServletContainer
class is actually part of the core dependency.
You should use GlassFish for Java EE enterprise applications. Some things to consider:
A web Server means: Handling HTTP requests (usually from browsers).
A Servlet Container (e.g. Tomcat) means: It can handle servlets & JSP.
An Application Server (e.g. GlassFish) means: *It can manage Java EE applications (usually both servlet/JSP and EJBs).
Tomcat - is run by Apache community - Open source and has two flavors:
No commercial support available (only community support)
JBoss - Run by RedHat This is a full-stack support for JavaEE and it is a certified Java EE container. This includes Tomcat as web container internally. This also has two flavors:
Glassfish - Run by Oracle This is also a full stack certified Java EE Container. This has its own web container (not Tomcat). This comes from Oracle itself, so all new specs will be tested and implemented with Glassfish first. So, always it would support the latest spec. I am not aware of its support models.
These are typical npm paths if you install a package globally:
Windows XP - %USERPROFILE%\Application Data\npm\node_modules
Newer Windows Versions - %AppData%\npm\node_modules
or - %AppData%\roaming\npm\node_modules
$("div.test:not(:first)").hide();
or:
$("div.test:not(:eq(0))").hide();
or:
$("div.test").not(":eq(0)").hide();
or:
$("div.test:gt(0)").hide();
or: (as per @Jordan Lev's comment):
$("div.test").slice(1).hide();
and so on.
See:
The conventional way of handling this doesn't play well with ES6. You can do this instead:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
this.delete(clickedElement.data('id'));
});
Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:
$('.delete').on('click', event => {
const clickedElement = $(event.target);
const targetElement = clickedElement.closest('.delete');
this.delete(targetElement.data('id'));
});
Here is a complete version of code for doing this. I have tested it. The BufferedImage
and Base64
class do the trick mainly. Also some parameter needs to be set correctly.
public class SimpleConvertImage {
public static void main(String[] args) throws IOException{
String dirName="C:\\";
ByteArrayOutputStream baos=new ByteArrayOutputStream(1000);
BufferedImage img=ImageIO.read(new File(dirName,"rose.jpg"));
ImageIO.write(img, "jpg", baos);
baos.flush();
String base64String=Base64.encode(baos.toByteArray());
baos.close();
byte[] bytearray = Base64.decode(base64String);
BufferedImage imag=ImageIO.read(new ByteArrayInputStream(bytearray));
ImageIO.write(imag, "jpg", new File(dirName,"snap.jpg"));
}
}
Python is neither pass-by-value nor pass-by-reference. It's more of "object references are passed by value" as described here:
Here's why it's not pass-by-value. Because
def append(list):
list.append(1)
list = [0]
reassign(list)
append(list)
returns [0,1] showing that some kind of reference was clearly passed as pass-by-value does not allow a function to alter the parent scope at all.
Looks like pass-by-reference then, hu? Nope.
Here's why it's not pass-by-reference. Because
def reassign(list):
list = [0, 1]
list = [0]
reassign(list)
print list
returns [0] showing that the original reference was destroyed when list was reassigned. pass-by-reference would have returned [0,1].
For more information look here:
If you want your function to not manipulate outside scope, you need to make a copy of the input parameters that creates a new object.
from copy import copy
def append(list):
list2 = copy(list)
list2.append(1)
print list2
list = [0]
append(list)
print list
Just delete key:
HKEY_CURRENT_USER/Software/Microsoft/VCExpress/9.0/Registration
Or run in command line:
reg delete HKCU\Software\Microsoft\VCExpress\9.0\Registration /f
With Java 6 form I think is better to check it is closed or not before close (for example if some connection pooler evict the connection in other thread) - for example some network problem - the statement and resultset state can be come closed. (it is not often happens, but I had this problem with Oracle and DBCP). My pattern is for that (in older Java syntax) is:
try {
//...
return resp;
} finally {
if (rs != null && !rs.isClosed()) {
try {
rs.close();
} catch (Exception e2) {
log.warn("Cannot close resultset: " + e2.getMessage());
}
}
if (stmt != null && !stmt.isClosed()) {
try {
stmt.close();
} catch (Exception e2) {
log.warn("Cannot close statement " + e2.getMessage());
}
}
if (con != null && !conn.isClosed()) {
try {
con.close();
} catch (Exception e2) {
log.warn("Cannot close connection: " + e2.getMessage());
}
}
}
In theory it is not 100% perfect because between the the checking the close state and the close itself there is a little room for the change for state. In the worst case you will get a warning in long. - but it is lesser than the possibility of state change in long run queries. We are using this pattern in production with an "avarage" load (150 simultanous user) and we had no problem with it - so never see that warning message.
var result = from entry in table
where entry.something == value||entry.something == null
select entry;
use that
IUS offers an installation script for subscribing to their repository and importing associated GPG keys. Make sure you’re in your home directory, and retrieve the script using curl:
curl 'https://setup.ius.io/' -o setup-ius.sh
sudo bash setup-ius.sh
Install Required Packages-:
sudo yum install -y mod_php70u php70u-cli php70u-mysqlnd php70u-json php70u-gd php70u-dom php70u-simplexml php70u-mcrypt php70u-intl
smalldatetime
has range up to June 6, 2079 so you can use
ORDER BY ISNULL(Next_Contact_Date, '2079-06-05T23:59:00')
If no legitimate records will have that date.
If this is not an assumption you fancy relying on a more robust option is sorting on two columns.
ORDER BY CASE WHEN Next_Contact_Date IS NULL THEN 1 ELSE 0 END, Next_Contact_Date
Both of the above suggestions are not able to use an index to avoid a sort however and give similar looking plans.
One other possibility if such an index exists is
SELECT 1 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NOT NULL
UNION ALL
SELECT 2 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NULL
ORDER BY Grp, Next_Contact_Date
The only thing that worked for me:
@Override
protected void configure(HttpSecurity http) throws Exception {
http.csrf().disable().authorizeRequests().anyRequest().permitAll();
}
and
security.ignored=/**
Could be that the properties part is redundant or can be done in code, but had no time to experiment. Anyway is temporary.
Code Snippet to convert SQL PreparedStaments with the list of arguments. It works for me
/**
*
* formatQuery Utility function which will convert SQL
*
* @param sql
* @param arguments
* @return
*/
public static String formatQuery(final String sql, Object... arguments) {
if (arguments != null && arguments.length <= 0) {
return sql;
}
String query = sql;
int count = 0;
while (query.matches("(.*)\\?(.*)")) {
query = query.replaceFirst("\\?", "{" + count + "}");
count++;
}
String formatedString = java.text.MessageFormat.format(query, arguments);
return formatedString;
}
For SQL Server 2008, I would imagine the procedure is similar...?
I made a solution for this.
$(function () {_x000D_
var dropZoneId = "drop-zone";_x000D_
var buttonId = "clickHere";_x000D_
var mouseOverClass = "mouse-over";_x000D_
_x000D_
var dropZone = $("#" + dropZoneId);_x000D_
var ooleft = dropZone.offset().left;_x000D_
var ooright = dropZone.outerWidth() + ooleft;_x000D_
var ootop = dropZone.offset().top;_x000D_
var oobottom = dropZone.outerHeight() + ootop;_x000D_
var inputFile = dropZone.find("input");_x000D_
document.getElementById(dropZoneId).addEventListener("dragover", function (e) {_x000D_
e.preventDefault();_x000D_
e.stopPropagation();_x000D_
dropZone.addClass(mouseOverClass);_x000D_
var x = e.pageX;_x000D_
var y = e.pageY;_x000D_
_x000D_
if (!(x < ooleft || x > ooright || y < ootop || y > oobottom)) {_x000D_
inputFile.offset({ top: y - 15, left: x - 100 });_x000D_
} else {_x000D_
inputFile.offset({ top: -400, left: -400 });_x000D_
}_x000D_
_x000D_
}, true);_x000D_
_x000D_
if (buttonId != "") {_x000D_
var clickZone = $("#" + buttonId);_x000D_
_x000D_
var oleft = clickZone.offset().left;_x000D_
var oright = clickZone.outerWidth() + oleft;_x000D_
var otop = clickZone.offset().top;_x000D_
var obottom = clickZone.outerHeight() + otop;_x000D_
_x000D_
$("#" + buttonId).mousemove(function (e) {_x000D_
var x = e.pageX;_x000D_
var y = e.pageY;_x000D_
if (!(x < oleft || x > oright || y < otop || y > obottom)) {_x000D_
inputFile.offset({ top: y - 15, left: x - 160 });_x000D_
} else {_x000D_
inputFile.offset({ top: -400, left: -400 });_x000D_
}_x000D_
});_x000D_
}_x000D_
_x000D_
document.getElementById(dropZoneId).addEventListener("drop", function (e) {_x000D_
$("#" + dropZoneId).removeClass(mouseOverClass);_x000D_
}, true);_x000D_
_x000D_
})
_x000D_
#drop-zone {_x000D_
/*Sort of important*/_x000D_
width: 300px;_x000D_
/*Sort of important*/_x000D_
height: 200px;_x000D_
position:absolute;_x000D_
left:50%;_x000D_
top:100px;_x000D_
margin-left:-150px;_x000D_
border: 2px dashed rgba(0,0,0,.3);_x000D_
border-radius: 20px;_x000D_
font-family: Arial;_x000D_
text-align: center;_x000D_
position: relative;_x000D_
line-height: 180px;_x000D_
font-size: 20px;_x000D_
color: rgba(0,0,0,.3);_x000D_
}_x000D_
_x000D_
#drop-zone input {_x000D_
/*Important*/_x000D_
position: absolute;_x000D_
/*Important*/_x000D_
cursor: pointer;_x000D_
left: 0px;_x000D_
top: 0px;_x000D_
/*Important This is only comment out for demonstration purposes._x000D_
opacity:0; */_x000D_
}_x000D_
_x000D_
/*Important*/_x000D_
#drop-zone.mouse-over {_x000D_
border: 2px dashed rgba(0,0,0,.5);_x000D_
color: rgba(0,0,0,.5);_x000D_
}_x000D_
_x000D_
_x000D_
/*If you dont want the button*/_x000D_
#clickHere {_x000D_
position: absolute;_x000D_
cursor: pointer;_x000D_
left: 50%;_x000D_
top: 50%;_x000D_
margin-left: -50px;_x000D_
margin-top: 20px;_x000D_
line-height: 26px;_x000D_
color: white;_x000D_
font-size: 12px;_x000D_
width: 100px;_x000D_
height: 26px;_x000D_
border-radius: 4px;_x000D_
background-color: #3b85c3;_x000D_
_x000D_
}_x000D_
_x000D_
#clickHere:hover {_x000D_
background-color: #4499DD;_x000D_
_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
<div id="drop-zone">_x000D_
Drop files here..._x000D_
<div id="clickHere">_x000D_
or click here.._x000D_
<input type="file" name="file" id="file" />_x000D_
</div>_x000D_
</div>
_x000D_
The Drag and Drop functionality for this method only works with Chrome, Firefox and Safari. (Don't know if it works with IE10), but for other browsers, the "Or click here" button works fine.
The input field simply follow your mouse when dragging a file over an area, and I've added a button as well..
Uncomment opacity:0; the file input is only visible so you can see what's going on.
You can use this command (python script) for larger inputs:
echo 58595a | python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"
The result will be:
XYZ
And for more simplicity, define an alias:
alias hexdecoder='python -c "import sys; import binascii; print(binascii.unhexlify(sys.stdin.read().strip()).decode())"'
echo 58595a | hexdecoder
r+
is the canonical mode for reading and writing at the same time. This is not different from using the fopen()
system call since file()
/ open()
is just a tiny wrapper around this operating system call.
Use awk(another great bash utility) instead of grep where you dont have the line buffered option! It will continuously stream your data from tail.
this is how you use grep
tail -f <file> | grep pattern
This is how you would use awk
tail -f <file> | awk '/pattern/{print $0}'
This worked for me endDate: "today"
$('#datepicker').datepicker({
format: "dd/mm/yyyy",
autoclose: true,
orientation: "top",
endDate: "today"
});
This css works for me:
.dataTables_paginate {
float: none !important;
text-align: center !important;
}
You should set the option:
local-infile=1
into your [mysql] entry of my.cnf file or call mysql client with the --local-infile option:
mysql --local-infile -uroot -pyourpwd yourdbname
You have to be sure that the same parameter is defined into your [mysqld] section too to enable the "local infile" feature server side.
It's a security restriction.
LOAD DATA LOCAL INFILE '/softwares/data/data.csv' INTO TABLE tableName;
I made a small change to Softlion answer, so all my modals won't refresh on hide. The modals with data-refresh='true' attribute are only refreshed, others work as usual. Here is the modified version.
$(document).on('hidden.bs.modal', function (e) {
if ($(e.target).attr('data-refresh') == 'true') {
// Remove modal data
$(e.target).removeData('bs.modal');
// Empty the HTML of modal
$(e.target).html('');
}
});
Now use the attribute as shown below,
<div class="modal fade" data-refresh="true" id="#modal" tabindex="-1" role="dialog" aria-labelledby="#modal-label" aria-hidden="true"></div>
This will make sure only the modals with data-refresh='true' are refreshed. And i'm also resetting the modal html because the old values are shown until new ones get loaded, making html empty fixes that one.
I'd recommend serialization,
public class Person
{
public string FirstName;
public string MI;
public string LastName;
}
static void Serialize()
{
clsPerson p = new Person();
p.FirstName = "Jeff";
p.MI = "A";
p.LastName = "Price";
System.Xml.Serialization.XmlSerializer x = new System.Xml.Serialization.XmlSerializer(p.GetType());
x.Serialize(System.Console.Out, p);
System.Console.WriteLine();
System.Console.WriteLine(" --- Press any key to continue --- ");
System.Console.ReadKey();
}
You can further control serialization with attributes.
But if it is simple, you could use XmlDocument:
using System;
using System.Xml;
public class GenerateXml {
private static void Main() {
XmlDocument doc = new XmlDocument();
XmlNode docNode = doc.CreateXmlDeclaration("1.0", "UTF-8", null);
doc.AppendChild(docNode);
XmlNode productsNode = doc.CreateElement("products");
doc.AppendChild(productsNode);
XmlNode productNode = doc.CreateElement("product");
XmlAttribute productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "01";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
XmlNode nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("Java"));
productNode.AppendChild(nameNode);
XmlNode priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
// Create and add another product node.
productNode = doc.CreateElement("product");
productAttribute = doc.CreateAttribute("id");
productAttribute.Value = "02";
productNode.Attributes.Append(productAttribute);
productsNode.AppendChild(productNode);
nameNode = doc.CreateElement("Name");
nameNode.AppendChild(doc.CreateTextNode("C#"));
productNode.AppendChild(nameNode);
priceNode = doc.CreateElement("Price");
priceNode.AppendChild(doc.CreateTextNode("Free"));
productNode.AppendChild(priceNode);
doc.Save(Console.Out);
}
}
And if it needs to be fast, use XmlWriter:
public static void WriteXML()
{
// Create an XmlWriterSettings object with the correct options.
System.Xml.XmlWriterSettings settings = new System.Xml.XmlWriterSettings();
settings.Indent = true;
settings.IndentChars = " "; // "\t";
settings.OmitXmlDeclaration = false;
settings.Encoding = System.Text.Encoding.UTF8;
using (System.Xml.XmlWriter writer = System.Xml.XmlWriter.Create("data.xml", settings))
{
writer.WriteStartDocument();
writer.WriteStartElement("books");
for (int i = 0; i < 100; ++i)
{
writer.WriteStartElement("book");
writer.WriteElementString("item", "Book "+ (i+1).ToString());
writer.WriteEndElement();
}
writer.WriteEndElement();
writer.Flush();
writer.Close();
} // End Using writer
}
And btw, the fastest way to read XML is XmlReader:
public static void ReadXML()
{
using (System.Xml.XmlReader xmlReader = System.Xml.XmlReader.Create("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml"))
{
while (xmlReader.Read())
{
if ((xmlReader.NodeType == System.Xml.XmlNodeType.Element) && (xmlReader.Name == "Cube"))
{
if (xmlReader.HasAttributes)
System.Console.WriteLine(xmlReader.GetAttribute("currency") + ": " + xmlReader.GetAttribute("rate"));
}
} // Whend
} // End Using xmlReader
System.Console.ReadKey();
}
And the most convenient way to read XML is to just deserialize the XML into a class.
This also works for creating the serialization classes, btw.
You can generate the class from XML with Xml2CSharp:
https://xmltocsharp.azurewebsites.net/
If you want to pull a directory with restricted access from a rooted device you need to restart adb as root: type adb root
before pull. Otherwise you'll get an error saying remote object '/data/data/xxx.example.app' does not exist
You might find ODA useful. It's a web-based disassembler that supports tons of architectures.
As the accepted answer suggests you can add "using" to all views by adding to section of config file.
But for a single view you could just use
@using SomeNamespace.Extensions
When we try to run python file with path from terminal.
import sys
#For file name
file_name=sys.argv[0]
#For first argument
dir= sys.argv[1]
print("File Name: {}, argument dir: {}".format(file_name, dir)
Save the file (test.py).
Runing system.
Open terminal and go the that dir where is save file. then write
python test.py "/home/saiful/Desktop/bird.jpg"
Hit enter
Output:
File Name: test, Argument dir: /home/saiful/Desktop/bird.jpg
Default c++ mechanism for file IO is called streams.
Streams can be of three flavors: input, output and inputoutput.
Input streams act like sources of data. To read data from an input stream you use >>
operator:
istream >> my_variable; //This code will read a value from stream into your variable.
Operator >>
acts different for different types. If in the example above my_variable
was an int, then a number will be read from the strem, if my_variable
was a string, then a word would be read, etc.
You can read more then one value from the stream by writing istream >> a >> b >> c;
where a, b and c would be your variables.
Output streams act like sink to which you can write your data. To write your data to a stream, use <<
operator.
ostream << my_variable; //This code will write a value from your variable into stream.
As with input streams, you can write several values to the stream by writing something like this:
ostream << a << b << c;
Obviously inputoutput streams can act as both.
In your code sample you use cout
and cin
stream objects.
cout
stands for console-output and cin for console-input
. Those are predefined streams for interacting with default console.
To interact with files, you need to use ifstream
and ofstream
types.
Similar to cin
and cout
, ifstream
stands for input-file-stream
and ofstream
stands for output-file-stream
.
Your code might look like this:
#include <iostream>
#include <fstream>
using namespace std;
int start()
{
cout << "Welcome...";
// do fancy stuff
return 0;
}
int main ()
{
string usreq, usr, yn, usrenter;
cout << "Is this your first time using TEST" << endl;
cin >> yn;
if (yn == "y")
{
ifstream iusrfile;
ofstream ousrfile;
iusrfile.open("usrfile.txt");
iusrfile >> usr;
cout << iusrfile; // I'm not sure what are you trying to do here, perhaps print iusrfile contents?
iusrfile.close();
cout << "Please type your Username. \n";
cin >> usrenter;
if (usrenter == usr)
{
start ();
}
}
else
{
cout << "THAT IS NOT A REGISTERED USERNAME.";
}
return 0;
}
For further reading you might want to look at c++ I/O reference
Cloning the objects before adding them. For example, instead of newList.addAll(oldList);
for(Person p : oldList) {
newList.add(p.clone());
}
Assuming clone
is correctly overriden inPerson
.
In the event that anyone would be interested. Here's a quick shell script that will remove all local branches that aren't tracked remotely. A word of caution: This will get rid of any branch that isn't tracked remotely regardless of whether it was merged or not.
If you guys see any issues with this please let me know and I'll fix it (etc. etc.)
Save it in a file called git-rm-ntb
(call it whatever) on PATH
and run:
git-rm-ntb <remote1:optional> <remote2:optional> ...
clean()
{
REMOTES="$@";
if [ -z "$REMOTES" ]; then
REMOTES=$(git remote);
fi
REMOTES=$(echo "$REMOTES" | xargs -n1 echo)
RBRANCHES=()
while read REMOTE; do
CURRBRANCHES=($(git ls-remote $REMOTE | awk '{print $2}' | grep 'refs/heads/' | sed 's:refs/heads/::'))
RBRANCHES=("${CURRBRANCHES[@]}" "${RBRANCHES[@]}")
done < <(echo "$REMOTES" )
[[ $RBRANCHES ]] || exit
LBRANCHES=($(git branch | sed 's:\*::' | awk '{print $1}'))
for i in "${LBRANCHES[@]}"; do
skip=
for j in "${RBRANCHES[@]}"; do
[[ $i == $j ]] && { skip=1; echo -e "\033[32m Keeping $i \033[0m"; break; }
done
[[ -n $skip ]] || { echo -e "\033[31m $(git branch -D $i) \033[0m"; }
done
}
clean $@
Button 1 Button 2 Button 3
var reply_click = function() {
alert("Button clicked, id "+this.id+", text"+this.innerHTML);
}
document.getElementById('1').onclick = reply_click;
document.getElementById('2').onclick = reply_click;
document.getElementById('3').onclick = reply_click;
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.
Both classes Rectangle and Ellipse need to override both of the abstract methods.
To work around this, you have 3 options:
Have a single method that does the function of the classes that will extend Shape, and override that method in Rectangle and Ellipse, for example:
abstract class Shape {
// ...
void draw(Graphics g);
}
And
class Rectangle extends Shape {
void draw(Graphics g) {
// ...
}
}
Finally
class Ellipse extends Shape {
void draw(Graphics g) {
// ...
}
}
And you can switch in between them, like so:
Shape shape = new Ellipse();
shape.draw(/* ... */);
shape = new Rectangle();
shape.draw(/* ... */);
Again, just an example.
I ran some other question regarding ARIA. But it's content looks more promising for this question. would like to share them
What is ARIA?
If you put effort into making your website accessible to users with a variety of different browsing habits and physical disabilities, you'll likely recognize the role and aria-* attributes. WAI-ARIA (Accessible Rich Internet Applications) is a method of providing ways to define your dynamic web content and applications so that people with disabilities can identify and successfully interact with it. This is done through roles that define the structure of the document or application, or through aria-* attributes defining a widget-role, relationship, state, or property.
ARIA use is recommended in the specifications to make HTML5 applications more accessible. When using semantic HTML5 elements, you should set their corresponding role.
And see this you tube video for ARIA live.
If you want the threads to stop when your program exits (as implied by your example), then make them daemon threads.
If you want your threads to die on command, then you have to do it by hand. There are various methods, but all involve doing a check in your thread's loop to see if it's time to exit (see Nix's example).
ol {
counter-reset: item;
}
ol li { display: block }
ol li:before {
content: counter(item) ". ";
counter-increment: item;
font-weight: bold;
}
To use arrow functions with function.prototype.call
, I made a helper function on the object prototype:
// Using
// @func = function() {use this here} or This => {use This here}
using(func) {
return func.call(this, this);
}
usage
var obj = {f:3, a:2}
.using(This => This.f + This.a) // 5
Edit
You don't NEED a helper. You could do:
var obj = {f:3, a:2}
(This => This.f + This.a).call(undefined, obj); // 5
If you have multiple columns in your dataframe and would like to remove all rows that have outliers in at least one column, the following expression would do that in one shot.
df = pd.DataFrame(np.random.randn(100, 3))
from scipy import stats
df[(np.abs(stats.zscore(df)) < 3).all(axis=1)]
description:
zscore
, df[0]
for example, and remove .all(axis=1)
.df[(np.abs(stats.zscore(df[0])) < 3)]
I think you are forgetting about the border. Having a one-pixel-wide border on the Div will take away two pixels of total length. Therefore it will appear as though the div is two pixels shorter than it actually is.
Take a look at the mstring module for node.js.
This is a simple little module that lets you have multi-line strings in JavaScript.
Just do this:
var M = require('mstring')
var mystring = M(function(){/***
Ontario
Mining and
Forestry
Group
***/})
to get
mystring === "Ontario\nMining and\nForestry\nGroup"
And that's pretty much it.
How It Works
In Node.js, you can call the.toString
method of a function, and it will give you the source code of the function definition, including any comments. A regular expression grabs the content of the comment.Yes, it's a hack. Inspired by a throwaway comment from Dominic Tarr.
note: The module (as of 2012/13/11) doesn't allow whitespace before the closing ***/
, so you'll need to hack it in yourself.
Also, mod can be used like this:
int a = 7;
b = a % 2;
b
would equal 1. Because 7 % 2 = 1
.
I used IntelliJ to create my .jar, which included some unpacked jars from my libraries. One of these other jars had some signed stuff in the MANIFEST which prevented the .jar from being loaded. No warnings, or anything, just didn't work. Could not find or load main class
Removing the unpacked jar which contained the manifest fixed it.
This will keep its space, but not show anything;
opacity: 0.0;
This will hide the object fully, plus its (reserved) space;
display: none;
This is possible using this cross browser javascript implementation of the HTML5 saveAs
function: https://github.com/koffsyrup/FileSaver.js
If all you want to do is save text then the above script works in all browsers(including all versions of IE), using nothing but JS.
You can delete the archive files and executable binaries that go install
(or go get
) produces for a package with go clean -i importpath...
. These normally reside under $GOPATH/pkg
and $GOPATH/bin
, respectively.
Be sure to include ...
on the importpath, since it appears that, if a package includes an executable, go clean -i
will only remove that and not archive files for subpackages, like gore/gocode
in the example below.
Source code then needs to be removed manually from $GOPATH/src
.
go clean
has an -n
flag for a dry run that prints what will be run without executing it, so you can be certain (see go help clean
). It also has a tempting -r
flag to recursively clean dependencies, which you probably don't want to actually use since you'll see from a dry run that it will delete lots of standard library archive files!
A complete example, which you could base a script on if you like:
$ go get -u github.com/motemen/gore
$ which gore
/Users/ches/src/go/bin/gore
$ go clean -i -n github.com/motemen/gore...
cd /Users/ches/src/go/src/github.com/motemen/gore
rm -f gore gore.exe gore.test gore.test.exe commands commands.exe commands_test commands_test.exe complete complete.exe complete_test complete_test.exe debug debug.exe helpers_test helpers_test.exe liner liner.exe log log.exe main main.exe node node.exe node_test node_test.exe quickfix quickfix.exe session_test session_test.exe terminal_unix terminal_unix.exe terminal_windows terminal_windows.exe utils utils.exe
rm -f /Users/ches/src/go/bin/gore
cd /Users/ches/src/go/src/github.com/motemen/gore/gocode
rm -f gocode.test gocode.test.exe
rm -f /Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore/gocode.a
$ go clean -i github.com/motemen/gore...
$ which gore
$ tree $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
/Users/ches/src/go/pkg/darwin_amd64/github.com/motemen/gore
0 directories, 0 files
# If that empty directory really bugs you...
$ rmdir $GOPATH/pkg/darwin_amd64/github.com/motemen/gore
$ rm -rf $GOPATH/src/github.com/motemen/gore
Note that this information is based on the go
tool in Go version 1.5.1.
I don' know why but my Android Studio 0.8.14 goes crazy when I try to implement these solutions using Gradle. I admit my poor knowledge of this great build tool but what does Studio mutilate my project for? I manage to get it working this way: put android-support-v13.jar into 'libs' directory, then F4 on my project and add File dependency where I pointed android-support-v13.jar.
If you want to follow all the "best practices," there's a few things I'd recommend, some of which are touched on in other answers and comments to this question.
First, while it doesn't have too much of an affect on the specific question you asked, you did mention efficiency, and the best way to handle shared data in your application is to factor it out into a service.
I would personally recommend embracing AngularJS's promise system, which will make your asynchronous services more composable compared to raw callbacks. Luckily, Angular's $http
service already uses them under the hood. Here's a service that will return a promise that resolves to the data from the JSON file; calling the service more than once will not cause a second HTTP request.
app.factory('locations', function($http) {
var promise = null;
return function() {
if (promise) {
// If we've already asked for this data once,
// return the promise that already exists.
return promise;
} else {
promise = $http.get('locations/locations.json');
return promise;
}
};
});
As far as getting the data into your directive, it's important to remember that directives are designed to abstract generic DOM manipulation; you should not inject them with application-specific services. In this case, it would be tempting to simply inject the locations
service into the directive, but this couples the directive to that service.
A brief aside on code modularity: a directive’s functions should almost never be responsible for getting or formatting their own data. There’s nothing to stop you from using the $http service from within a directive, but this is almost always the wrong thing to do. Writing a controller to use $http is the right way to do it. A directive already touches a DOM element, which is a very complex object and is difficult to stub out for testing. Adding network I/O to the mix makes your code that much more difficult to understand and that much more difficult to test. In addition, network I/O locks in the way that your directive will get its data – maybe in some other place you’ll want to have this directive receive data from a socket or take in preloaded data. Your directive should either take data in as an attribute through scope.$eval and/or have a controller to handle acquiring and storing the data.
In this specific case, you should place the appropriate data on your controller's scope and share it with the directive via an attribute.
app.controller('SomeController', function($scope, locations) {
locations().success(function(data) {
$scope.locations = data;
});
});
<ul class="list">
<li ng-repeat="location in locations">
<a href="#">{{location.id}}. {{location.name}}</a>
</li>
</ul>
<map locations='locations'></map>
app.directive('map', function() {
return {
restrict: 'E',
replace: true,
template: '<div></div>',
scope: {
// creates a scope variable in your directive
// called `locations` bound to whatever was passed
// in via the `locations` attribute in the DOM
locations: '=locations'
},
link: function(scope, element, attrs) {
scope.$watch('locations', function(locations) {
angular.forEach(locations, function(location, key) {
// do something
});
});
}
};
});
In this way, the map
directive can be used with any set of location data--the directive is not hard-coded to use a specific set of data, and simply linking the directive by including it in the DOM will not fire off random HTTP requests.
These methods works on the locks and locks are associated with Object and not Threads. Hence, it is in Object class.
The methods wait(), notify() and notifyAll() are not only just methods, these are synchronization utility and used in communication mechanism among threads in Java.
For more detailed explanation, please visit : http://parameshk.blogspot.in/2013/11/why-wait-notify-and-notifyall-methods.html
As the code below shows it, it works.
public <T> ResponseWrapper<T> makeRequest(URI uri, final Class<T> clazz) {
ResponseEntity<ResponseWrapper<T>> response = template.exchange(
uri,
HttpMethod.POST,
null,
new ParameterizedTypeReference<ResponseWrapper<T>>() {
public Type getType() {
return new MyParameterizedTypeImpl((ParameterizedType) super.getType(), new Type[] {clazz});
}
});
return response;
}
public class MyParameterizedTypeImpl implements ParameterizedType {
private ParameterizedType delegate;
private Type[] actualTypeArguments;
MyParameterizedTypeImpl(ParameterizedType delegate, Type[] actualTypeArguments) {
this.delegate = delegate;
this.actualTypeArguments = actualTypeArguments;
}
@Override
public Type[] getActualTypeArguments() {
return actualTypeArguments;
}
@Override
public Type getRawType() {
return delegate.getRawType();
}
@Override
public Type getOwnerType() {
return delegate.getOwnerType();
}
}
I've been trying to do this for a while. Here is a script that changes to the same working directory, runs the command, and closes the terminal window.
#!/bin/sh
osascript <<END
tell application "Terminal"
do script "cd \"`pwd`\";$1;exit"
end tell
END
The jQuery plugin hoverIntent http://cherne.net/brian/resources/jquery.hoverIntent.html goes much further than the naive approaches listed here. While they certainly work, they might not necessarily behave how users expect.
The strongest reason to use hoverIntent is the timeout feature. It allows you to do things like prevent a menu from closing because a user drags their mouse slightly too far to the right or left before they click the item they want. It also provides capabilities for not activating hover events in a barrage and waits for focused hovering.
Usage example:
var config = {
sensitivity: 3, // number = sensitivity threshold (must be 1 or higher)
interval: 200, // number = milliseconds for onMouseOver polling interval
over: makeTall, // function = onMouseOver callback (REQUIRED)
timeout: 500, // number = milliseconds delay before onMouseOut
out: makeShort // function = onMouseOut callback (REQUIRED)
};
$("#demo3 li").hoverIntent( config )
Further explaination of this can be found on https://stackoverflow.com/a/1089381/37055
You can use deparse
and substitute
to get the name of a function argument:
myfunc <- function(v1) {
deparse(substitute(v1))
}
myfunc(foo)
[1] "foo"
Even though a bit old thread, for those who still looking for the differences:
Aside from layout (space) taken in Hidden and not taken in Collapsed, there is another difference.
If we have custom controls inside this 'Collapsed' main control, the next time we set it to Visible, it will "load" all custom controls. It will not pre-load when window is started.
As for 'Hidden', it will load all custom controls + main control which we set as hidden when the "window" is started.
You simply need to specify the gem name on the command line:
bundle update gem-name
I prefer to hide all code complexity in my services... so, I generally use something like this:
In my events.service.ts
async getEvents() {
const snapchot = await this.db.collection('events').ref.get();
return new Promise <Event[]> (resolve => {
const v = snapchot.docs.map(x => {
const obj = x.data();
obj.id = x.id;
return obj as Event;
});
resolve(v);
});
}
In my sth.page.ts
myList: Event[];
construct(private service: EventsService){}
async ngOnInit() {
this.myList = await this.service.getEvents();
}
Enjoy :)
You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/
You might be interested in the StringTokenizer class. However, the java docs advise that you use the .split method as StringTokenizer is a legacy class.
does the later approach save computation time and memory?
There is no big difference between those two examples that you provided. The first example cuts the video sequentially, in 2 steps, while the second example does it at the same time (using threads). No particular speed-up will be noticeable. You can read more about creating multiple outputs with FFmpeg
Further more, what you can use (in recent FFmpeg) is the stream segmenter muxer which can:
output streams to a number of separate files of nearly fixed duration. Output filename pattern can be set in a fashion similar to image2.
That is what I did and it helped me to find out what my Apache-PHP needed:
C:\Users\Admin>cd C:\wamp\bin\apache\apache2.4.9\bin
C:\wamp\bin\apache\apache2.4.9\bin>httpd -t
Syntax OK
C:\wamp\bin\apache\apache2.4.9\bin>httpd -k start
[Thu Apr 23 14:14:52.150189 2015] [mpm_winnt:error] [pid 3184:tid 112]
(OS 2)The system cannot find the file specified. : AH00436:
No installed service named "Apache2.4".
C:\wamp\bin\apache\apache2.4.9\bin>
The most simple solution:
Uninstall and reinstall WAMP (do not even try to set it up on top of existing installation - it would not help)
P.S.
If you wonder how did I get to this situation, here is the answer: I was trying to install WAMP and it throws me an error in the middle of installation saying:
httpd.exe - System Error
The program can't start because MSVCR110.dll is missing from your computer.
Try reinstalling the program to fix this problem.
OK
I got and installed Microsoft Visual C++ 2012 Redistributable from here http://www.microsoft.com/en-us/download/details.aspx?id=30679#
And it gave me the "dll" and the MYSQL started working, but not Apache. To make Apache to work I uninstalled and reinstalled WAMP.
Use SQL*Loader. It takes a little setting up, but if this isn't a one off, its worth it.
Create Table
SQL> create table ldr_test (id number(10) primary key, description varchar2(20));
Table created.
SQL>
Create CSV
oracle-2% cat ldr_test.csv
1,Apple
2,Orange
3,Pear
oracle-2%
Create Loader Control File
oracle-2% cat ldr_test.ctl
load data
infile 'ldr_test.csv'
into table ldr_test
fields terminated by "," optionally enclosed by '"'
( id, description )
oracle-2%
Run SQL*Loader command
oracle-2% sqlldr <username> control=ldr_test.ctl
Password:
SQL*Loader: Release 9.2.0.5.0 - Production on Wed Sep 3 12:26:46 2008
Copyright (c) 1982, 2002, Oracle Corporation. All rights reserved.
Commit point reached - logical record count 3
Confirm insert
SQL> select * from ldr_test;
ID DESCRIPTION
---------- --------------------
1 Apple
2 Orange
3 Pear
SQL>
SQL*Loader has alot of options, and can take pretty much any text file as its input. You can even inline the data in your control file if you want.
Here is a page with some more details -> SQL*Loader
According to Python3 documentation,python when divided by integer,will generate float despite expected to be integer.
For exclusively printing integer,use floor division method
.
Floor division is rounding off zero and removing decimal point. Represented by //
Hence,instead of 2/2 ,use 2//2
You can also import division from __future__
irrespective of using python2 or python3.
Hope it helps!
Sometimes this exception is caused by a bug in the support library implementation. Recently I had to downgrade from 26.1.0 to 25.4.0 to get rid of it.
You can use like this(Though the random number generator logic is not upto the mark)
public class WorkSheet {
HashMap<String,ArrayList<Integer>> map = new HashMap<String,ArrayList<Integer>>();
public static void main(String args[]) {
WorkSheet test = new WorkSheet();
test.inputData("mango", 5);
test.inputData("apple", 2);
test.inputData("grapes", 2);
test.inputData("peach", 3);
test.displayData();
}
public void displayData(){
for (Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
System.out.print(entry.getKey()+" | ");
for(int fruitNo : entry.getValue()){
System.out.print(fruitNo+" ");
}
System.out.println();
}
}
public void inputData(String name ,int number) {
Random rndData = new Random();
ArrayList<Integer> fruit = new ArrayList<Integer>();
for(int i=0 ; i<number ; i++){
fruit.add(rndData.nextInt(10));
}
map.put(name, fruit);
}
}
grapes | 7 5
apple | 9 5
peach | 5 5 8
mango | 4 7 1 5 5
I would like to add to what @Visionscaper says at the top:
Third --> First --> object --> Second --> object
In this case the interpreter doesnt filter out the object class because its duplicated, rather its because Second appears in a head position and doesnt appear in the tail position in a hierarchy subset. While object only appears in tail positions and is not considered a strong position in C3 algorithm to determine priority.
The linearisation(mro) of a class C, L(C), is the
Linearised Merge is done by selecting the common classes that appears as the head of lists and not the tail since order matters(will become clear below)
The linearisation of Third can be computed as follows:
L(O) := [O] // the linearization(mro) of O(object), because O has no parents
L(First) := [First] + merge(L(O), [O])
= [First] + merge([O], [O])
= [First, O]
// Similarly,
L(Second) := [Second, O]
L(Third) := [Third] + merge(L(First), L(Second), [First, Second])
= [Third] + merge([First, O], [Second, O], [First, Second])
// class First is a good candidate for the first merge step, because it only appears as the head of the first and last lists
// class O is not a good candidate for the next merge step, because it also appears in the tails of list 1 and 2,
= [Third, First] + merge([O], [Second, O], [Second])
// class Second is a good candidate for the second merge step, because it appears as the head of the list 2 and 3
= [Third, First, Second] + merge([O], [O])
= [Third, First, Second, O]
Thus for a super() implementation in the following code:
class First(object):
def __init__(self):
super(First, self).__init__()
print "first"
class Second(object):
def __init__(self):
super(Second, self).__init__()
print "second"
class Third(First, Second):
def __init__(self):
super(Third, self).__init__()
print "that's it"
it becomes obvious how this method will be resolved
Third.__init__() ---> First.__init__() ---> Second.__init__() --->
Object.__init__() ---> returns ---> Second.__init__() -
prints "second" - returns ---> First.__init__() -
prints "first" - returns ---> Third.__init__() - prints "that's it"
I would like to share an answer that also demonstrates approach using the Android SDK provided by the Ubuntu repository:
Install Android SDK
sudo apt-get install android-sdk
Export environmental variables
export ANDROID_HOME="/usr/lib/android-sdk/"
export PATH="${PATH}:${ANDROID_HOME}tools/:${ANDROID_HOME}platform-tools/"
I've seen that problem when I'm writing to a filesystem which doesn't (properly) handle times -- I think SMB shares or FAT or something.
What is your target filesystem?
cat filename | sort | uniq -c | awk -F" " '$1<2 {print $2}'
Deletes the duplicate lines using awk.
NOTE: Hopefully this changed in the latest version.
You cannot copy data between a MongoDB 4.0 mongod instance (regardless of the FCV value) and a MongoDB 3.4 and earlier mongod instance. https://docs.mongodb.com/v4.0/reference/method/db.copyDatabase/
ALERT: Hey folks just be careful while copying the database, if you don't want to mess up the different collections under single database.
The following shows you how to rename
> show dbs;
testing
games
movies
To rename you use the following syntax
db.copyDatabase("old db name","new db name")
Example:
db.copyDatabase('testing','newTesting')
Now you can safely delete the old db by the following way
use testing;
db.dropDatabase(); //Here the db **testing** is deleted successfully
Now just think what happens if you try renaming the new database name with existing database name
Example:
db.copyDatabase('testing','movies');
So in this context all the collections (tables) of testing will be copied to movies database.
I had a similar problem and solved it using list...not sure if this will help or not
classes = list(unique_labels(y_true, y_pred))
Use .lower()
- For example:
s = "Kilometer"
print(s.lower())
The official 2.x documentation is here: str.lower()
The official 3.x documentation is here: str.lower()
This code takes advantage of SIMD instructions to improve performance.
public static bool IsPositive(int n)
{
var v = new Vector<int>(n);
var result = Vector.GreaterThanAll(v, Vector<int>.Zero);
return result;
}
Excellent question. I've tackled this problem as well, and while I agree that "factories" (class-method constructors) are a good method, I would like to suggest another, which I've also found very useful:
Here's a sample (this is a read
method and not a constructor, but the idea is the same):
def read(self, str=None, filename=None, addr=0):
""" Read binary data and return a store object. The data
store is also saved in the interal 'data' attribute.
The data can either be taken from a string (str
argument) or a file (provide a filename, which will
be read in binary mode). If both are provided, the str
will be used. If neither is provided, an ArgumentError
is raised.
"""
if str is None:
if filename is None:
raise ArgumentError('Please supply a string or a filename')
file = open(filename, 'rb')
str = file.read()
file.close()
...
... # rest of code
The key idea is here is using Python's excellent support for named arguments to implement this. Now, if I want to read the data from a file, I say:
obj.read(filename="blob.txt")
And to read it from a string, I say:
obj.read(str="\x34\x55")
This way the user has just a single method to call. Handling it inside, as you saw, is not overly complex
Use the iFrame's .onload
function of JavaScript:
<iframe id="my_iframe" src="http://www.test.tld/">
<script type="text/javascript">
document.getElementById('my_iframe').onload = function() {
__doPostBack('ctl00$ctl00$bLogout','');
}
</script>
<!--OTHER STUFF-->
</iframe>
type in the terminal and it will solve the issue:
find . -type f | xargs -n 5 touch
make clean
clean
The thread is very old, but I came looking for answer here hence providing new solution.
With MongoDB version 3.6+, it is now possible to use the positional operator to update all items in an array. See official documentation here.
Following query would work for the question asked here. I have also verified with Java-MongoDB driver and it works successfully.
.update( // or updateMany directly, removing the flag for 'multi'
{"events.profile":10},
{$set:{"events.$[].handled":0}}, // notice the empty brackets after '$' opearor
false,
true
)
Hope this helps someone like me.
const path = require('path');
const express = require('express');
const app = new express();
app.use(express.static('/media'));
app.get('/', (req, res) => {
res.sendFile(path.resolve(__dirname, 'media/page/', 'index.html'));
});
app.listen(4000, () => {
console.log('App listening on port 4000')
})
SQL>Clear Screen (It is used the Clear The Screen FUlly in SQL Plus Window)
There really aren't any differences.
"
is processed as "
which is the decimal equivalent of &x22;
which is the ISO 8859-1 equivalent of "
.
The only reason you may be against using "
is because it was mistakenly omitted from the HTML 3.2 specification.
Otherwise it all boils down to personal preference.
My solution is similar to Payam's, except I am using
//older code
//postman.setGlobalVariable("currentDate", new Date().toLocaleDateString());
pm.globals.set("currentDate", new Date().toLocaleDateString());
If you hit the "3 dots" on the folder and click "Edit"
Then set Pre-Request Scripts for the all calls, so the global variable is always available.
In addition to adding @Transactional
on @Test
method, you also need to add @Rollback(false)
You can do a subquery where you first get the IDs of the top 10 ordered by priority and then update the ones that are on that sub query:
UPDATE messages
SET status=10
WHERE ID in (SELECT TOP (10) Id
FROM Table
WHERE status=0
ORDER BY priority DESC);
Add this option: -std=c++11
while compiling your code
g++ -std=c++11 my_cpp_code.cpp
It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.
You may use parseInt
:
int id = Integer.parseInt(jsonObj.get("id"));
or better and more directly the getInt method :
int id = jsonObj.getInt("id");
Google Drive has an extension to open MDB files.
I'm not sure how well BLOBs work because I couldn't get my images to display but all the text came up.
I hope this can help someone in the future.
You can use the Google Geocoding API, as said before, I had to do some work with this recently, I hope this helps:
<!DOCTYPE html>
<html>
<head>
<script src="https://maps.googleapis.com/maps/api/js?v=3.exp&sensor=false&libraries=places"></script>
<script type="text/javascript">
function initialize() {
var address = (document.getElementById('my-address'));
var autocomplete = new google.maps.places.Autocomplete(address);
autocomplete.setTypes(['geocode']);
google.maps.event.addListener(autocomplete, 'place_changed', function() {
var place = autocomplete.getPlace();
if (!place.geometry) {
return;
}
var address = '';
if (place.address_components) {
address = [
(place.address_components[0] && place.address_components[0].short_name || ''),
(place.address_components[1] && place.address_components[1].short_name || ''),
(place.address_components[2] && place.address_components[2].short_name || '')
].join(' ');
}
});
}
function codeAddress() {
geocoder = new google.maps.Geocoder();
var address = document.getElementById("my-address").value;
geocoder.geocode( { 'address': address}, function(results, status) {
if (status == google.maps.GeocoderStatus.OK) {
alert("Latitude: "+results[0].geometry.location.lat());
alert("Longitude: "+results[0].geometry.location.lng());
}
else {
alert("Geocode was not successful for the following reason: " + status);
}
});
}
google.maps.event.addDomListener(window, 'load', initialize);
</script>
</head>
<body>
<input type="text" id="my-address">
<button id="getCords" onClick="codeAddress();">getLat&Long</button>
</body>
</html>
Now this has also an autocomlpete function which you can see in the code, it fetches the address from the input and gets auto completed by the API while typing.
Once you have your address hit the button and you get your results via alert as required. Please also note this uses the latest API and it loads the 'places' library (when calling the API uses the 'libraries' parameter).
Hope this helps, and read the documentation for more information, cheers.
Edit #1: Fiddle
Yes, there is the workbench.action.gotoSymbol
command. On Windows and Linux it's set to CTRL+Shift+O by default.
If this command isn't available for the file types you are working with then you should take a look at the VSCode extensions. Not all languages support this feature.
Here is my opinion.
Query params are used as meta data to a request. They act as filter or modifier to an existing resource call.
Example:
/calendar/2014-08-08/events
should give calendar events for that day.
If you want events for a specific category
/calendar/2014-08-08/events?category=appointments
or if you need events of longer than 30 mins
/calendar/2014-08-08/events?duration=30
A litmus test would be to check if the request can still be served without an query params.
In Android Studios 2.1.1, the command-line Options is under "Build, Execution, Deployment">"Compiler"
If the .env
a file is missing, then there is another way to generate a .env file
You can download env.example, rename it to .env
and edit it. Just set up correct DB credentials etc.
Don't forget to When you use the php artisan key:generate
it will generate the new key to your .env
file
You can use this on iOS 5.0 and later: This no longer works.
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs://"]];
The integer passed to the constructor represents its initial capacity, i.e., the number of elements it can hold before it needs to resize its internal array (and has nothing to do with the initial number of elements in the list).
To initialize an list with 60 zeros you do:
List<Integer> list = new ArrayList<Integer>(Collections.nCopies(60, 0));
If you want to create a list with 60 different objects, you could use the Stream API with a Supplier
as follows:
List<Person> persons = Stream.generate(Person::new)
.limit(60)
.collect(Collectors.toList());
sudo apt-get install ia32-libs
I will start from a general point of view about tuples in Java and finish with an implication for your concrete problem.
1) The way tuples are used in non-generic languages is avoided in Java because they are not type-safe (e.g. in Python: tuple = (4, 7.9, 'python')
). If you still want to use something like a general purpose tuple (which is not recommended), you should use Object[]
or List<Object>
and cast the elements after a check with instanceof
to assure type-safety.
Usually, tuples in a certain setting are always used the same way with containing the same structure. In Java, you have to define this structure explicitly in a class
to provide well-defined, type-safe values and methods. This seems annoying and unnecessairy at first but prevents errors already at compile-time.
2) If you need a tuple containing the same (super-)classes Foo
, use Foo[]
, List<Foo>
, or List<? extends Foo>
(or the lists's immutable counterparts). Since a tuple is not of a defined length, this solution is equivalent.
3) In your case, you seem to need a Pair
(i.e. a tuple of well-defined length 2). This renders maerics's answer or one of the supplementary answers the most efficient since you can reuse the code in the future.
This problem got resolved by mentioning the package name
I moved my file Test_Steps.java which was under package stepDefinition
by just adding the package stepDefinition the problem got resolved
So this problem can occur when you have a package and you are not using in your class file.
Adding it has resolved the problem and the error was no longer appearing.
There is no boot.ini on a machine with just Vista installed.
How do you want to identify the drive/partition: by the windows drive letter it is mapped to (eg. c:\, d:) or by how its hardware signature (which bus, etc).
For the simple case check out GetSystemDirectory
If you have tsocks or proxychains installed and configured, you can
$ tsocks git clone <you_repository>
or
$ proxychains git clone <you_repository>
to make it shorter, I created a symbol link /usr/bin/p
for proxychains
, so I can use it like this
p git clone <you_repository>
and I can use it to proxy any command,
p <cmd-need-be-proxied>
by the way, proxychains is not updated for a long time, you may wanna try proxychians-ng
For those, like me, who did not have the possibility to use angular directive and were "stuck" outside of the angular scope, here is something that might help you.
After hours searching on the web and on the angular doc, I have created a class that compiles HTML, place it inside a targets, and binds it to a scope ($rootScope
if there is no $scope
for that element)
/**
* AngularHelper : Contains methods that help using angular without being in the scope of an angular controller or directive
*/
var AngularHelper = (function () {
var AngularHelper = function () { };
/**
* ApplicationName : Default application name for the helper
*/
var defaultApplicationName = "myApplicationName";
/**
* Compile : Compile html with the rootScope of an application
* and replace the content of a target element with the compiled html
* @$targetDom : The dom in which the compiled html should be placed
* @htmlToCompile : The html to compile using angular
* @applicationName : (Optionnal) The name of the application (use the default one if empty)
*/
AngularHelper.Compile = function ($targetDom, htmlToCompile, applicationName) {
var $injector = angular.injector(["ng", applicationName || defaultApplicationName]);
$injector.invoke(["$compile", "$rootScope", function ($compile, $rootScope) {
//Get the scope of the target, use the rootScope if it does not exists
var $scope = $targetDom.html(htmlToCompile).scope();
$compile($targetDom)($scope || $rootScope);
$rootScope.$digest();
}]);
}
return AngularHelper;
})();
It covered all of my cases, but if you find something that I should add to it, feel free to comment or edit.
Hope it will help.
You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.
gc .\file2.txt| Add-Content -Path .\file1.txt
Have a look at the examples below for a clearer understanding of the differences between the different operators:
> # Floating Division:
> 5/2
[1] 2.5
>
> # Integer Division:
> 5%/%2
[1] 2
>
> # Remainder:
> 5%%2
[1] 1
Like @CoolBeans mentioned, take a look at jUnit. Here is a short tutorial to get you started as well with jUnit 4.x
Finally, if you really want to learn more about testing and test-driven development (TDD) I recommend you take a look at the following book by Kent Beck: Test-Driven Development By Example.
For people who don't want to use Bouncy, and are trying some of the code included in other answers, I've found that the code works MOST of the time, but trips up on some RSA private strings, such as the one I've included below. By looking at the bouncy code, I tweaked the code provided by wprl to
RSAparams.D = ConvertRSAParametersField(D, MODULUS.Length);
RSAparams.DP = ConvertRSAParametersField(DP, P.Length);
RSAparams.DQ = ConvertRSAParametersField(DQ, Q.Length);
RSAparams.InverseQ = ConvertRSAParametersField(IQ, Q.Length);
private static byte[] ConvertRSAParametersField(byte[] bs, int size)
{
if (bs.Length == size)
return bs;
if (bs.Length > size)
throw new ArgumentException("Specified size too small", "size");
byte[] padded = new byte[size];
Array.Copy(bs, 0, padded, size - bs.Length, bs.Length);
return padded;
}
-----BEGIN RSA PRIVATE KEY-----
MIIEoQIBAAKCAQEAxCgWAYJtfKBVa6Px1Blrj+3Wq7LVXDzx+MiQFrLCHnou2Fvb
fxuDeRmd6ERhDWnsY6dxxm981vTlXukvYKpIZQYpiSzL5pyUutoi3yh0+/dVlsHZ
UHheVGZjSMgUagUCLX1p/augXltAjgblUsj8GFBoKJBr3TMKuR5TwF7lBNYZlaiR
k9MDZTROk6MBGiHEgD5RaPKA/ot02j3CnSGbGNNubN2tyXXAgk8/wBmZ4avT0U4y
5oiO9iwCF/Hj9gK/S/8Q2lRsSppgUSsCioSg1CpdleYzIlCB0li1T0flB51zRIpg
JhWRfmK1uTLklU33xfzR8zO2kkfaXoPTHSdOGQIDAQABAoIBAAkhfzoSwttKRgT8
sgUYKdRJU0oqyO5s59aXf3LkX0+L4HexzvCGbK2hGPihi42poJdYSV4zUlxZ31N2
XKjjRFDE41S/Vmklthv8i3hX1G+Q09XGBZekAsAVrrQfRtP957FhD83/GeKf3MwV
Bhe/GKezwSV3k43NvRy2N1p9EFa+i7eq1e5i7MyDxgKmja5YgADHb8izGLx8Smdd
+v8EhWkFOcaPnQRj/LhSi30v/CjYh9MkxHMdi0pHMMCXleiUK0Du6tnsB8ewoHR3
oBzL4F5WKyNHPvesYplgTlpMiT0uUuN8+9Pq6qsdUiXs0wdFYbs693mUMekLQ4a+
1FOWvQECgYEA7R+uI1r4oP82sTCOCPqPi+fXMTIOGkN0x/1vyMXUVvTH5zbwPp9E
0lG6XmJ95alMRhjvFGMiCONQiSNOQ9Pec5TZfVn3M/w7QTMZ6QcWd6mjghc+dGGE
URmCx8xaJb847vACir7M08AhPEt+s2C7ZokafPCoGe0qw/OD1fLt3NMCgYEA08WK
S+G7dbCvFMrBP8SlmrnK4f5CRE3pV4VGneWp/EqJgNnWwaBCvUTIegDlqS955yVp
q7nVpolAJCmlUVmwDt4gHJsWXSQLMXy3pwQ25vdnoPe97y3xXsi0KQqEuRjD1vmw
K7SXoQqQeSf4z74pFal4CP38U3pivvoE4MQmJeMCfyJFceWqQEUEneL+IYkqrZSK
7Y8urNse5MIC3yUlcose1cWVKyPh4RCEv2rk0U1gKqX29Jb9vO2L7RflAmrLNFuA
J+72EcRxsB68RAJqA9VHr1oeAejQL0+JYF2AK4dJG/FsvvFOokv4eNU+FBHY6Tzo
k+t63NDidkvb5jIF6lsCgYEAlnQ08f5Y8Z9qdCosq8JpKYkwM+kxaVe1HUIJzqpZ
X24RTOL3aa8TW2afy9YRVGbvg6IX9jJcMSo30Llpw2cl5xo21Dv24ot2DF2gGN+s
peFF1Z3Naj1Iy99p5/KaIusOUBAq8pImW/qmc/1LD0T56XLyXekcuK4ts6Lrjkit
FaMCgYAusOLTsRgKdgdDNI8nMQB9iSliwHAG1TqzB56S11pl+fdv9Mkbo8vrx6g0
NM4DluCGNEqLZb3IkasXXdok9e8kmX1en1lb5GjyPbc/zFda6eZrwIqMX9Y68eNR
IWDUM3ckwpw3rcuFXjFfa+w44JZVIsgdoGHiXAdrhtlG/i98Rw==
-----END RSA PRIVATE KEY-----
we solve this problem without using regex this query replace only exact match string.
update employee set
employee_firstname =
trim(REPLACE(concat(" ",employee_firstname," "),' jay ',' abc '))
Example:
emp_id employee_firstname
1 jay
2 jay ajay
3 jay
After executing query result:
emp_id employee_firstname
1 abc
2 abc ajay
3 abc
How about using good(?) old goto
?
:loop
echo Ooops
goto loop
See also this for a more useful example.
I think @Flo254 chained $salt
to $password1
and stored them to $hashed
variable. $hashed
variable goes inside INSERT
query with $salt
.
You need to do two things:
The code:
dtt$model <- factor(dtt$model, levels=c("mb", "ma", "mc"), labels=c("MBB", "MAA", "MCC"))
library(ggplot2)
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha = 0.35, linetype=0)+
geom_line(aes(linetype=model), size = 1) +
geom_point(aes(shape=model), size=4) +
theme(legend.position=c(.6,0.8)) +
theme(legend.background = element_rect(colour = 'black', fill = 'grey90', size = 1, linetype='solid')) +
scale_linetype_discrete("Model 1") +
scale_shape_discrete("Model 1") +
scale_colour_discrete("Model 1")
However, I think this is really ugly as well as difficult to interpret. It's far better to use facets:
ggplot(dtt, aes(x=year, y=V, group = model, colour = model, ymin = lower, ymax = upper)) +
geom_ribbon(alpha=0.2, colour=NA)+
geom_line() +
geom_point() +
facet_wrap(~model)
One of Androids powerful feature is the AsyncTask class.
To work with it, you have to first extend it and override doInBackground
(...).
doInBackground
automatically executes on a worker thread, and you can add some
listeners on the UI Thread to get notified about status update, those functions are
called: onPreExecute()
, onPostExecute()
and onProgressUpdate()
You can find a example here.
Refer to below post for other alternatives:
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!
With Spring you can do:
String path = new UrlPathHelper().getPathWithinApplication(request);
!important
, after your CSS declaration.
div {
color: blue !important;
/* This Is Now Working */
}
The best answer here is too long. I cannot comment so I added my answer.
Based on all the responses and CS231n notes, allow me to summarise:
def softmax(x, axis):
x -= np.max(x, axis=axis, keepdims=True)
return np.exp(x) / np.exp(x).sum(axis=axis, keepdims=True)
Usage:
x = np.array([[1, 0, 2,-1],
[2, 4, 6, 8],
[3, 2, 1, 0]])
softmax(x, axis=1).round(2)
Output:
array([[0.24, 0.09, 0.64, 0.03],
[0. , 0.02, 0.12, 0.86],
[0.64, 0.24, 0.09, 0.03]])
You can use like bellow:
(( var0 = var1<98?9:21 ))
the same as
if [ "$var1" -lt 98 ]; then
var0=9
else
var0=21
fi
extends
condition?result-if-true:result-if-false
I found the interested thing on the book "Advanced Bash-Scripting Guide"
I have a blog post on how to increase the file size for asp upload control.
From the post:
By default, the FileUpload control allows a maximum of 4MB file to be uploaded and the execution timeout is 110 seconds. These properties can be changed from within the web.config file’s httpRuntime section. The maxRequestLength property determines the maximum file size that can be uploaded. The executionTimeout property determines the maximum time for execution.
None of the Pythonic solutions worked for me.
It turned out that proc.stdout.read()
or similar may block forever.
Therefore, I use tee
like this:
subprocess.run('./my_long_running_binary 2>&1 | tee -a my_log_file.txt && exit ${PIPESTATUS}', shell=True, check=True, executable='/bin/bash')
This solution is convenient if you are already using shell=True
.
${PIPESTATUS}
captures the success status of the entire command chain (only available in Bash).
If I omitted the && exit ${PIPESTATUS}
, then this would always return zero since tee
never fails.
unbuffer
might be necessary for printing each line immediately into the terminal, instead of waiting way too long until the "pipe buffer" gets filled.
However, unbuffer swallows the exit status of assert (SIG Abort)...
2>&1
also logs stderror to the file.
Or you can just include the SELECT statement in the SQL that's invoking the trigger, so its passed in as one of the columns in the trigger row(s). As long as you're certain it will infallibly return only one row (hence one value). (And, of course, it must not return a value that interacts with the logic in the trigger, but that's true in any case.)
I ran into this problem a few times. Many of the solutions will run the rm
command for each individual file that needs to be deleted. This is very inefficient:
find . -name "*.pdf" -print0 | xargs -0 rm -rf
I ended up writing a python script to delete the files based on the first 4 characters in the file-name:
import os
filedir = '/tmp/' #The directory you wish to run rm on
filelist = (os.listdir(filedir)) #gets listing of all files in the specified dir
newlist = [] #Makes a blank list named newlist
for i in filelist:
if str((i)[:4]) not in newlist: #This makes sure that the elements are unique for newlist
newlist.append((i)[:4]) #This takes only the first 4 charcters of the folder/filename and appends it to newlist
for i in newlist:
if 'tmp' in i: #If statment to look for tmp in the filename/dirname
print ('Running command rm -rf '+str(filedir)+str(i)+'* : File Count: '+str(len(os.listdir(filedir)))) #Prints the command to be run and a total file count
os.system('rm -rf '+str(filedir)+str(i)+'*') #Actual shell command
print ('DONE')
This worked very well for me. I was able to clear out over 2 million temp files in a folder in about 15 minutes. I commented the tar out of the little bit of code so anyone with minimal to no python knowledge can manipulate this code.
Try Run This Query
ALTER TABLE tablename AUTO_INCREMENT = value;
Or Try This Query For The Reset Auto Increment
ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL;
And Set Auto Increment Then Run This Query
ALTER TABLE `tablename` CHANGE `id` `id` INT(10) UNSIGNED NOT NULL AUTO_INCREMENT;
For a quick solution, I usually do like this.
This approach will allow the user to enter date in any format they like in the textbox, and finally format in mm/dd/yyyy format when he is done editing. So it is quite flexible:
Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)
If TextBox1.Text <> "" Then
If IsDate(TextBox1.Text) Then
TextBox1.Text = Format(TextBox1.Text, "mm/dd/yyyy")
Else
MsgBox "Please enter a valid date!"
Cancel = True
End If
End If
End Sub
However, I think what Sid developed is a much better approach - a full fledged date picker control.
Here is a solution that worked for me.
function calduedate(ndays){
var newdt = new Date(); var chrday; var chrmnth;
newdt.setDate(newdt.getDate() + parseInt(ndays));
var newdate = newdt.getFullYear();
if(newdt.getMonth() < 10){
newdate = newdate+'-'+'0'+newdt.getMonth();
}else{
newdate = newdate+'-'+newdt.getMonth();
}
if(newdt.getDate() < 10){
newdate = newdate+'-'+'0'+newdt.getDate();
}else{
newdate = newdate+'-'+newdt.getDate();
}
alert("newdate="+newdate);
}
Just call the script using something like python2.7 or python2 instead of just python.
So:
python2 myscript.py
instead of:
python myscript.py
What you could alternatively do is to replace the symbolic link "python" in /usr/bin which currently links to python3 with a link to the required python2/2.x executable. Then you could just call it as you would with python 3.
It can also be achieved using below code.
DataSet data = JsonConvert.DeserializeObject<DataSet>(json);
To parse a DateTime, use one of the following methods:
Alternatively, you may use try-parse pattern:
Read more about Custom Date and Time Format Strings.
To return a DateTime as a string in "yyyyMMdd" format, you may use ToString
method.
string date = DateTime.ToString("yyyyMMdd");
In your case, assuming you don't want to handle scenario when date is different format or misssing, it would be most convenient to use ParseExact
:
string dateToParse = "20170506";
DateTime parsedDate = DateTime.ParseExact(dateToParse,
"yyyyMMdd",
CultureInfo.InvariantCulture);
You may remove the dot .
from the double you are trying to get the decimals from using the Remove()
function after converting the double to string so that you could do the operations required on it
Consider having a double _Double
of value of 0.66781
, the following code will only show the numbers after the dot .
which are 66781
double _Double = 0.66781; //Declare a new double with a value of 0.66781
string _Decimals = _Double.ToString().Remove(0, _Double.ToString().IndexOf(".") + 1); //Remove everything starting with index 0 and ending at the index of ([the dot .] + 1)
Another Solution
You may use the class Path
as well which performs operations on string instances in a cross-platform manner
double _Double = 0.66781; //Declare a new double with a value of 0.66781
string Output = Path.GetExtension(D.ToString()).Replace(".",""); //Get (the dot and the content after the last dot available and replace the dot with nothing) as a new string object Output
//Do something
One simple thing you could do is abstract the test inside a function.
local function isempty(s)
return s == nil or s == ''
end
if isempty(foo) then
foo = "default value"
end
If you get this compilation error, it means that you have not included the servlet jar in the classpath. The correct way to include this jar is to add the Server Runtime jar to your eclipse project. You should follow the steps below to address this issue: You can download the servlet-api.jar from here http://www.java2s.com/Code/Jar/s/Downloadservletapijar.htm
Save it in directory. Right click on project -> go to properties->Buildpath and follow the steps.
_x000D_
Note: The jar which are shown in the screen are not correct jar.
you can follow the step to configure.
For those who even yet have the problem, try enabling "Build project automatically" in the Java compiler settings and see if that makes a difference as it worked for me.
You can type them manually but the editor will assist you.
http://developer.android.com/reference/android/Manifest.permission.html
You can see the snap sot below.
As soon as you type "a" inside the quotes you get a list of permissions and also hint to move caret up and down to select the same.
The built-in node.js module fs will do it either asynchronously or synchronously depending on your needs.
You can load it using var fs = require('fs');
fs.readFile('./content.json', (err, data) => {
if (err)
console.log(err);
else {
var json = JSON.parse(data);
//your code using json object
}
})
var json = JSON.parse(fs.readFileSync('./content.json').toString());
there is one more difference, but only in internet explorer. It occurs when you mix HTML and SVG. if the parent is the 'other' of those two, then .parentNode gives the parent, while .parentElement gives undefined.
Hmmm $array = json_decode($json, true);
will make your string an array which is easy to print nicely with print_r($array, true);
But if you really want to prettify your json... Check this out
From your code, It looks like your file contains code that makes get request to localhost (127.0.0.1:8000).
The problem might be you have not created server on your local machine which listens to port 8000.
For that you have to set up server on localhost which can serve your request.
Create server.js
var express = require('express');
var app = express();
app.get('/', function (req, res) {
res.send('Hello World!'); // This will serve your request to '/'.
});
app.listen(8000, function () {
console.log('Example app listening on port 8000!');
});
Run server.js : node server.js
Run file that contains code to make request.
import java.io.File;
public class Test {
public static void main( String [] args ) {
File actual = new File(".");
for( File f : actual.listFiles()){
System.out.println( f.getName() );
}
}
}
It displays indistinctly files and folders.
See the methods in File class to order them or avoid directory print etc.
$()
means: "first evaluate this, and then evaluate the rest of the line".
Ex :
echo $(pwd)/myFile.txt
will be interpreted as
echo /my/path/myFile.txt
On the other hand ${}
expands a variable.
Ex:
MY_VAR=toto
echo ${MY_VAR}/myFile.txt
will be interpreted as
echo toto/myFile.txt
Why can't I use it as
bash$ while ((i=0;i<10;i++)); do echo $i; done
I'm afraid the answer is just that the bash syntax for while
just isn't the same as the syntax for for
.
There is a newer version of the Apache Commons Lang library and it uses a different package name (org.apache.commons.lang3). The StringEscapeUtils
now has different static methods for escaping different types of documents (http://commons.apache.org/proper/commons-lang/javadocs/api-3.0/index.html). So to escape HTML version 4.0 string:
import static org.apache.commons.lang3.StringEscapeUtils.escapeHtml4;
String output = escapeHtml4("The less than sign (<) and ampersand (&) must be escaped before using them in HTML");
The error message is quite descriptive, try:
ALTER TABLE MyTable ADD Stage INT NOT NULL DEFAULT '-';
+=
is the in-place addition operator.
It's the same as doing cnt = cnt + 1
. For example:
>>> cnt = 0
>>> cnt += 2
>>> print cnt
2
>>> cnt += 42
>>> print cnt
44
The operator is often used in a similar fashion to the ++
operator in C-ish languages, to increment a variable by one in a loop (i += 1
)
There are similar operator for subtraction/multiplication/division/power and others:
i -= 1 # same as i = i - 1
i *= 2 # i = i * 2
i /= 3 # i = i / 3
i **= 4 # i = i ** 4
The +=
operator also works on strings, for example:
>>> s = "Hi"
>>> s += " there"
>>> print s
Hi there
People tend to recommend against doing this for performance reason, but for the most scripts this really isn't an issue. To quote from the "Sequence Types" docs:
- If s and t are both strings, some Python implementations such as CPython can usually perform an in-place optimization for assignments of the form s=s+t or s+=t. When applicable, this optimization makes quadratic run-time much less likely. This optimization is both version and implementation dependent. For performance sensitive code, it is preferable to use the str.join() method which assures consistent linear concatenation performance across versions and implementations.
The str.join() method refers to doing the following:
mysentence = []
for x in range(100):
mysentence.append("test")
" ".join(mysentence)
..instead of the more obvious:
mysentence = ""
for x in range(100):
mysentence += " test"
The problem with the later is (aside from the leading-space), depending on the Python implementation, the Python interpreter will have to make a new copy of the string in memory every time you append (because strings are immutable), which will get progressively slower the longer the string to append is.. Whereas appending to a list then joining it together into a string is a consistent speed (regardless of implementation)
If you're doing basic string manipulation, don't worry about it. If you see a loop which is basically just appending to a string, consider constructing an array, then "".join()
'ing it.
You can also use it with attributes such as disabled="disabled" on the form fields etc. like so:
$("#change_password").click(function() {
var target = $(this).attr("rel");
if($("#" + target).attr("disabled")) {
$("#" + target).attr("disabled", false);
} else {
$("#" + target).attr("disabled", true);
}
});
The "rel" attribute stores the id of the target input field.
TEXT
and BLOB
may by stored off the table with the table just having a pointer to the location of the actual storage. Where it is stored depends on lots of things like data size, columns size, row_format, and MySQL version.
VARCHAR
is stored inline with the table. VARCHAR
is faster when the size is reasonable, the tradeoff of which would be faster depends upon your data and your hardware, you'd want to benchmark a real-world scenario with your data.
There is no feature in scp to filter files. For "advanced" stuff like this, I recommend using rsync:
rsync -av --exclude '*.svn' user@server:/my/dir .
(this line copy rsync from distant folder to current one)
Recent versions of rsync tunnel over an ssh connection automatically by default.
Also, this might help finding the actual location the btsnoop_hci.log is being saved:
adb shell "cat /etc/bluetooth/bt_stack.conf | grep FileName"
1 byte may hold 1 character. For Example: Refer Ascii values for each character & convert into binary. This is how it works.
value 255 is stored as (11111111) base 2. Visit this link for knowing more about binary conversion. http://acc6.its.brooklyn.cuny.edu/~gurwitz/core5/nav2tool.html
Size of Tiny Int = 1 Byte ( -128 to 127)
Int = 4 Bytes (-2147483648 to 2147483647)
try:
Activity parentActivity = this.getParent();
if (parentActivity != null)
{
View landmarkEditNameView = (EditText) parentActivity.findViewById(R.id. landmark_name_dialog_edit);
}
The HTTP 502 "Bad Gateway" response is generated when Apache web server does not receive a valid HTTP response from the upstream server, which in this case is your Tomcat web application.
Some reasons why this might happen:
If the problem is related to timeout settings, you may be able to resolve it by investigating the following:
Most modern devices support the tel: scheme. So use <a href="tel:555-555-5555">555-555-5555</a>
and you should be good to go.
If you want to use it for an image, the <a>
tag can handle the <img/>
placed in it just like other normal situations with : <a href="tel:555-555-5555"><img src="path/to/phone/icon.jpg" /></a>
You can actually use CHAR
(length of hash) to define your datatype for MySQL because each hashing algorithm will always evaluate out to the same number of characters. For example, SHA1
always returns a 40-character hexadecimal number.
[tup for tup in a if tup[0] == 1]
You can't pull in blocks from an included file into a child template to override the parent template's blocks. However, you can specify a parent in a variable and have the base template specified in the context.
From the documentation:
{% extends variable %} uses the value of variable. If the variable evaluates to a string, Django will use that string as the name of the parent template. If the variable evaluates to a Template object, Django will use that object as the parent template.
Instead of separate "page1.html" and "page2.html", put {% extends base_template %}
at the top of "commondata.html". And then in your view, define base_template
to be either "base1.html" or "base2.html".
I didn't want to reinstall everything because I have so many SDK versions installed and my development environment is set up just right. Getting it set up again takes way too long.
What worked for me was deleting, then re-creating the Android Virtual Device, being certain to put in a value for SD Card Size (I used 200 MiB).
while the above does fix the problem temporarily, it is recurring. I just tried my application within Android Studio and saw this in the output log which I did not notice before in Eclipse:
"/Applications/Android Studio.app/sdk/tools/emulator" -avd AVD_for_Nexus_S_by_Google -netspeed full -netdelay none
WARNING: Data partition already in use. Changes will not persist!
WARNING: SD Card image already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/sdcard.img
ko:Snapshot storage already in use: /Users/[user]/.android/avd/AVD_for_Nexus_S_by_Google.avd/snapshots.img
I suspect that changes to the log are not saving to the SD Card, so when LogCat tries to access the logs, they aren't there, causing the error message. The act of deleting the AVD and re-creating it removes the files, and the next launch is a fresh launch, allowing LogCat to access the virtual SD Card.
Use CSS3 PIE, which emulates some CSS3 properties in older versions of IE.
It supports box-shadow
(except for the inset
keyword).
Two ways:
1.
for row in session.execute(session.query(User).statement):
print(dict(row))
2.
selected_columns = User.__table__.columns
rows = session.query(User).with_entities(*selected_columns).all()
for row in rows :
print(row._asdict())
It's a reserved keyword (like return, filter, function, break).
Also, as per Section 7.6.4 of Bruce Payette's Powershell in Action:
But what happens when you want a script to exit from within a function defined in that script? ... To make this easier, Powershell has the exit keyword.
Of course, as other have pointed out, it's not hard to do what you want by wrapping exit in a function:
PS C:\> function ex{exit}
PS C:\> new-alias ^D ex
It looks like you're passing in Null for every argument except for PropertyValueID and DropDownOptionID, right? I don't think any of your IF statements will fire if only these two values are not-null. In short, I think you have a logic error.
Other than that, I would suggest two things...
First, instead of testing for NULL, use this kind syntax on your if statements (it's safer)...
ELSE IF ISNULL(@UnitValue, 0) != 0 AND ISNULL(@UnitOfMeasureID, 0) = 0
Second, add a meaningful PRINT statement before each UPDATE. That way, when you run the sproc in MSSQL, you can look at the messages and see how far it's actually getting.
ArrayDeque
is probably the fastest object-based queue in the JDK; Trove has the TIntQueue
interface, but I don't know where its implementations live.
This should get you there every single time.
background-image: url(<%= asset_data_uri 'transparent_2x2.png'%>);
A very short way to do it is just right click on the activity_main.xml design background and select convert view then select Relativealayout. Your code in Xml Text will auto. Change. Goodluck
The only way that cleanly solved this issue for me (.NET 4.6.1) was to not only add a Nuget reference to System.Net.Http V4.3.4 for the project that actually used System.Net.Http, but also to the startup project (a test project in my case).
(Which is strange, because the correct System.Net.Http.dll existed in the bin directory of the test project and the .config assemblyBingings looked OK, too.)
I have resolve the problem by using the command:
- Go to: C:\Users\ [PC NAME] \AppData\Local\Android\sdk\tools\bin\ (If the folder is not available then download the android SDK first, or you can install it from the android studio installation process.)
- Shift+Left click and Press W,then Enter to open CMD on the folder path
- Type in the cmd: sdkmanager --licenses
- Once press enter, you need to accept all the licenses by pressing y
CHECKING THE LICENSES
- Go to: C:\Users[PC NAME]\AppData\Local\Android\sdk\
- Check the folder named licenses
android-googletv-license
android-sdk-license
android-sdk-preview-license
google-gdk-license
intel-android-extra-license
mips-android-sysimage-license
WAS TESTED ON CORDOVA USING THE COMMAND:
cordova build android
-- UPDATE NEW FOLDER PATH --
Open Android Studio, Tools > Sdk Manager > Android SDK Command-Line Tools (Just Opt-in)
SDKManager will be store in :
- Go to C:\Users\ [PC NAME] \AppData\Local\Android\Sdk\cmdline-tools\latest\bin
- Type in the cmd: sdkmanager --licenses
Documentation to using the Android SDK: https://developer.android.com/studio/command-line/sdkmanager.html
Based nodejs document, http://nodejs.org/api/stream.html#stream_event_finish,
it should handle writableStream's finish
event.
var writable = getWriteable();
var readable = getReadable();
readable.pipe(writable);
writable.on('finish', function(){ ... });
You shouldn't be setting the value of the input through refs.
Take a look at the documentation for controlled form components here - https://facebook.github.io/react/docs/forms.html#controlled-components
In a nutshell
<input value={this.state.value} onChange={(e) => this.setState({value: e.target.value})} />
Then you will be able to control the disabled state by using disabled={!this.state.value}
The size_t type is the type returned by the sizeof operator. It is an unsigned integer capable of expressing the size in bytes of any memory range supported on the host machine. It is (typically) related to ptrdiff_t in that ptrdiff_t is a signed integer value such that sizeof(ptrdiff_t) and sizeof(size_t) are equal.
When writing C code you should always use size_t whenever dealing with memory ranges.
The int type on the other hand is basically defined as the size of the (signed) integer value that the host machine can use to most efficiently perform integer arithmetic. For example, on many older PC type computers the value sizeof(size_t) would be 4 (bytes) but sizeof(int) would be 2 (byte). 16 bit arithmetic was faster than 32 bit arithmetic, though the CPU could handle a (logical) memory space of up to 4 GiB.
Use the int type only when you care about efficiency as its actual precision depends strongly on both compiler options and machine architecture. In particular the C standard specifies the following invariants: sizeof(char) <= sizeof(short) <= sizeof(int) <= sizeof(long) placing no other limitations on the actual representation of the precision available to the programmer for each of these primitive types.
Note: This is NOT the same as in Java (which actually specifies the bit precision for each of the types 'char', 'byte', 'short', 'int' and 'long').
You cannot play two animations since the attribute can be defined only once. Rather why don't you include the second animation in the first and adjust the keyframes to get the timing right?
.image {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
left: 50%;_x000D_
width: 120px;_x000D_
height: 120px;_x000D_
margin:-60px 0 0 -60px;_x000D_
-webkit-animation:spin-scale 4s linear infinite;_x000D_
}_x000D_
_x000D_
@-webkit-keyframes spin-scale { _x000D_
50%{_x000D_
transform: rotate(360deg) scale(2);_x000D_
}_x000D_
100% { _x000D_
transform: rotate(720deg) scale(1);_x000D_
} _x000D_
}
_x000D_
<img class="image" src="http://makeameme.org/media/templates/120/grumpy_cat.jpg" alt="" width="120" height="120">
_x000D_
This isn't a direct answer to the question, but I had the same problem. I installed VSFTPD on my Ubuntu Server VPS. I could upload files, but every file I uploaded didn't have execution permissions (all files had rights "600"). These posts explain explain exactly what you have to do to configure your VSFTPD to set default rights on your files:
http://blog.keithclark.co.uk/wp-content/uploads/2012/11/ie-media-block-tests.php
I used @media \0screen {}
and it works fine for me in REAL IE8.
In the Azure CLI (I use GNU/Linux):
$ azure login # add "-e AzureChinaCloud" if you're using Azure China
This will ask you to login via https://aka.ms/devicelogin or https://aka.ms/deviceloginchina
$ azure account show
info: Executing command account show
data: Name : BizSpark Plus
data: ID : aZZZZZZZ-YYYY-HHHH-GGGG-abcdef569123
data: State : Enabled
data: Tenant ID : 0XXXXXXX-YYYY-HHHH-GGGG-123456789123
data: Is Default : true
data: Environment : AzureCloud
data: Has Certificate : No
data: Has Access Token : Yes
data: User name : [email protected]
data:
info: account show command OK
or simply:
azure account show --json | jq -r '.[0].tenantId'
or the new az:
az account show --subscription a... | jq -r '.tenantId'
az account list | jq -r '.[].tenantId'
I hope it helps
You will want to check out Image.getScaledInstance(), and more in this answer: How to improve the performance of g.drawImage() method for resizing images
It fires. Check demo http://jsfiddle.net/yeyene/kbAk3/
$("#inline_content input[name='type']").click(function(){
alert('You clicked radio!');
if($('input:radio[name=type]:checked').val() == "walk_in"){
alert($('input:radio[name=type]:checked').val());
//$('#select-table > .roomNumber').attr('enabled',false);
}
});
The simplest:
int main()
{
const char* str = "hello";
for (const char* p = str; *p; ++p)
{
printf("%02x", *p);
}
printf("\n");
return 0;
}
final
variables)Lock
API ]A Lock provides exclusive access to a shared resource: only one thread at a time can acquire the lock and all access to the shared resource requires that the lock be acquired first.
Sample code to use ReentrantLock
which implements Lock
interface
class X {
private final ReentrantLock lock = new ReentrantLock();
// ...
public void m() {
lock.lock(); // block until condition holds
try {
// ... method body
} finally {
lock.unlock()
}
}
}
Advantages of Lock over Synchronized(this)
The use of synchronized methods or statements forces all lock acquisition and release to occur in a block-structured way.
Lock implementations provide additional functionality over the use of synchronized methods and statements by providing
tryLock()
)lockInterruptibly()
)tryLock(long, TimeUnit)
).A Lock class can also provide behavior and semantics that is quite different from that of the implicit monitor lock, such as
Have a look at this SE question regarding various type of Locks
:
You can achieve thread safety by using advanced concurrency API instead of Synchronied blocks. This documentation page provides good programming constructs to achieve thread safety.
Lock Objects support locking idioms that simplify many concurrent applications.
Executors define a high-level API for launching and managing threads. Executor implementations provided by java.util.concurrent provide thread pool management suitable for large-scale applications.
Concurrent Collections make it easier to manage large collections of data, and can greatly reduce the need for synchronization.
Atomic Variables have features that minimize synchronization and help avoid memory consistency errors.
ThreadLocalRandom (in JDK 7) provides efficient generation of pseudorandom numbers from multiple threads.
Refer to java.util.concurrent and java.util.concurrent.atomic packages too for other programming constructs.
You can't show dialog box ON SERVER from ASP.NET application, well of course tehnically you can do that but it makes no sense since your user is using browser and it can't see messages raised on server. You have to understand how web sites work, server side code (ASP.NET in your case) produces html, javascript etc on server and then browser loads that content and displays it to the user, so in order to present modal message box to the user you have to use Javascript, for example alert function.
Here is the example for asp.net :
This worked for me:
ActiveWorkbook.refreshall
ActiveWorkbook.Save
When you save the workbook it's necessary to complete the refresh.
onClick={this.handleRemove.bind(this, id)}
reason: if you are looking at a column of data with a time stamp, the _MOST_IMPORTANT_ bit of information is the year. If data has been in the db for ten years, that's important to know. so year comes first.
it makes sense that month would come next, then day, hour, minute. Objectively, these are the most logical sequence for time data to be displayed.
it also makes sense that if you are going to display the data by default, you should display only the most significant portion of the data, so by default, only Y-M-D. everything else CAN be displayed, but it does not clutter your sql report by default.
Ordering by date is logical if you display Y-M-D because it is sequential. Computers are good at sequential, and it looks logical.
finally. Your bias to want M-D-Y is your bias. Not everyone even in the US uses this format. So use the most logical format and don't be outraged when others decide to be logical by default.
(I am US born, and I do not represent Oracle. I can, however, think for myself)
This works for me. Take your vector v
length(summary(as.factor(v),maxsum=50000))
Comment: set maxsum to be large enough to capture the number of unique values
or with the magrittr
package
v %>% as.factor %>% summary(maxsum=50000) %>% length
One thing you can do is to set your axis range by yourself by using matplotlib.pyplot.axis.
matplotlib.pyplot.axis
from matplotlib import pyplot as plt
plt.axis([0, 10, 0, 20])
0,10 is for x axis range. 0,20 is for y axis range.
or you can also use matplotlib.pyplot.xlim or matplotlib.pyplot.ylim
matplotlib.pyplot.ylim
plt.ylim(-2, 2)
plt.xlim(0,10)
If you want to write the output to a file you can use the stdout-argument of subprocess.call
.
It takes None
, subprocess.PIPE
, a file object or a file descriptor. The first is the default, stdout is inherited from the parent (your script). The second allows you to pipe from one command/process to another. The third and fourth are what you want, to have the output written to a file.
You need to open a file with something like open
and pass the object or file descriptor integer to call
:
f = open("blah.txt", "w")
subprocess.call(["/home/myuser/run.sh", "/tmp/ad_xml", "/tmp/video_xml"], stdout=f)
I'm guessing any valid file-like object would work, like a socket (gasp :)), but I've never tried.
As marcog mentions in the comments you might want to redirect stderr as well, you can redirect this to the same location as stdout with stderr=subprocess.STDOUT
. Any of the above mentioned values works as well, you can redirect to different places.
<a href="http://www.google.com" target="_blank">
<img width="220" height="250" border="0" align="center" src=""/>
</a>
If you are still trying to put files relative to your executable instead of in the temp directory, you need to copy it yourself. This is how I ended up getting it done.
https://stackoverflow.com/a/59415662/999943
You add a step in the spec file that does a filesystem copy to the DISTPATH variable.
Hope that helps.
To update Angular CLI to a new version, you must update both the global package and your project's local package.
Global package:
npm uninstall -g @angular/cli
npm cache clean
# if npm version is > 5 then use `npm cache verify` to avoid errors (or to avoid using --force)
npm install -g @angular/cli@latest
Local project package:
rm -rf node_modules dist # use rmdir /S/Q node_modules dist in Windows Command Prompt; use rm -r -fo node_modules,dist in Windows PowerShell
npm install --save-dev @angular/cli@latest
npm install
Source: Github
Open the httpd.conf file and search for
"rewrite"
, then remove
"#"
at the starting of the line,so the line looks like.
LoadModule rewrite_module modules/mod_rewrite.so
then restart the wamp.
We've released EAP to dotCover and will be releasing the beta version soon.
The unix setup should be like the following:
0 */3 * * * sh cron/update_old_citations.sh
good reference for how to set various settings in cron at: http://www.thegeekstuff.com/2011/07/cron-every-5-minutes/
this
points to the object in whose member function it is reffered, so it is optional.
function(url,callback){
request(url).on('data',(data) => {
try{
var json = JSON.parse(data);
}
catch(error){
callback("");
}
callback(json);
})
}
You can also use this. This is to async flow. The error comes when the response is not a JSON. Also in 404 status code .
You can open Dev Tools (F12
in Chrome) in new window by clicking three, vertical dots
on the right bottom corner, and choose Open as Separate Window
.
Oskar Persson's answer is the best way to handle it because makes it easier to pass the data to the context and treat it normally from the template as we get the object instances (easily iterable to get props) instead of a plain value list.
After that you can just easily get the wanted prop:
for employee in employees:
print(employee.eng_name)
Or in the template:
{% for employee in employees %}
<p>{{ employee.eng_name }}</p>
{% endfor %}
NavigationView navigationView = (NavigationView) findViewById(R.id.nav_view);
View hView = navigationView.getHeaderView(0);
TextView nav_user = (TextView)hView.findViewById(R.id.nav_name);
nav_user.setText(user);
hope this help!
Depends on what they looked like. I use gitx which makes pictures like this one:
You can compare git log --graph
vs. gitk on a 24-way octopus merge (originally from http://clojure-log.n01se.net/date/2008-12-24.html):
Your URL should be jdbc:sqlserver://server:port;DatabaseName=dbname
and Class name should be like com.microsoft.sqlserver.jdbc.SQLServerDriver
Use MicrosoftSQL Server JDBC Driver 2.0
The public
keyword is used only when declaring a class method.
Since you're declaring a simple function and not a class you need to remove public
from your code.
In python3.x it can be done using :
# Converting lat/long to cartesian
import numpy as np
def get_cartesian(lat=None,lon=None):
lat, lon = np.deg2rad(lat), np.deg2rad(lon)
R = 6371 # radius of the earth
x = R * np.cos(lat) * np.cos(lon)
y = R * np.cos(lat) * np.sin(lon)
z = R *np.sin(lat)
return x,y,z
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package Algorithms;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import javax.swing.JOptionPane;
/**
*
* @author Mokhtar
*/
public class Anagrams {
//Write aprogram to check if two words are anagrams
public static void main(String[] args) {
Anagrams an=new Anagrams();
ArrayList<String> l=new ArrayList<String>();
String result=JOptionPane.showInputDialog("How many words to test anagrams");
if(Integer.parseInt(result) >1)
{
for(int i=0;i<Integer.parseInt(result);i++)
{
String word=JOptionPane.showInputDialog("Enter word #"+i);
l.add(word);
}
System.out.println(an.isanagrams(l));
}
else
{
JOptionPane.showMessageDialog(null, "Can not be tested, \nYou can test two words or more");
}
}
private static String sortString( String w )
{
char[] ch = w.toCharArray();
Arrays.sort(ch);
return new String(ch);
}
public boolean isanagrams(ArrayList<String> l)
{
boolean isanagrams=true;
ArrayList<String> anagrams = null;
HashMap<String, ArrayList<String>> map = new HashMap<String, ArrayList<String>>();
for(int i=0;i<l.size();i++)
{
String word = l.get(i);
String sortedWord = sortString(word);
anagrams = map.get( sortedWord );
if( anagrams == null ) anagrams = new ArrayList<String>();
anagrams.add(word);
map.put(sortedWord, anagrams);
}
for(int h=0;h<l.size();h++)
{
if(!anagrams.contains(l.get(h)))
{
isanagrams=false;
break;
}
}
return isanagrams;
//}
}
}
Why not combine the onclick method with the <a>
element inside the <td>
for backup for non-JS? Seems to work great.
<td onclick="location.href='yourpage.html'"><a href="yourpage.html">Link</a></td>
You can just inject the DOCUMENT token into the constructor and use the same functions on it
import { Inject } from '@angular/core';
import { DOCUMENT } from '@angular/common';
@Component({...})
export class AppCmp {
constructor(@Inject(DOCUMENT) document) {
document.getElementById('el');
}
}
Or if the element you want to get is in that component, you can use template references.
Here is a more concise version of the accepted answer which avoids repeating the NoteProperty identifiers and the [pscustomobject]
-cast:
$myItems = ("Joe",32,"something about him"), ("Sue",29,"something about her")
| ForEach-Object {[pscustomobject]@{name = $_[0]; age = $_[1]; info = $_[2]}}
Result:
> $myItems
name age info
---- --- ----
Joe 32 something about him
Sue 29 something about her
The columns that needs to be converted to int can be mentioned in a dictionary also as below
df = df.astype({'col1': 'int', 'col2': 'int', 'col3': 'int'})
If you hadn't made any commit yet, only (1: branch) and (3: checkout) would be enough.
Or, in one command: git checkout -b newBranch
As mentioned in the git reset
man page:
$ git branch topic/wip # (1)
$ git reset --hard HEAD~3 # (2) NOTE: use $git reset --soft HEAD~3 (explanation below)
$ git checkout topic/wip # (3)
master
" branch. You want to continue polishing them in a topic branch, so create "topic/wip
" branch off of the current HEAD
.master
branch to get rid of those three commits.topic/wip
" branch and keep working.Note: due to the "destructive" effect of a git reset --hard
command (it does resets the index and working tree. Any changes to tracked files in the working tree since <commit>
are discarded), I would rather go with:
$ git reset --soft HEAD~3 # (2)
This would make sure I'm not losing any private file (not added to the index).
The --soft
option won't touch the index file nor the working tree at all (but resets the head to <commit>
, just like all modes do).
With Git 2.23+, the new command git switch
would create the branch in one line (with the same kind of reset --hard
, so beware of its effect):
git switch -f -c topic/wip HEAD~3
You have two ways to do that:
METHOD 1. The secure way.
Put the images on /www/htdocs/
<?php
$www_root = 'http://localhost/images';
$dir = '/var/www/images';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="', $www_root, '/', $file, '" alt="', $file, '"/>';
break;
}
}
}
?>
METHOD 2. Unsecure but more flexible.
Put the images on any directory (apache must have permission to read the file).
<?php
$dir = '/home/user/Pictures';
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if ( file_exists( $dir ) == false ) {
echo 'Directory \'', $dir, '\' not found!';
} else {
$dir_contents = scandir( $dir );
foreach ( $dir_contents as $file ) {
$file_type = strtolower( end( explode('.', $file ) ) );
if ( ($file !== '.') && ($file !== '..') && (in_array( $file_type, $file_display)) ) {
echo '<img src="file_viewer.php?file=', base64_encode($dir . '/' . $file), '" alt="', $file, '"/>';
break;
}
}
}
?>
And create another script to read the image file.
<?php
$filename = base64_decode($_GET['file']);
// Check the folder location to avoid exploit
if (dirname($filename) == '/home/user/Pictures')
echo file_get_contents($filename);
?>