1 - Open the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid (take note to revert this change on step 6)
Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox
Change:
<HardDisks>
<HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
To:
<HardDisks>
<HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
2 - Reboot machine
4 - Stop Virtual Machine (if started)
5 - On terminal:
su vbox
cd /home/virtualbox/WindowsServer/
VBoxManage modifyhd WindowsServer.vdi --resize SIZE
exit
exit
change SIZE for a number in Megabytes, example 80000 (80GB)
6 - Open again the files '.vbox' and '.vbox-prev' (if exist) files in any text editor and replace the first character of HardDisk uuid whith the original value
Example: nano /home/virtualbox/WindowsServer/WindowsServer.vbox
Change:
<HardDisks>
<HardDisk uuid="{2ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
To:
<HardDisks>
<HardDisk uuid="{3ebaa9b6-8318-4b81-b853-8f30dd278bdc}" location="/home/virtualbox/WindowsServer/WindowsServer.vdi" format="VDI" type="Normal"/>
7 - Reboot machine
Basically you need to edit the JS and add (in this case, inside $('#featured-articles').slick({
), this:
variableWidth: true,
This will allow you to edit the width in your CSS where you can, generically use:
.slick-slide {
width: 100%;
}
or in this case:
.featured {
width: 100%;
}
It is very clear from your exception that it is trying to connect to localhost
and not to 10.101.3.229
exception snippet : Could not connect to SMTP host: localhost, port: 25;
1.) Please check if there are any null check which is setting localhost as default value
2.) After restarting, if it is working fine, then it means that only at first-run, the proper value is been taken from Properties and from next run the value is set to default. So keep the property-object as a singleton one and use it all-over your project
EDIT: I just realized you want to filter details
, which is an array of hashes. In that case you could do
details.reject { |item| item[:qty].empty? }
The inner data structure itself is not an Array, but a Hash. You can also use select
here, but the block is given the key and value in this case:
irb(main):001:0> h = {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .", :qty=>"", :qty2=>"1", :price=>"5,204.34 P"}
irb(main):002:0> h.select { |key, value| !value.empty? }
=> {:sku=>"507772-B21", :desc=>"HP 1TB 3G SATA 7.2K RPM LFF (3 .",
:qty2=>"1", :price=>"5,204.34 P"}
Or using reject
, which is the inverse of select
(excludes all items for which the given condition holds):
h.reject { |key, value| value.empty? }
Note that this is Ruby 1.9. If you have to maintain compatibility with 1.8, you could do:
Hash[h.reject { |key, value| value.empty? }]
Windows has two different settings in which priority is established. There is the metric value which you have already set in the adapter settings, and then there is the connection priority in the network connections settings.
To change the priority of the connections:
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!
This is a derivative of @Ralph suggestion that I've been using. Add the c:url
to the top of your JSP.
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:url value="/" var="root" />
Then just reference the root variable in your page:
<link rel="stylesheet" href="${root}templates/style/main.css">
Here's the cache of the page described by Greg Smith. In case that dies as well, the alter statement looks like this:
UPDATE pg_attribute SET atttypmod = 35+4
WHERE attrelid = 'TABLE1'::regclass
AND attname = 'COL1';
Where your table is TABLE1, the column is COL1 and you want to set it to 35 characters (the +4 is needed for legacy purposes according to the link, possibly the overhead referred to by A.H. in the comments).
If you need to resume an scp transfer from local to remote, try with rsync:
rsync --partial --progress --rsh=ssh local_file user@host:remote_file
Short version, as pointed out by @aurelijus-rozenas:
rsync -P -e ssh local_file user@host:remote_file
In general the order of args for rsync is
rsync [options] SRC DEST
I had a similar issue when I checked out a web project from a github repo on my eclipse. src/main/java was directly inside the project root in Package Explorer. My expectation was that src/main/java be visible inside a source folder "Java Resources". There were few things which I did to achieve this.
One simple solution:
cond1 <- df$sub == 1 & df$day == 2
cond2 <- df$sub == 3 & df$day == 4
df <- df[!(cond1 | cond2),]
You could query an LDAP server from the command line with ldap-utils: ldapsearch, ldapadd, ldapmodify
This Line of code returns Store StoredProcedure returned value from SQL Server
cmd.Parameters.Add("@id", System.Data.SqlDbType.Int).Direction = System.Data.ParameterDirection.ReturnValue;
cmd.ExecuteNonQuery();
Atfer Execution of query value will returned from SP
id = (int)cmd.Parameters["@id"].Value;
I found an alternative that works.
None of these answers worked for me (currently testing in FireFox 22.0), and after a lot of research I found, what seems to be, a much cleaner and straight forward solution.
Implemented solution:
function IsScrollbarAtBottom() {
var documentHeight = $(document).height();
var scrollDifference = $(window).height() + $(window).scrollTop();
return (documentHeight == scrollDifference);
}
Regards
This is backwards from what Bootstrap is designed for, but you can do this:
<div class="row">
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
<div class="col-xs-4 col-md-12">.col-xs-4 .col-md-12</div>
</div>
This will make each element 33.3% wide on small and extra small devices but 100% wide on medium and larger devices.
JSFiddle: http://jsfiddle.net/jdwire/sggt8/embedded/result/
I think you're looking for the visible-xs
and/or visible-sm
classes. These will let you make certain elements only visible to small screen devices.
For example, if you want a element to only be visible to small and extra-small devices, do this:
<div class="visible-xs visible-sm">You're using a fairly small device.</div>
To show it only for larger screens, use this:
<div class="hidden-xs hidden-sm">You're probably not using a phone.</div>
See http://getbootstrap.com/css/#responsive-utilities-classes for more information.
If you have API 26 then you might consider using autoSizeTextType:
<Button
app:autoSizeTextType="uniform" />
Default setting lets the auto-sizing of TextView scale uniformly on horizontal and vertical axes.
https://developer.android.com/guide/topics/ui/look-and-feel/autosizing-textview
You could do this:
echo "<script>alert('Successfully Updated'); window.location = './edit.php';</script>";
I like Alex's answer. If you want something quick to try out in a ViewController
make sure you use
viewWillAppear()
override func viewWillAppear(animated: Bool) {
super.viewWillAppear(animated)
var nav = self.navigationController?.navigationBar
nav?.barStyle = UIBarStyle.Black
nav?.tintColor = UIColor.white
nav?.titleTextAttributes = [NSForegroundColorAttributeName: UIColor.orange]
//nav?.titleTextAttributes = [NSAttributedString.Key.foregroundColor: UIColor.orange] // swift 4.2
}
make sure your have correct jackson version in your classpath
This is impossible as you cannot return from an asynchronous call inside a synchronous method.
In this case you need to pass a callback to foo that will receive the return value
function foo(address, fn){
geocoder.geocode( { 'address': address}, function(results, status) {
fn(results[0].geometry.location);
});
}
foo("address", function(location){
alert(location); // this is where you get the return value
});
The thing is, if an inner function call is asynchronous, then all the functions 'wrapping' this call must also be asynchronous in order to 'return' a response.
If you have a lot of callbacks you might consider taking the plunge and use a promise library like Q.
I'd use request for this:
request('http://google.com/doodle.png').pipe(fs.createWriteStream('doodle.png'))
Or if you don't need to save to a file first, and you just need to read the CSV into memory, you can do the following:
var request = require('request');
request.get('http://www.whatever.com/my.csv', function (error, response, body) {
if (!error && response.statusCode == 200) {
var csv = body;
// Continue with your processing here.
}
});
etc.
In Visual Studio, you can't just open a .cpp
file and expect it to run. You must create a project first, or open the .cpp in some existing project.
In your case, there is no project, so there is no project to build.
Go to File --> New --> Project --> Visual C++ --> Win32 Console Application
. You can uncheck "create a directory for solution". On the next page, be sure to check "Empty project".
Then, You can add .cpp
files you created outside the Visual Studio by right clicking in the Solution explorer
on folder icon "Source" and Add->Existing Item.
Obviously You can create new .cpp this way too (Add --> New). The .cpp file will be created in your project directory.
Then you can press ctrl+F5 to compile without debugging and can see output on console window.
If the problem is that you are not seeing your changes to the file take effect, just open a new terminal window, and it will be "sourced". You will be able to use the proper PATH etc with each subsequent terminal window.
This is a basic example of an object "Article" with getters and setters:
public class Article
{
public String title;
public String link;
public String description;
public string getTitle()
{
return title;
}
public void setTitle(string value)
{
title = value;
}
public string getLink()
{
return link;
}
public void setLink(string value)
{
link = value;
}
public string getDescription()
{
return description;
}
public void setDescription(string value)
{
description = value;
}
}
Ascii string to integer conversion is done by the atoi()
function.
I know, you ask for Eloquent but you can do it with Fluent Query Builder
$data = DB::table('themes')
->join('users', 'users.id', '=', 'themes.user_id')
->get(array('themes.*', 'users.username'));
In my case this error is happening because of not connected to firebase firestore but using the same.
To rectify the issue please go to Tools-> Firebase
when a window will open on RHS choose the options to -> Connect your app to Firebase -> Add Cloud Firestore to your app
You can not directly send an email with a HTML form. You can however send the form to your web server and then generate the email with a server side program written in e.g. PHP.
The other solution is to create a link as you did with the "mailto:". This will open the local email program from the user. And he/she can then send the pre-populated email.
When you decided how you wanted to do it you can ask another (more specific) question on this site. (Or you can search for a solution somewhere on the internet.)
If you are running SQL Server 2012 or newer you can also use the new TRY_PARSE() function:
Returns the result of an expression, translated to the requested data type, or null if the cast fails in SQL Server. Use TRY_PARSE only for converting from string to date/time and number types.
Or TRY_CONVERT/TRY_CAST:
Returns a value cast to the specified data type if the cast succeeds; otherwise, returns null.
I'll explain it in a simple way.
Generics defined at Class level are completely separate from the generics defined at the (static) method level.
class Greet<T> {
public static <T> void sayHello(T obj) {
System.out.println("Hello " + obj);
}
}
When you see the above code anywhere, please note that the T defined at the class level has nothing to do with the T defined in the static method. The following code is also completely valid and equivalent to the above code.
class Greet<T> {
public static <E> void sayHello(E obj) {
System.out.println("Hello " + obj);
}
}
Why the static method needs to have its own generics separate from those of the Class?
This is because, the static method can be called without even instantiating the Class. So if the Class is not yet instantiated, we do not yet know what is T. This is the reason why the static methods needs to have its own generics.
So, whenever you are calling the static method,
Greet.sayHello("Bob");
Greet.sayHello(123);
JVM interprets it as the following.
Greet.<String>sayHello("Bob");
Greet.<Integer>sayHello(123);
Both giving the same outputs.
Hello Bob
Hello 123
getActivity().finish();
System.exit(0);
this is the best way to exit your app.!!!
The best solution for me.
I had this problem and this is the best solution without any external or additional script libraries: In Javascript tags or file create this function: We assume here that canvas is your canvas:
function download(){
var download = document.getElementById("download");
var image = document.getElementById("canvas").toDataURL("image/png")
.replace("image/png", "image/octet-stream");
download.setAttribute("href", image);
}
In the body part of your HTML specify the button:
<a id="download" download="image.png"><button type="button" onClick="download()">Download</button></a>
This is working and download link looks like a button. Tested in Firefox and Chrome.
Exported variables such as $HOME
and $PATH
are available to (inherited by) other programs run by the shell that exports them (and the programs run by those other programs, and so on) as environment variables. Regular (non-exported) variables are not available to other programs.
$ env | grep '^variable='
$ # No environment variable called variable
$ variable=Hello # Create local (non-exported) variable with value
$ env | grep '^variable='
$ # Still no environment variable called variable
$ export variable # Mark variable for export to child processes
$ env | grep '^variable='
variable=Hello
$
$ export other_variable=Goodbye # create and initialize exported variable
$ env | grep '^other_variable='
other_variable=Goodbye
$
For more information, see the entry for the export
builtin in the GNU Bash manual, and also the sections on command execution environment and environment.
Note that non-exported variables will be available to subshells run via ( ... )
and similar notations because those subshells are direct clones of the main shell:
$ othervar=present
$ (echo $othervar; echo $variable; variable=elephant; echo $variable)
present
Hello
elephant
$ echo $variable
Hello
$
The subshell can change its own copy of any variable, exported or not, and may affect the values seen by the processes it runs, but the subshell's changes cannot affect the variable in the parent shell, of course.
Some information about subshells can be found under command grouping and command execution environment in the Bash manual.
I tested this code and Works
Javascript
<script>
$(document).ready(function() {
$('#summernote').summernote({
height: 200,
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
});
function sendFile(file, editor, welEditable) {
data = new FormData();
data.append("file", file);
$.ajax({
data: data,
type: "POST",
url: "Your URL POST (php)",
cache: false,
contentType: false,
processData: false,
success: function(url) {
editor.insertImage(welEditable, url);
}
});
}
});
</script>
PHP
if ($_FILES['file']['name']) {
if (!$_FILES['file']['error']) {
$name = md5(rand(100, 200));
$ext = pathinfo($_FILES['file']['name'], PATHINFO_EXTENSION);
$filename = $name.
'.'.$ext;
$destination = '/assets/images/'.$filename; //change this directory
$location = $_FILES["file"]["tmp_name"];
move_uploaded_file($location, $destination);
echo 'http://test.yourdomain.al/images/'.$filename; //change this URL
} else {
echo $message = 'Ooops! Your upload triggered the following error: '.$_FILES['file']['error'];
}
}
Update:
After 0.7.0 onImageUpload
should be inside callbacks
option as mentioned by @tugberk
$('#summernote').summernote({
height: 200,
callbacks: {
onImageUpload: function(files, editor, welEditable) {
sendFile(files[0], editor, welEditable);
}
}
});
In dplyr 0.3 this can be easily achieved using the distinct()
method.
Here is an example:
distinct_df = df %>% distinct(field1)
You can get a vector of the distinct values with:
distinct_vector = distinct_df$field1
You can also select a subset of columns at the same time as you perform the distinct()
call, which can be cleaner to look at if you examine the data frame using head/tail/glimpse.:
distinct_df = df %>% distinct(field1) %>% select(field1)
distinct_vector = distinct_df$field1
In Workbench 6.3 it is supereasy:
You can easily launch a market link or an install prompt:
Intent promptInstall = new Intent(Intent.ACTION_VIEW)
.setDataAndType(Uri.parse("file:///path/to/your.apk"),
"application/vnd.android.package-archive");
startActivity(promptInstall);
Intent goToMarket = new Intent(Intent.ACTION_VIEW)
.setData(Uri.parse("market://details?id=com.package.name"));
startActivity(goToMarket);
However, you cannot install .apks without user's explicit permission; not unless the device and your program is rooted.
Another way to create an absolute URL to an action:
var relativeUrl = Url.Action("MyAction"); //..or one of the other .Action() overloads
var currentUrl = Request.Url;
var absoluteUrl = new System.Uri(currentUrl, relativeUrl);
Here's an answer to my own question. I combined the answers from the various results to write a class that pretty prints XML.
No guarantees on how it responds with invalid XML or large documents.
package ecb.sdw.pretty;
import org.apache.xml.serialize.OutputFormat;
import org.apache.xml.serialize.XMLSerializer;
import org.w3c.dom.Document;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import java.io.IOException;
import java.io.StringReader;
import java.io.StringWriter;
import java.io.Writer;
/**
* Pretty-prints xml, supplied as a string.
* <p/>
* eg.
* <code>
* String formattedXml = new XmlFormatter().format("<tag><nested>hello</nested></tag>");
* </code>
*/
public class XmlFormatter {
public XmlFormatter() {
}
public String format(String unformattedXml) {
try {
final Document document = parseXmlFile(unformattedXml);
OutputFormat format = new OutputFormat(document);
format.setLineWidth(65);
format.setIndenting(true);
format.setIndent(2);
Writer out = new StringWriter();
XMLSerializer serializer = new XMLSerializer(out, format);
serializer.serialize(document);
return out.toString();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
private Document parseXmlFile(String in) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
DocumentBuilder db = dbf.newDocumentBuilder();
InputSource is = new InputSource(new StringReader(in));
return db.parse(is);
} catch (ParserConfigurationException e) {
throw new RuntimeException(e);
} catch (SAXException e) {
throw new RuntimeException(e);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
public static void main(String[] args) {
String unformattedXml =
"<?xml version=\"1.0\" encoding=\"UTF-8\"?><QueryMessage\n" +
" xmlns=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/message\"\n" +
" xmlns:query=\"http://www.SDMX.org/resources/SDMXML/schemas/v2_0/query\">\n" +
" <Query>\n" +
" <query:CategorySchemeWhere>\n" +
" \t\t\t\t\t <query:AgencyID>ECB\n\n\n\n</query:AgencyID>\n" +
" </query:CategorySchemeWhere>\n" +
" </Query>\n\n\n\n\n" +
"</QueryMessage>";
System.out.println(new XmlFormatter().format(unformattedXml));
}
}
Based on Tim's second edit and this page you could do this:
@echo off
if "%1"=="loop" (
for /l %%f in (1,1,1000000) do (
echo %%f
if exist %%f exit
)
goto :eof
)
cmd /v:on /q /d /c "%0 loop"
echo done
This page suggests a way to use a goto inside a loop, it seems it does work, but it takes some time in a large loop. So internally it finishes the loop before the goto is executed.
eval
and exec
are the correct solution, and they can be used in a safer manner.
As discussed in Python's reference manual and clearly explained in this tutorial, the eval
and exec
functions take two extra parameters that allow a user to specify what global and local functions and variables are available.
For example:
public_variable = 10
private_variable = 2
def public_function():
return "public information"
def private_function():
return "super sensitive information"
# make a list of safe functions
safe_list = ['public_variable', 'public_function']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
# add any needed builtins back in
safe_dict['len'] = len
>>> eval("public_variable+2", {"__builtins__" : None }, safe_dict)
12
>>> eval("private_variable+2", {"__builtins__" : None }, safe_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'private_variable' is not defined
>>> exec("print \"'%s' has %i characters\" % (public_function(), len(public_function()))", {"__builtins__" : None}, safe_dict)
'public information' has 18 characters
>>> exec("print \"'%s' has %i characters\" % (private_function(), len(private_function()))", {"__builtins__" : None}, safe_dict)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<string>", line 1, in <module>
NameError: name 'private_function' is not defined
In essence you are defining the namespace in which the code will be executed.
For those who dont want to use datepicker method
var alldatepicker= $("[class$=hasDatepicker]");
alldatepicker.each(function(){
var value=$(this).val();
var today = new Date();
var dd = today.getDate();
var mm = today.getMonth()+1; //January is 0!
var yyyy = today.getFullYear();
if(dd<10) {
dd='0'+dd
}
if(mm<10) {
mm='0'+mm
}
today = mm+'/'+dd+'/'+yyyy;
if(value!=''){
if(value>today){
alert("Date cannot be greater than current date");
}
}
});
CompareStrings with equals(..)
not with ==
if (operation.equals("+")
{
System.out.println("your answer is" + (num1 + num2));
}
if (operation.equals("-"))
{
System.out.println("your answer is" + (num1 - num2));
}
if (operation.equals("/"))
{
System.out.println("your answer is" + (num1 / num2));
}
if (operation .equals( "*"))
{
System.out.println("your answer is" + (num1 * num2));
}
And the ;
after the conditions was an empty statement so the conditon had no effect at all.
If you use java 7 you can also replace the if statements with a switch
.
In java <7 you can test, if operation
has length 1 and than make a switch for the char
[switch (operation.charAt(0))
]
While there is no technical difference, I have seen the two used to denote slightly different things.
For a template that should accept any type as T, including built-ins (such as an array )
template<typename T>
class Foo { ... }
For a template that will only work where T is a real class.
template<class T>
class Foo { ... }
But keep in mind that this is purely a style thing some people use. Not mandated by the standard or enforced by compilers
cursor.execute(sql,array)
Only takes two arguments.
It will iterate the "array"-object and match ? in the sql-string.
(with sanity checks to avoid sql-injection)
You need to first enable query logging
DB::enableQueryLog();
Then you can get query logs by simply:
dd(DB::getQueryLog());
It would be better if you enable query logging before application starts, which you can do in a BeforeMiddleware and then retrieve the executed queries in AfterMiddleware.
You want to use slicing.
for item in listOfStuff[1:3]:
print item
Here is how I remember when to use what -
Semaphore: Use a semaphore when you (thread) want to sleep till some other thread tells you to wake up. Semaphore 'down' happens in one thread (producer) and semaphore 'up' (for same semaphore) happens in another thread (consumer) e.g.: In producer-consumer problem, producer wants to sleep till at least one buffer slot is empty - only the consumer thread can tell when a buffer slot is empty.
Mutex: Use a mutex when you (thread) want to execute code that should not be executed by any other thread at the same time. Mutex 'down' happens in one thread and mutex 'up' must happen in the same thread later on. e.g.: If you are deleting a node from a global linked list, you do not want another thread to muck around with pointers while you are deleting the node. When you acquire a mutex and are busy deleting a node, if another thread tries to acquire the same mutex, it will be put to sleep till you release the mutex.
Spinlock: Use a spinlock when you really want to use a mutex but your thread is not allowed to sleep. e.g.: An interrupt handler within OS kernel must never sleep. If it does the system will freeze / crash. If you need to insert a node to globally shared linked list from the interrupt handler, acquire a spinlock - insert node - release spinlock.
Bootstrap 3 now has Responsive tables out of the box. Hooray! :)
You can check it here: https://getbootstrap.com/docs/3.3/css/#tables-responsive
Add a <div class="table-responsive">
surrounding your table and you should be good to go:
<div class="table-responsive">
<table class="table">
...
</table>
</div>
To make it work on all layouts you can do this:
.table-responsive
{
overflow-x: auto;
}
From the Publish
tab go to application Files
.
Then, click unnecessary files
.
After that, do the exclude press ok
.
Finally, build the project files and run the projects.
That's what we have in our applications:
Attribute
public class HttpParamActionAttribute : ActionNameSelectorAttribute
{
public override bool IsValidName(ControllerContext controllerContext, string actionName, MethodInfo methodInfo)
{
if (actionName.Equals(methodInfo.Name, StringComparison.InvariantCultureIgnoreCase))
return true;
var request = controllerContext.RequestContext.HttpContext.Request;
return request[methodInfo.Name] != null;
}
}
Actions decorated with it:
[HttpParamAction]
public ActionResult Save(MyModel model)
{
// ...
}
[HttpParamAction]
public ActionResult Publish(MyModel model)
{
// ...
}
HTML/Razor
@using (@Html.BeginForm())
{
<!-- form content here -->
<input type="submit" name="Save" value="Save" />
<input type="submit" name="Publish" value="Publish" />
}
name
attribute of submit button should match action/method name
This way you do not have to hard-code urls in javascript
In the box is working on being able to convert android projects to iOS
Looking at the language itself may help; it often helps me (I'm not a native English speaker).
In duck typing
:
1) the word typing
does not mean typing on a keyboard (as was the persistent image in my mind), it means determining "what type of a thing is that thing?"
2) the word duck
expresses how is that determining done; it's kind of a 'loose' determining, as in: "if it walks like a duck ... then it's a duck". It's 'loose' because the thing may be a duck or may not, but whether it actually is a duck doesn't matter; what matters is that I can do with it what I can do with ducks and expect behaviors exhibited by ducks. I can feed it bread crumbs and the thing may go towards me or charge at me or back off ... but it will not devour me like a grizzly would.
Given the code you provided in comments, I assume you want to do this:
>>> dateList = "Thu Sep 16 13:14:15 CDT 2010".split()
>>> sdateList = "Thu Sep 16 14:14:15 CDT 2010".split()
>>> dateList == sdataList
false
The split
-method of the string returns a list. A list in Python is very different from an array. ==
in this case does an element-wise comparison of the two lists and returns if all their elements are equal and the number and order of the elements is the same. Read the documentation.
The shell process is $$
since it is a special parameter
On Linux, the proc(5) filesystem gives a lot of information about processes. Perhaps
pgrep(1) (which accesses /proc
) might help too.
So try cat /proc/$$/status
to get the status of the shell process.
Hence, its parent process id could be retrieved with e.g.
parpid=$(awk '/PPid:/{print $2}' /proc/$$/status)
Then use $parpid
in your script to refer to the parent process pid (the parent of the shell).
But I don't think you need it!
Read some Bash Guide (or with caution advanced bash scripting guide, which has mistakes) and advanced linux programming.
Notice that some server daemon processes (wich usually need to be unique) are explicitly writing their pid into /var/run
, e.g. the sshd
server daemon is writing its pid into the textual file /var/run/sshd.pid
). You may want to add such a feature into your own server-like programs (coded in C, C++, Ocaml, Go, Rust or some other compiled language).
What worked for me in python 3.7 and img2pdf version 0.4.0 was to use something similar to the code given by Syed Shamikh Shabbir but changing the current working directory using OS as Stu suggested in his comment to Syed's solution
import os
import img2pdf
path = './path/to/folder'
os.chdir(path)
images = [i for i in os.listdir(os.getcwd()) if i.endswith(".jpg")]
for image in images:
with open(image[:-4] + ".pdf", "wb") as f:
f.write(img2pdf.convert(image))
It is worth mentioning this solution above saves each .jpg separately in one single pdf. If you want all your .jpg files together in only one .pdf you could do:
import os
import img2pdf
path = './path/to/folder'
os.chdir(path)
images = [i for i in os.listdir(os.getcwd()) if i.endswith(".jpg")]
with open("output.pdf", "wb") as f:
f.write(img2pdf.convert(images))
Code generation would be the only other way I can think of. Personally, I'd got with a generally reusable reflection solution (unless that part of the code is absolutely performance-critical). Using JMS sounds like overkill (additional dependency, and that's not even what it's meant for). Besides, it probably uses reflection as well under the hood.
Be warned, the majority of the mathematically calculated examples have a hard limit of 2038-01-18
dates and will not work with fictional dates.
As there was a lack of DateTime
and DateInterval
based examples, I wanted to provide a multi-purpose function that satisfies the OP's need and others wanting compound elapsed periods, such as 1 month 2 days ago
. Along with a bunch of other use cases, such as a limit to display the date instead of the elapsed time, or to filter out portions of the elapsed time result.
Additionally the majority of the examples assume elapsed is from the current time, where the below function allows for it to be overridden with the desired end date.
/**
* multi-purpose function to calculate the time elapsed between $start and optional $end
* @param string|null $start the date string to start calculation
* @param string|null $end the date string to end calculation
* @param string $suffix the suffix string to include in the calculated string
* @param string $format the format of the resulting date if limit is reached or no periods were found
* @param string $separator the separator between periods to use when filter is not true
* @param null|string $limit date string to stop calculations on and display the date if reached - ex: 1 month
* @param bool|array $filter false to display all periods, true to display first period matching the minimum, or array of periods to display ['year', 'month']
* @param int $minimum the minimum value needed to include a period
* @return string
*/
function elapsedTimeString($start, $end = null, $limit = null, $filter = true, $suffix = 'ago', $format = 'Y-m-d', $separator = ' ', $minimum = 1)
{
$dates = (object) array(
'start' => new DateTime($start ? : 'now'),
'end' => new DateTime($end ? : 'now'),
'intervals' => array('y' => 'year', 'm' => 'month', 'd' => 'day', 'h' => 'hour', 'i' => 'minute', 's' => 'second'),
'periods' => array()
);
$elapsed = (object) array(
'interval' => $dates->start->diff($dates->end),
'unknown' => 'unknown'
);
if ($elapsed->interval->invert === 1) {
return trim('0 seconds ' . $suffix);
}
if (false === empty($limit)) {
$dates->limit = new DateTime($limit);
if (date_create()->add($elapsed->interval) > $dates->limit) {
return $dates->start->format($format) ? : $elapsed->unknown;
}
}
if (true === is_array($filter)) {
$dates->intervals = array_intersect($dates->intervals, $filter);
$filter = false;
}
foreach ($dates->intervals as $period => $name) {
$value = $elapsed->interval->$period;
if ($value >= $minimum) {
$dates->periods[] = vsprintf('%1$s %2$s%3$s', array($value, $name, ($value !== 1 ? 's' : '')));
if (true === $filter) {
break;
}
}
}
if (false === empty($dates->periods)) {
return trim(vsprintf('%1$s %2$s', array(implode($separator, $dates->periods), $suffix)));
}
return $dates->start->format($format) ? : $elapsed->unknown;
}
One thing to note - the retrieved intervals for the supplied filter values do not carry over to the next period. The filter merely displays the resulting value of the supplied periods and does not recalculate the periods to display only the desired filter total.
Usage
For the OP's need of displaying the highest period (as of 2015-02-24).
echo elapsedTimeString('2010-04-26');
/** 4 years ago */
To display compound periods and supply a custom end date (note the lack of time supplied and fictional dates).
echo elapsedTimeString('1920-01-01', '2500-02-24', null, false);
/** 580 years 1 month 23 days ago */
To display the result of filtered periods (ordering of array doesn't matter).
echo elapsedTimeString('2010-05-26', '2012-02-24', null, ['month', 'year']);
/** 1 year 8 months ago */
To display the start date in the supplied format (default Y-m-d) if the limit is reached.
echo elapsedTimeString('2010-05-26', '2012-02-24', '1 year');
/** 2010-05-26 */
There are bunch of other use cases. It can also easily be adapted to accept unix timestamps and/or DateInterval objects for the start, end, or limit arguments.
For SQL Server version 9.0 (2005), you can use the code below:
select *
from
syscomments c
inner join sys.procedures p on p.object_id = c.id
where
p.name like '%usp_ConnectionsCount%';
Something like this, if want to go old-school.
<font color="blue">Sustaining : $60.00 USD - yearly</font>
Though a more modern approach would be to use a css style:
<td style="color:#0000ff">Sustaining : $60.00 USD - yearly</td>
There are of course even more general ways to do it.
This will sort your results by the first column returned. In the example it will sort by payment_date.
# /etc/init.d/mysqld stop
Stopping MySQL: [ OK ]
# mysqld_safe --skip-grant-tables &
[1] 13694
# Starting mysqld daemon with databases from /var/lib/mysql
# mysql -u root
Welcome to the MySQL monitor. Commands end with ; or \g.
Your MySQL connection id is 1
Server version: 5.0.77 Source distribution
Type 'help;' or '\h' for help. Type '\c' to clear the buffer.
mysql>
For Python 2.6 and later if you are dealing with bytes then a bytearray
is the most obvious choice:
>>> str(bytearray([17, 24, 121, 1, 12, 222, 34, 76]))
'\x11\x18y\x01\x0c\xde"L'
To me this is even more direct than Alex Martelli's answer - still no string manipulation or len
call but now you don't even need to import anything!
If you're in netbeans you can right click in the test method and click "Run Focused Test Method".
Use MoreLINQ, which has a DistinctBy
method :)
IEnumerable<Car> distinctCars = cars.DistinctBy(car => car.CarCode);
(This is only for LINQ to Objects, mind you.)
__repr__
should return a printable representation of the object, most likely one of the ways possible to create this object. See official documentation here. __repr__
is more for developers while __str__
is for end users.
A simple example:
>>> class Point:
... def __init__(self, x, y):
... self.x, self.y = x, y
... def __repr__(self):
... return 'Point(x=%s, y=%s)' % (self.x, self.y)
>>> p = Point(1, 2)
>>> p
Point(x=1, y=2)
If you are splitting from Linux, you can still reassemble in Windows.
copy /b file1 + file2 + file3 + file4 filetogether
I wouldn't call those different kind of streams. The Stream class have CanRead and CanWrite properties that tell you if the particular stream can be read from and written to.
The major difference between different stream classes (such as MemoryStream vs FileStream) is the backing store - where the data is read from or where it's written to. It's kind of obvious from the name. A MemoryStream stores the data in memory only, a FileStream is backed by a file on disk, a NetworkStream reads data from the network and so on.
Rhino is what you are looking for.
Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users.
Update: Now Nashorn, which is more performant JavaScript Engine for Java, is available with jdk8.
This worked for me on Chromium. The % for translate is in reference to the size of the bounding box of the element it is applied to so it perfectly gets the element to the lower right edge while not having to switch which property is used to specify it's location.
topleft {
top: 0%;
left: 0%;
}
bottomright {
top: 100%;
left: 100%;
-webkit-transform: translate(-100%,-100%);
}
Was also struggling with this error and based on the topic here and this answer was able to figure out snippet to copy/paste without the need to figure out what has to be imported (excellent for C# beginners), code below:
try
{
context.SaveChanges();
}
catch (System.Data.Entity.Validation.DbEntityValidationException ex)
{
foreach (var entityValidationErrors in ex.EntityValidationErrors)
{
foreach (var validationError in entityValidationErrors.ValidationErrors)
{
System.Diagnostics.Debug.WriteLine("Property: " + validationError.PropertyName + " Error: " + validationError.ErrorMessage);
}
}
}
Use the --force
(-f
) flag on your mysql import. Rather than stopping on the offending statement, MySQL will continue and just log the errors to the console.
For example:
mysql -u userName -p -f -D dbName < script.sql
Try adding this to your CSS
html, body {
max-width: 100%;
overflow-x: hidden;
}
There is no such functionality in jQuery. Use JSON.stringify
or alternatively any jQuery plugin with similar functionality (e.g jquery-json).
Not only you can add a path, but you can add git diff --relative
to get result relative to that folder.
git -C a/folder diff --relative
And with Git 2.28 (Q3 2020), the commands in the "diff
" family learned to honor the "diff.relative
" configuration variable.
See commit c28ded8 (22 May 2020) by Laurent Arnoud (spk
).
(Merged by Junio C Hamano -- gitster
-- in commit e34df9a, 02 Jun 2020)
diff
: add config optionrelative
Signed-off-by: Laurent Arnoud
Acked-by: Ðoàn Tr?n Công DanhThe
diff.relative
boolean option set totrue
shows only changes in the current directory/value specified by thepath
argument of therelative
option and shows pathnames relative to the aforementioned directory.Teach
--no-relative
to override earlier--relative
Add for git-format-patch(1) options documentation
--relative
and--no-relative
The documentation now includes:
diff.relative
:If set to '
true
', 'git diff
' does not show changes outside of the directory and show pathnames relative to the current directory.
function createQuestionPanel() {
var element = document.createElement("Input");
element.setAttribute("type", "button");
element.setAttribute("value", "button");
element.setAttribute("name", "button");
var div = document.createElement("div"); <------- Create DIv Node
div.appendChild(element);<--------------------
document.body.appendChild(div) <------------- Then append it to body
}
function formvalidate() {
}
It usually represents some common service (protocol) that bluetooth device supports.
When creating your own rfcomm server (with listenUsingRfcommWithServiceRecord
), you should specify your own UUID so that the clients connecting to it could identify it;
it is one of the reasons why createRfcommSocketToServiceRecord
requires an UUID parameter.
Otherwise, some common services have the same UUID, just find one you need and use it.
See here
Without arc4Random_uniform() in some versions of Xcode(in 7.1 it runs but doesn't autocomplete for me). You can do this instead.
To generate a random number from 0-5. First
import GameplayKit
Then
let diceRoll = GKRandomSource.sharedRandom().nextIntWithUpperBound(6)
Using Altair.
from altair import *
import pandas as pd
df = datasets.load_dataset('iris')
Chart(df).mark_point().encode(x='petalLength',y='sepalLength', color='species')
I found that selecting a clob
column in CTE caused this explosion. ie
with cte as (
select
mytable1.myIntCol,
mytable2.myClobCol
from mytable1
join mytable2 on ...
)
select myIntCol, myClobCol
from cte
where ...
presumably because oracle can't handle a clob in a temporary table.
Because my values were longer than 4K, I couldn't use to_char()
.
My work around was to select it from the final select
, ie
with cte as (
select
mytable1.myIntCol
from mytable1
)
select myIntCol, myClobCol
from cte
join mytable2 on ...
where ...
Too bad if this causes a performance problem.
it's android:button="@drawable/selector_checkbox"
to make it work
At grub screen goto boot in recovery.
As booting hold ESC
It should take you into a gui menu. Open command and fix selinux.
Also I suggest run the clean broken packages
I had the same problem in Visual Studio Pro 2017: missing MSVCP120.dll file in Release mode and missing MSVCP120d.dll file in Debug mode. I installed Visual C++ Redistributable Packages for Visual Studio 2013 and Update for Visual C++ 2013 and Visual C++ Redistributable Package as suggested here Microsoft answer this fixed the release mode. For the debug mode what eventually worked was to copy msvcp120d.dll and msvcr120d.dll from a different computer (with Visual studio 2013) into C:\Windows\System32
For "polling" transport.
Apache side:
<VirtualHost *:80>
ServerName mysite.com
DocumentRoot /my/path
ProxyRequests Off
<Proxy *>
Order deny,allow
Allow from all
</Proxy>
ProxyPass /my-connect-3001 http://127.0.0.1:3001/socket.io
ProxyPassReverse /my-connect-3001 http://127.0.0.1:3001/socket.io
</VirtualHost>
Client side:
var my_socket = new io.Manager(null, {
host: 'mysite.com',
path: '/my-connect-3001'
transports: ['polling'],
}).socket('/');
Shows the Computer Name, Use a Button to call it
Dim strHostName As String
strHostName = System.Net.Dns.GetHostName(). MsgBox(strHostName)
Shows the User Name, Use a Button to call it
If TypeOf My.User.CurrentPrincipal Is Security.Principal.WindowsPrincipal Then
Dim parts() As String = Split(My.User.Name, "\") Dim username As String = parts(1) MsgBox(username) End If
For IP Address its little complicated, But I try to explain as much as I can. First write the next code, before Form1_Load but after import section
Public Class Form1
Dim mem As String Private Sub GetIPAddress() Dim strHostName As String Dim strIPAddress As String strHostName = System.Net.Dns.GetHostName() strIPAddress = System.Net.Dns.GetHostByName(strHostName).AddressList(0).ToString() mem = strIPAddress MessageBox.Show("IP Address: " & strIPAddress) End Sub
Then in Form1_Load Section just call it
GetIPAddress()
Result: On form load it will show a msgbox along with the IP address, for put into Label1.text or some where else play with the code.
for finding a specific value of a column you can use the code below
irrespective of the preference you can use the any of the method you like
df.col_name.value_counts().Value_you_are_looking_for
take example of the titanic dataset
df.Sex.value_counts().male
this gives a count of all male on the ship Although if you want to count a numerical data then you cannot use the above method because value_counts() is used only with series type of data hence fails So for that you can use the second method example
the second method is
#this is an example method of counting on a data frame
df[(df['Survived']==1)&(df['Sex']=='male')].counts()
this is not that efficient as value_counts() but surely will help if you want to count values of a data frame hope this helps
Of course src="@/assets/images/x.jpg
works,
but better way is:
src="~assets/images/x.jpg
You cannot return anonymous types. Can you create a model that can be returned? Otherwise, you must use an object
.
Here is an article written by Jon Skeet on the subject
Code from the article:
using System;
static class GrottyHacks
{
internal static T Cast<T>(object target, T example)
{
return (T) target;
}
}
class CheesecakeFactory
{
static object CreateCheesecake()
{
return new { Fruit="Strawberry", Topping="Chocolate" };
}
static void Main()
{
object weaklyTyped = CreateCheesecake();
var stronglyTyped = GrottyHacks.Cast(weaklyTyped,
new { Fruit="", Topping="" });
Console.WriteLine("Cheesecake: {0} ({1})",
stronglyTyped.Fruit, stronglyTyped.Topping);
}
}
Or, here is another similar article
Or, as others are commenting, you could use dynamic
.env
and .env.production
VUE_APP_
eg: VUE_APP_WHATEVERYOUWANT
.env
and build uses .env.production
process.env.VUE_APP_WHATEVERYOUWANT
to call valueBe sure you are using vue-cli version 3 or above
For more information: https://cli.vuejs.org/guide/mode-and-env.html
As others have pointed out, ideally, the foreign key would be created as a reference to a primary key (usually an IDENTITY column). However, we don't live in an ideal world, and sometimes even a "small" change to a schema can have significant ripple effects to the application logic.
Consider the case of a Customer table with a SSN column (and a dumb primary key), and a Claim table that also contains a SSN column (populated by business logic from the Customer data, but no FK exists). The design is flawed, but has been in use for several years, and three different applications have been built on the schema. It should be obvious that ripping out Claim.SSN and putting in a real PK-FK relationship would be ideal, but would also be a significant overhaul. On the other hand, putting a UNIQUE constraint on Customer.SSN, and adding a FK on Claim.SSN, could provide referential integrity, with little or no impact on the applications.
Don't get me wrong, I'm all for normalization, but sometimes pragmatism wins over idealism. If a mediocre design can be helped with a band-aid, surgery might be avoided.
$(".first").addClass("second");
If you'd like to add it on an event, you can do so easily as well. An example with the click event:
$(".first").click(function() {
$(this).addClass("second");
});
I always have a primary key, even if in the beginning I don't have a purpose in mind yet for it. There have been a few times when I eventually need a PK in a table that doesn't have one and it's always more trouble to put it in later. I think there is more of an upside to always including one.
I suggest to do 2 things:
I could see $.ajax
is removed from jQuery slim 3.2.1
From the jQuery docs
You can also use the slim build, which excludes the ajax and effects modules
Below is the comment from the slim version with the features removed
/*! jQuery v3.2.1 -ajax,-ajax/jsonp,-ajax/load,-ajax/parseXML,-ajax/script,-ajax/var/location,-ajax/var/nonce,-ajax/var/rquery,-ajax/xhr,-manipulation/_evalUrl,-event/ajax,-effects,-effects/Tween,-effects/animatedSelector | (c) JS Foundation and other contributors | jquery.org/license */
Visual Studio Code: Version 1.14.2 (1.14.2)
At default setting, you can see this:
// Columns at which to show vertical rulers
"editor.rulers": [],
This means the empty array won't show the vertical rulers.
At right window "user setting", add the following:
"editor.rulers": [140]
Save the file, and you will see the rulers.
I like the viewer of Total Commander because it only loads the text you actually see and so is very fast. Of course, it is just a text/hex viewer, so it won't format your XML, but you can use a basic text search.
Putting #pragma once
at the top of your header file will ensure that it is only included once. Note that #pragma once
is not standard C99, but supported by most modern compilers.
An alternative is to use include guards (e.g. #ifndef MY_FILE #define MY_FILE ... #endif /* MY_FILE */
)
You can try this:
#!/bin/sh
nohup java -jar /web/server.jar &
The & symbol, switches the program to run in the background.
The nohup utility makes the command passed as an argument run in the background even after you log out.
Here's the code with parameter labels
def draw_text(self, frame, text, x, y, color=BGR_COMMON['green'], thickness=1.3, size=0.3,):
if x is not None and y is not None:
cv2.putText(
frame, text, (int(x), int(y)), cv2.FONT_HERSHEY_SIMPLEX, size, color, thickness)
For font name please see another answer in this thread.
Excerpt from answer by @Roeffus
This is indeed a bit of an annoying problem. For python 2.x.x you use:
cv2.CV_FONT_HERSHEY_SIMPLEX and for Python 3.x.x:
cv2.FONT_HERSHEY_SIMPLEX
For more see this http://www.programcreek.com/python/example/83399/cv2.putText
Make sure that you actually save the file as UTF-8, alternatively use HTML entities (&#nnn;
) for the special characters.
To modify the float output do this:
df= pd.DataFrame(range(5), columns=['a'])
df.a = df.a.astype(float)
df
Out[33]:
a
0 0.0000000
1 1.0000000
2 2.0000000
3 3.0000000
4 4.0000000
pd.options.display.float_format = '{:,.0f}'.format
df
Out[35]:
a
0 0
1 1
2 2
3 3
4 4
I use this site mostly
Its good one
Still its better preferred to test on real device..
Hope this info helps you..
you can have pointers for literals as well. You have to implement them yourself. It is pretty basic for experts ;). Use an array of int/object/long/byte and voila you have the basics for implementing pointers. Now any int value can be a pointer to that array int[]. You can increment the pointer, you can decrement the pointer, you can multiply the pointer. You indeed have pointer arithmetics! That's the only way to implements 1000 int attributes classes and have a generic method that applies to all attributes. You can also use a byte[] array instead of an int[]
However I do wish Java would let you pass literal values by reference. Something along the lines
//(* telling you it is a pointer)
public void myMethod(int* intValue);
The best answer online is at here. I tried the fifth method.
Now run your application it will work for you.
For Kotlin Users
You just need to add ? with Intent in onActivityResult
as the data can be null
if user cancels the transaction or anything goes wrong. So we need to define data as nullable
in onActivityResult
Just replace onActivityResult
signature of SampleActivity with below:
override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?)
You can use String.Format function to add second class based on condition:
<div class="@String.Format("details {0}", Details.Count > 0 ? "show" : "hide")">
#include <iostream>
#include <sstream>
std::string input = "abc,def,ghi";
std::istringstream ss(input);
std::string token;
while(std::getline(ss, token, ',')) {
std::cout << token << '\n';
}
abc
def
ghi
In AAA style using the explicitly typed initializer idiom:
#include <chrono>
#include <iostream>
int main(){
auto start = std::chrono::high_resolution_clock::now();
// Code to time here...
auto end = std::chrono::high_resolution_clock::now();
auto dur = end - start;
auto i_millis = std::chrono::duration_cast<std::chrono::milliseconds>(dur);
auto f_secs = std::chrono::duration_cast<std::chrono::duration<float>>(dur);
std::cout << i_millis.count() << '\n';
std::cout << f_secs.count() << '\n';
}
You can't commit empty folders in git. If you want it to show up, you need to put something in it, even just an empty file.
For example, add an empty file called .gitkeep
to the folder you want to keep, then in your .gitignore
file write:
# exclude everything
somefolder/*
# exception to the rule
!somefolder/.gitkeep
Commit your .gitignore
and .gitkeep
files and this should resolve your issue.
This is one of the tricky parts of Javascript, but also one of its core features. A variable declared with var
"begins its life" right where you declare it. If you leave out the var
, it's like you're talking about a variable that you have used before.
var foo = 'first time use';
foo = 'second time use';
With regards to scope, it is not true that variables automatically become global. Rather, Javascript will traverse up the scope chain to see if you have used the variable before. If it finds an instance of a variable of the same name used before, it'll use that and whatever scope it was declared in. If it doesn't encounter the variable anywhere it'll eventually hit the global object (window
in a browser) and will attach the variable to it.
var foo = "I'm global";
var bar = "So am I";
function () {
var foo = "I'm local, the previous 'foo' didn't notice a thing";
var baz = "I'm local, too";
function () {
var foo = "I'm even more local, all three 'foos' have different values";
baz = "I just changed 'baz' one scope higher, but it's still not global";
bar = "I just changed the global 'bar' variable";
xyz = "I just created a new global variable";
}
}
This behavior is really powerful when used with nested functions and callbacks. Learning about what functions
are and how scope works is the most important thing in Javascript.
Try adding the below code to the class that you want to use
[Serializable()]
public partial class Class
{
The simplest solution is to put yy,mm,dd into the date()
formula by first extracting them with left()
, mid()
and right()
. In this case, assuming your input date is in A1:
=date(right(A1,2)+100,left(A1,2),mid(A1,4,2))
Explanation of above:
=right(A1,2)
gets the last two digits in the cell (yy). We add 100 because it defaults to 1911 instead 2011 (omit +100 if it doesn't do that on yours)
=left(A1,2)
gets the first two digits in the cell (mm).
=mid(A1,4,2)
gets 2 digits in the middle of the cell, starting at 4th digit (dd).
Why this happens in the first place:
I come across this problem all the time when I import Canadian bank data into excel. In short, your input date format does not match your regional settings.
Seems your setting mean Excel wants date input as either DD-MM-YY or YY-MM-DD, but your input data is formatted as MM-DD-YY.
So, excel sees your days as months and vice-versa, which means any date with day below 12 will be recognized as a date, BUT THE WRONG DATE (month and day reversed) and any date with day above 12 won't be recognized as a date at all, because Excel sees the day as a 13th+ month.
Unfortunately, you can't just change the formatting, because Excel has already locked those day/month assignments in place, and you just end up moving what Excel THINKS are days and months around visually, not reassigning them.
Frankly, it is surprising to me there is not a date-reverse tool in excel, because I would think this happens all the time. But the formula above does it pretty simply.
NOTE: if your dates don't have leading zeros (i.e. 4/8/11 vs 04/08/12) it gets trickier because you have to extract different amounts of digits depending on the date (i.e. 4/9/11 vs 4/10/11). You then have to build a couple if statements in your formula. Gross.
Without the combined child selector you would probably do something similar to this:
foo {
bar {
baz {
color: red;
}
}
}
If you want to reproduce the same syntax with >
, you could to this:
foo {
> bar {
> baz {
color: red;
}
}
}
This compiles to this:
foo > bar > baz {
color: red;
}
Or in sass:
foo
> bar
> baz
color: red
Using Jquery
Rather than creating temp variables it can be written in a continuous flow pattern as follows:
$('</form>', { action: url, method: 'POST' }).append(
$('<input>', {type: 'hidden', id: 'id_field_1', name: 'name_field_1', value: val_field_1}),
$('<input>', {type: 'hidden', id: 'id_field_2', name: 'name_field_2', value: val_field_2}),
).appendTo('body').submit();
first check with instanceof keyword . if true then cast it.
Note that one difference between git remote --prune
and git fetch --prune
is being fixed, with commit 10a6cc8, by Tom Miller (tmiller
) (for git 1.9/2.0, Q1 2014):
When we have a remote-tracking branch named "
frotz/nitfol
" from a previous fetch, and the upstream now has a branch named "**frotz"**,fetch
would fail to remove "frotz/nitfol
" with a "git fetch --prune
" from the upstream.
git would inform the user to use "git remote prune
" to fix the problem.
So: when a upstream repo has a branch ("frotz") with the same name as a branch hierarchy ("frotz/xxx", a possible branch naming convention), git remote --prune
was succeeding (in cleaning up the remote tracking branch from your repo), but git fetch --prune
was failing.
Not anymore:
Change the way "
fetch --prune
" works by moving the pruning operation before the fetching operation.
This way, instead of warning the user of a conflict, it automatically fixes it.
Annoyingly, the withTimeAtStartOfDay answer is wrong, but only occasionally. You want:
Days.daysBetween(start.toLocalDate(), end.toLocalDate()).getDays()
It turns out that "midnight/start of day" sometimes means 1am (daylight savings happen this way in some places), which Days.daysBetween doesn't handle properly.
// 5am on the 20th to 1pm on the 21st, October 2013, Brazil
DateTimeZone BRAZIL = DateTimeZone.forID("America/Sao_Paulo");
DateTime start = new DateTime(2013, 10, 20, 5, 0, 0, BRAZIL);
DateTime end = new DateTime(2013, 10, 21, 13, 0, 0, BRAZIL);
System.out.println(daysBetween(start.withTimeAtStartOfDay(),
end.withTimeAtStartOfDay()).getDays());
// prints 0
System.out.println(daysBetween(start.toLocalDate(),
end.toLocalDate()).getDays());
// prints 1
Going via a LocalDate
sidesteps the whole issue.
The user @manoj has provided the correct answer to the question. From Kibana host, a request to http://localhost:9200/ will not be answered, unless ElasticSearch is also running on the same node. Kibana listens on port 5601 not 9200.
In most cases, except for DEV, ElasticSearch will not be on the same node as Kibana, for a number of reasons. Therefore, to get information about your ElasticSearch from Kibana, you should select the "Dev Tools" tab on the left and in the console issue the command: GET /
python: read lines from compressed text files
Using gzip.GzipFile
:
import gzip
with gzip.open('input.gz','r') as fin:
for line in fin:
print('got line', line)
Since -f
caused another problem, I developed another solution.
The -f
flag does not solved my problem because my onbuild
image looks for a file in a folder and had to call like this:
-f foo/bar/Dockerfile foo/bar
instead of
-f foo/bar/Dockerfile .
Also note that this is only solution for some cases as -f
flag
For MAC users:
1. Open terminal
cd ~
2. Double check the $PATH
echo $PATH
3. Edit file
nano ~/.bash_profile
4. PASTE
export PATH="~/.composer/vendor/bin:$PATH"
Don't forget to put quotation marks.
5. control + X (y + enter to save the file and exit)
Now start vagrant, go to your folder and try:
laravel new yourprojectname
npm install -g increase-memory-limit
increase-memory-limit
OR
C:\Users\{user_name}\AppData\Roaming\npm
--max_old_space_size=8192
to the IF
and ELSE
blocknow ng.cmd file looks like this after the change:
@IF EXIST "%~dp0\node.exe" (
"%~dp0\node.exe" "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
) ELSE (
@SETLOCAL
@SET PATHEXT=%PATHEXT:;.JS;=;%
node "--max_old_space_size=8192" "%~dp0\node_modules\@angular\cli\bin\ng" %*
)
You probably want
list2.extend(list1)
instead of
list2.append(list1)
Here's the difference:
>>> a = range(5)
>>> b = range(3)
>>> c = range(2)
>>> b.append(a)
>>> b
[0, 1, 2, [0, 1, 2, 3, 4]]
>>> c.extend(a)
>>> c
[0, 1, 0, 1, 2, 3, 4]
Since list.extend()
accepts an arbitrary iterable, you can also replace
for line in mylog:
list1.append(line)
by
list1.extend(mylog)
Why should not use jquery popup for this purpose.I use bpopup
for this purpose.See more about this.
http://dinbror.dk/bpopup/
In my opinion this is the simplest solution
$orderby = 'name';
$order = 'asc';
$hide_empty = false ;
$cat_args = array(
'orderby' => $orderby,
'order' => $order,
'hide_empty' => $hide_empty,
);
$product_categories = get_terms( 'product_cat', $cat_args );
if( !empty($product_categories) ){
echo '
<ul>';
foreach ($product_categories as $key => $category) {
echo '
<li>';
echo '<a href="'.get_term_link($category).'" >';
echo $category->name;
echo '</a>';
echo '</li>';
}
echo '</ul>
';
}
Use Fail module.
- fail: msg="The execution has failed because of errors." when: flag == "failed"
Update:
Use register to store the result of a task like you have shown in your example. Then, use a task like this:
- name: Set flag
set_fact: flag = failed
when: "'FAILED' in command_result.stderr"
You should use below method-
Math.pow(double a, double b)
Returns the value of the first argument raised to the power of the second argument.
Extending this more from m.kocikowski's and Dan J's answers with more explanation for newbies
1# First you have to create objective-c-categories to make the code useable in any class.
.h
@interface NSString (NAME_OF_CATEGORY)
- (NSString *)stringByStrippingHTML;
@end
.m
@implementation NSString (NAME_OF_CATEGORY)
- (NSString *)stringByStrippingHTML
{
NSMutableString *outString;
NSString *inputString = self;
if (inputString)
{
outString = [[NSMutableString alloc] initWithString:inputString];
if ([inputString length] > 0)
{
NSRange r;
while ((r = [outString rangeOfString:@"<[^>]+>" options:NSRegularExpressionSearch]).location != NSNotFound)
{
[outString deleteCharactersInRange:r];
}
}
}
return outString;
}
@end
2# Then just import the .h file of the category class you've just created e.g.
#import "NSString+NAME_OF_CATEGORY.h"
3# Calling the Method.
NSString* sub = [result stringByStrippingHTML];
NSLog(@"%@", sub);
result is NSString I want to strip the tags from.
Well what you have to "import" (use) is the namespace of MyClass
not the class name itself. If both classes are in the same namespace, you don't have to "import" it.
Definition MyClass.cs
namespace Ns1
{
public class MyClass
{
...
}
}
Usage AnotherClass.cs
using Ns1;
namespace AnotherNs
{
public class AnotherClass
{
public AnotherClass()
{
var myInst = new MyClass();
}
}
}
With HTML5 specification you do not need to write too much JS for the same or find some hacks.
One of the feature introduced in HTML5 is Web Workers which is JavaScript running in the background,independently of other scripts, without affecting the performance of the page.
It is supported in almost all browsers :
Chrome - 4.0+
IE - 10.0+
Mozilla - 3.5+
Safari - 4.0+
Opera - 11.5+
Since money needs an exact representation don't use data types that are only approximate like float
. You can use a fixed-point numeric data type for that like
decimal(15,2)
15
is the precision (total length of value including decimal places)2
is the number of digits after decimal pointSee MySQL Numeric Types:
These types are used when it is important to preserve exact precision, for example with monetary data.
I find that if you're familiar with SQL syntax, using the LINQ query syntax is much clearer, more natural, and makes it easier to spot errors:
var id = 1;
var query =
from post in database.Posts
join meta in database.Post_Metas on post.ID equals meta.Post_ID
where post.ID == id
select new { Post = post, Meta = meta };
If you're really stuck on using lambdas though, your syntax is quite a bit off. Here's the same query, using the LINQ extension methods:
var id = 1;
var query = database.Posts // your starting point - table in the "from" statement
.Join(database.Post_Metas, // the source table of the inner join
post => post.ID, // Select the primary key (the first part of the "on" clause in an sql "join" statement)
meta => meta.Post_ID, // Select the foreign key (the second part of the "on" clause)
(post, meta) => new { Post = post, Meta = meta }) // selection
.Where(postAndMeta => postAndMeta.Post.ID == id); // where statement
if exist <insert file name here> (
rem file exists
) else (
rem file doesn't exist
)
Or on a single line (if only a single action needs to occur):
if exist <insert file name here> <action>
for example, this opens notepad on autoexec.bat, if the file exists:
if exist c:\autoexec.bat notepad c:\autoexec.bat
It seems that the only parameter that allows you to inject custom text is the "quote".
https://www.facebook.com/sharer/sharer.php?u=THE_URL"e=THE_CUSTOM_TEXT
you can add the selected values in an array
and set it as the value for default selection
eg:
var selectedItems =[];
selectedItems.push("your selected items");
..
$('#drp_Books_Ill_Illustrations').select2('val',selectedItems );
Try this, this should definitely work!
"Headers already sent" means that your PHP script already sent the HTTP headers, and as such it can't make modifications to them now.
Check that you don't send ANY content before calling session_start
. Better yet, just make session_start
the first thing you do in your PHP file (so put it at the absolute beginning, before all HTML etc).
I suggest to use a container for each img
p
like this:
<div class="image123">
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif" height="200" width="200" />
<p style="text-align:center;">This is image 1</p>
</div>
<div style="float:left;margin-right:5px;">
<img class="middle-img" src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 2</p>
</div>
<div style="float:left;margin-right:5px;">
<img src="/images/tv.gif/" height="200" width="200" />
<p style="text-align:center;">This is image 3</p>
</div>
</div>
Then apply float:left
to each container. I add and 5px
margin right
so there is a space between each image. Also alway close your elements. Maybe in html img
tag is not important to close but in XHTML is.
Also a friendly advice. Try to avoid inline styles as much as possible. Take a look here:
html
<div class="image123">
<div>
<img src="/images/tv.gif" />
<p>This is image 1</p>
</div>
<div>
<img class="middle-img" src="/images/tv.gif/" />
<p>This is image 2</p>
</div>
<div>
<img src="/images/tv.gif/" />
<p>This is image 3</p>
</div>
</div>
css
div{
float:left;
margin-right:5px;
}
div > img{
height:200px;
width:200px;
}
p{
text-align:center;
}
It's generally recommended that you use linked style sheets because:
Use following if value is string (e.g. from <input
):
Math.floor(value).toString() !== value
I add .toString()
to floor to make it work also for cases when value == "1."
(ends with decimal separator or another string). Also Math.floor
always returns some value so .toString()
never fails.
This is the reason why Factory Patterns and other creational patterns are so popular in Java. You are correct that without them Java doesn't provide an out of the box mechanism for easy abstraction of instantiation. Still, you get abstraction everywhere where you don't create an object in your method, which should be most of your code.
As an aside, I generally encourage people to not follow the "IRealname" mechanism for naming interfaces. That's a Windows/COM thing that puts one foot in the grave of Hungarian notation and really isn't necessary (Java is already strongly typed, and the whole point of having interfaces is to have them as largely indistinguishable from class types as possible).
How about doing it like this:
1) show popup with form
2) submit form using AJAX
3) in AJAX server side code, render response that will either:
In MySQL, certain words like SELECT
, INSERT
, DELETE
etc. are reserved words. Since they have a special meaning, MySQL treats it as a syntax error whenever you use them as a table name, column name, or other kind of identifier - unless you surround the identifier with backticks.
As noted in the official docs, in section 10.2 Schema Object Names (emphasis added):
Certain objects within MySQL, including database, table, index, column, alias, view, stored procedure, partition, tablespace, and other object names are known as identifiers.
...
If an identifier contains special characters or is a reserved word, you must quote it whenever you refer to it.
...
The identifier quote character is the backtick ("
`
"):
A complete list of keywords and reserved words can be found in section 10.3 Keywords and Reserved Words. In that page, words followed by "(R)" are reserved words. Some reserved words are listed below, including many that tend to cause this issue.
You have two options.
The simplest solution is simply to avoid using reserved words as identifiers. You can probably find another reasonable name for your column that is not a reserved word.
Doing this has a couple of advantages:
It eliminates the possibility that you or another developer using your database will accidentally write a syntax error due to forgetting - or not knowing - that a particular identifier is a reserved word. There are many reserved words in MySQL and most developers are unlikely to know all of them. By not using these words in the first place, you avoid leaving traps for yourself or future developers.
The means of quoting identifiers differs between SQL dialects. While MySQL uses backticks for quoting identifiers by default, ANSI-compliant SQL (and indeed MySQL in ANSI SQL mode, as noted here) uses double quotes for quoting identifiers. As such, queries that quote identifiers with backticks are less easily portable to other SQL dialects.
Purely for the sake of reducing the risk of future mistakes, this is usually a wiser course of action than backtick-quoting the identifier.
If renaming the table or column isn't possible, wrap the offending identifier in backticks (`
) as described in the earlier quote from 10.2 Schema Object Names.
An example to demonstrate the usage (taken from 10.3 Keywords and Reserved Words):
mysql> CREATE TABLE interval (begin INT, end INT); ERROR 1064 (42000): You have an error in your SQL syntax. near 'interval (begin INT, end INT)'
mysql> CREATE TABLE `interval` (begin INT, end INT); Query OK, 0 rows affected (0.01 sec)
Similarly, the query from the question can be fixed by wrapping the keyword key
in backticks, as shown below:
INSERT INTO user_details (username, location, `key`)
VALUES ('Tim', 'Florida', 42)"; ^ ^
Use the DateFormat
API to convert the String into a Date object, then use the Calendar
API to add one day. Let me know if you want specific code examples, and I can update my answer.
<a data-title="A Title" data-placement="top" data-html="true" data-content="<form><input type='text'/></form>" data-trigger="hover" rel="popover" class="btn btn-primary" id="test">Top popover</a>
just state data-html="true"
console.log( Object.keys( {'a':1,'b':2} ) );
os.system
is equivalent to Unix system
command, while subprocess
was a helper module created to provide many of the facilities provided by the Popen
commands with an easier and controllable interface. Those were designed similar to the Unix Popen command.
system()
executes a command specified in command by calling/bin/sh -c command
, and returns after the command has been completed
Whereas:
The
popen()
function opens a process by creating a pipe, forking, and invoking the shell.
If you are thinking which one to use, then use subprocess
definitely because you have all the facilities for execution, plus additional control over the process.
File.exist?("directory")
Dir[]
returns an array, so it will never be nil
. If you want to do it your way, you could do
Dir["directory"].empty?
which will return true
if it wasn't found.
Looks like a Windows Forms project that is trying to use a startup form but for some reason the project properties is set to startup being Main.
If you have enabled application framework you may not be able to see that Main is active (this is an invalid configuration).
The second argument Title does not mean Title of the page - It is more of a definition/information for the state of that page
But we can still change the title using onpopstate event, and passing the title name not from the second argument, but as an attribute from the first parameter passed as object
Reference: http://spoiledmilk.com/blog/html5-changing-the-browser-url-without-refreshing-page/
$(".datepicker").datepicker().on("changeDate", function(e) {
console.log("Date changed: ", e.date);
});
This also works:
this.getCurrentFocus()
It gets the view so I can use it.
One way to do that is to use a counter:
ArrayList<Integer> list = new ArrayList<Integer>();
...
int size = list.size();
for (Integer i : list) {
...
if (--size == 0) {
// Last item.
...
}
}
Edit
Anyway, as Tom Hawtin said, it is sometimes better to use the "old" syntax when you need to get the current index information, by using a for
loop or the iterator
, as everything you win when using the Java5 syntax will be lost in the loop itself...
for (int i = 0; i < list.size(); i++) {
...
if (i == (list.size() - 1)) {
// Last item...
}
}
or
for (Iterator it = list.iterator(); it.hasNext(); ) {
...
if (!it.hasNext()) {
// Last item...
}
}
Using the google maps projection api to draw the polylines on an overlay view enables us to do a lot of things. Check this repo that has an example.
The float value is stored in IEEE 754 format so we can't convert it directly like integer, char to binary.
But we can convert float to binary through a pointer.
#include <stdio.h>
int main()
{
float a = 7.5;
int i;
int * p;
p = &a;
for (i = sizeof(int) * 8 - 1; i >= 0; i--)
{
printf("%d", (*p) >> i & 1);
}
return 0;
}
Output
0 10000001 11100000000000000000000
Spaces added for clarification, they are not included as part of the program.
$(window).height(); // returns height of browser viewport
$(document).height(); // returns height of HTML document
As documented here: http://api.jquery.com/height/
How about this :
// Checks to see if the value passed is valid.
if (!TypeDescriptor.GetConverter(typeof(T)).IsValid(value))
{
throw new ArgumentException();
}
You have a ; at the end of the if
.
Change:
if (fp == NULL);
return 0;
to
if (fp == NULL)
return 0;
You are inside vim. To save changes and quit, type:
<esc> :wq <enter>
That means:
:wq
An alternative that stdcall in the comments mentions is:
Z
twice).SELECT Lname, Cods, CASE WHEN Lname LIKE '% HN%' THEN SUBSTRING(Lname,
CHARINDEX(' ', Lname) - 50, 50) WHEN Lname LIKE 'HN%' THEN Lname ELSE
Lname END AS LnameTrue FROM dbo.____Fname_Lname
You can call it three ways - with parameters, with DEFAULT and via EXECUTE
SET NOCOUNT ON;
DECLARE
@Table SYSNAME = 'YourTable',
@Schema SYSNAME = 'dbo',
@Rows INT;
SELECT dbo.TableRowCount( @Table, @Schema )
SELECT dbo.TableRowCount( @Table, DEFAULT )
EXECUTE @Rows = dbo.TableRowCount @Table
SELECT @Rows
[.\n]
does not work because .
has no special meaning inside of []
, it just means a literal .
. (.|\n)
would be a way to specify "any character, including a newline". If you want to match all newlines, you would need to add \r
as well to include Windows and classic Mac OS style line endings: (.|[\r\n])
.
That turns out to be somewhat cumbersome, as well as slow, (see KrisWebDev's answer for details), so a better approach would be to match all whitespace characters and all non-whitespace characters, with [\s\S]
, which will match everything, and is faster and simpler.
In general, you shouldn't try to use a regexp to match the actual HTML tags. See, for instance, these questions for more information on why.
Instead, try actually searching the DOM for the tag you need (using jQuery makes this easier, but you can always do document.getElementsByTagName("pre")
with the standard DOM), and then search the text content of those results with a regexp if you need to match against the contents.
Another approach to solve this, question:
public class CollectionUtils {
/**
* Splits the collection into lists with given batch size
* @param collection to split in to batches
* @param batchsize size of the batch
* @param <T> it maintains the input type to output type
* @return nested list
*/
public static <T> List<List<T>> makeBatch(Collection<T> collection, int batchsize) {
List<List<T>> totalArrayList = new ArrayList<>();
List<T> tempItems = new ArrayList<>();
Iterator<T> iterator = collection.iterator();
for (int i = 0; i < collection.size(); i++) {
tempItems.add(iterator.next());
if ((i+1) % batchsize == 0) {
totalArrayList.add(tempItems);
tempItems = new ArrayList<>();
}
}
if (tempItems.size() > 0) {
totalArrayList.add(tempItems);
}
return totalArrayList;
}
}
Bootswatch is a good alternative, but you can also find multiple types of free templates made for ASP.NET MVC that use MDBootstrap (a front-end framework built on top of Bootstrap) here:
The operating system is also a program, so we can also create our own program by creating from scratch or changing (limiting or adding) features of one of the small operating systems, and then run it during the boot process (using an ISO image).
For example, this page can be used as a starting point:
How to write a simple operating system
Here, the entire Operating System fit entirely in a 512-byte boot sector (MBR)!
Such or similar simple OS can be used to create a simple framework that will allow us:
make the bootloader load subsequent sectors on the disk into RAM, and jump to that point to continue execution. Or you could read up on FAT12, the filesystem used on floppy drives, and implement that.
There are many possibilities, however. For for example to see a bigger x86 assembly language OS we can explore the MykeOS, x86 operating system which is a learning tool to show the simple 16-bit, real-mode OSes work, with well-commented code and extensive documentation.
Other common type of programs that run without the operating system are also Boot Loaders. We can create a program inspired by such a concept for example using this site:
How to develop your own Boot Loader
The above article presents also the basic architecture of such a programs:
- Correct loading to the memory by 0000:7C00 address.
- Calling the BootMain function that is developed in the high-level language.
- Show “”Hello, world…”, from low-level” message on the display.
As we can see, this architecture is very flexible and allows us to implement any program, not necessarily a boot loader.
In particular, it shows how to use the "mixed code" technique thanks to which it is possible to combine high-level constructions (from C or C++) with low-level commands (from Assembler). This is a very useful method, but we have to remember that:
to build the program and obtain executable file you will need the compiler and linker of Assembler for 16-bit mode. For C/C++ you will need only the compiler that can create object files for 16-bit mode.
The article shows also how to see the created program in action and how to perform its testing and debug.
The above examples used the fact of loading the sector MBR on the data medium. However, we can go deeper into the depths by plaing for example with the UEFI applications:
Beyond loading an OS, UEFI can run UEFI applications, which reside as files on the EFI System Partition. They can be executed from the UEFI command shell, by the firmware's boot manager, or by other UEFI applications. UEFI applications can be developed and installed independently of the system manufacturer.
A type of UEFI application is an OS loader such as GRUB, rEFInd, Gummiboot, and Windows Boot Manager; which loads an OS file into memory and executes it. Also, an OS loader can provide a user interface to allow the selection of another UEFI application to run. Utilities like the UEFI shell are also UEFI applications.
If we would like to start creating such programs, we can, for example, start with these websites:
Programming for EFI: Creating a "Hello, World" Program / UEFI Programming - First Steps
It is well known that there is a whole group of malicious software (which are programs) that are running before the operating system starts.
A huge group of them operate on the MBR sector or UEFI applications, just like the all above solutions, but there are also those that use another entry point such as the Volume Boot Record (VBR) or the BIOS:
There are at least four known BIOS attack viruses, two of which were for demonstration purposes.
or perhaps another one too.
Bootkits have evolved from Proof-of-Concept development to mass distribution and have now effectively become open-source software.
I also think that in this context it is also worth mentioning that there are various forms of booting the operating system (or the executable program intended for this). There are many, but I would like to pay attention to loading the code from the network using Network Boot option (PXE), which allows us to run the program on the computer regardless of its operating system and even regardless of any storage medium that is directly connected to the computer:
The difference is subtle but important. The MOV instruction is a 'MOVe' effectively a copy of the address that the TABLE-ADDR label stands for. The LEA instruction is a 'Load Effective Address' which is an indirected instruction, which means that TABLE-ADDR points to a memory location at which the address to load is found.
Effectively using LEA is equivalent to using pointers in languages such as C, as such it is a powerful instruction.
Use the following syntax:
ALTER TABLE your_table
MODIFY COLUMN column1 datatype,
MODIFY COLUMN column2 datatype,
... ... ... ... ...
... ... ... ... ...
Based on that, your ALTER
command should be:
ALTER TABLE webstore.Store
MODIFY COLUMN ShortName VARCHAR(100),
MODIFY COLUMN UrlShort VARCHAR(100)
Note that:
MODIFY
statements.MODIFY
statements for two separate columns.This is the standard format of the MODIFY
statement for an ALTER
command on multiple columns in a MySQL table.
Take a look at the following: http://dev.mysql.com/doc/refman/5.1/en/alter-table.html and Alter multiple columns in a single statement
I just want to give the solution that I came up with that handles all cases presented in this post that I derived from Vasek and devconsole. This solution also handles the special case when the phone is rotated more than once while fragments aren't visible.
Here is were I store the bundle for later use since onCreate and onSaveInstanceState are the only calls that are made when the fragment isn't visible
MyObject myObject;
private Bundle savedState = null;
private boolean createdStateInDestroyView;
private static final String SAVED_BUNDLE_TAG = "saved_bundle";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState != null) {
savedState = savedInstanceState.getBundle(SAVED_BUNDLE_TAG);
}
}
Since destroyView isn't called in the special rotation situation we can be certain that if it creates the state we should use it.
@Override
public void onDestroyView() {
super.onDestroyView();
savedState = saveState();
createdStateInDestroyView = true;
myObject = null;
}
This part would be the same.
private Bundle saveState() {
Bundle state = new Bundle();
state.putSerializable(SAVED_BUNDLE_TAG, myObject);
return state;
}
Now here is the tricky part. In my onActivityCreated method I instantiate the "myObject" variable but the rotation happens onActivity and onCreateView don't get called. Therefor, myObject will be null in this situation when the orientation rotates more than once. I get around this by reusing the same bundle that was saved in onCreate as the out going bundle.
@Override
public void onSaveInstanceState(Bundle outState) {
if (myObject == null) {
outState.putBundle(SAVED_BUNDLE_TAG, savedState);
} else {
outState.putBundle(SAVED_BUNDLE_TAG, createdStateInDestroyView ? savedState : saveState());
}
createdStateInDestroyView = false;
super.onSaveInstanceState(outState);
}
Now wherever you want to restore the state just use the savedState bundle
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
...
if(savedState != null) {
myObject = (MyObject) savedState.getSerializable(SAVED_BUNDLE_TAG);
}
...
}
When posting an HTML checkbox to the server, it has a string value of 'on' or ''.
Readonly does not stop the user editing the checkbox, and disabled stops the value being posted back.
One way around this is to have a hidden element to store the actual value and the displayed checkbox is a dummy which is disabled. This way the checkbox state is persisted between posts.
Here is a function to do this. It uses a string of 'T' or 'F' and you can change this any way you like. This has been used in an ASP page using server side VB script.
public function MakeDummyReadonlyCheckbox(i_strName, i_strChecked_TorF)
dim strThisCheckedValue
if (i_strChecked_TorF = "T") then
strThisCheckedValue = " checked "
i_strChecked_TorF = "on"
else
strThisCheckedValue = ""
i_strChecked_TorF = ""
end if
MakeDummyReadonlyCheckbox = "<input type='hidden' id='" & i_strName & "' name='" & i_strName & "' " & _
"value='" & i_strChecked_TorF & "'>" & _
"<input type='checkbox' disabled id='" & i_strName & "Dummy' name='" & i_strName & "Dummy' " & _
strThisCheckedValue & ">"
end function
public function GetCheckbox(i_objCheckbox)
select case trim(i_objCheckbox)
case ""
GetCheckbox = "F"
case else
GetCheckbox = "T"
end select
end function
At the top of an ASP page you can pickup the persisted value...
strDataValue = GetCheckbox(Request.Form("chkTest"))
and when you want to output your checkbox you can do this...
response.write MakeDummyReadonlyCheckbox("chkTest", strDataValue)
I have tested this and it works just fine. It also does not rely upon JavaScript.
If you can link to a C library, you can use libenca
. See http://cihar.com/software/enca/. From the man page:
Enca reads given text files, or standard input when none are given, and uses knowledge about their language (must be supported by you) and a mixture of parsing, statistical analysis, guessing and black magic to determine their encodings.
It's GPL v2.
Having trouble wrapping my head around this.
Have a rewrite rule with four conditions.
The first three conditions A, B, C are to be AND which is then OR with D
RewriteCond A true
RewriteCond B false
RewriteCond C [OR] true
RewriteCond D true
RewriteRule ...
But that seems to be an expression of A and B and (C or D) = false (don't rewrite)
How can I get to the desired expression? (A and B and C) or D = true (rewrite)
Preferably without using the additional steps of setting environment variables.
HELP!!!
Unfortunately, the string.encode() method is not always reliable. Check out this thread for more information: What is the fool proof way to convert some string (utf-8 or else) to a simple ASCII string in python
You can add a Form and name it as Form1, add a Frame to it as Frame1 as well as Label1 too. Set Frame1 width to 200, Back Color to Blue. Place the code in the module and check if it helps.
Sub Main()
Dim i As Integer
Dim response
Form1.Show vbModeless
Form1.Frame1.Width = 0
For i = 10 To 10000
With Form1
.Label1.Caption = Round(i / 100, 0) & "%"
.Frame1.Width = Round(i / 100, 0) * 2
DoEvents
End With
Next i
Application.Wait Now + 0.0000075
Unload Form1
response = MsgBox("100% Done", vbOKOnly)
End Sub
If you want to display on the Status Bar then you can use other way that's simpler:
Sub Main()
Dim i As Integer
Dim response
For i = 10 To 10000
Application.StatusBar = Round(i / 100, 0) & "%"
Next i
Application.Wait Now + 0.0000075
response = MsgBox("100% Done", vbOKOnly)
End Sub
Loop over Application.Current.Windows[]
and find the one with IsActive == true
.
please set dataType config property in your ajax call and give it another try!
another point is you are using ajax call setup configuration properties as string and it is wrong as reference site
$.ajax({
url : 'http://voicebunny.comeze.com/index.php',
type : 'GET',
data : {
'numberOfWords' : 10
},
dataType:'json',
success : function(data) {
alert('Data: '+data);
},
error : function(request,error)
{
alert("Request: "+JSON.stringify(request));
}
});
I hope be helpful!
Even if old, this seems to be a popular questions, so I'll post another solution, which I think is very elegant:
http://fiveminutelessons.com/learn-microsoft-excel/using-multiple-if-statements-excel
It's elegant because it uses just the IF function. Basically, it boils down to this:
if(condition, choose/use a value from the table, if(condition, choose/use another value from the table...
And so on
Works beautifully, even better than HLOOKUP or VLOOOKUP
but... Be warned - there is a limit to the number of nested if statements excel can handle.
For CentOS, do:
sudo yum install php-mysqli
try:
gsub('\\$', '', '$5.00$')
No, you can't.
There's no reason why you would need to. This is a one-time operation and so takes only an additional second or two to actually type and execute.
If you're adding columns in your web application this is more indicative of a flaw in your data-model as you shouldn't need to be doing it.
In response to your comment that a comment is a column attribute; it may seem so but behind the scenes Oracle stores this as an attribute of an object.
SQL> desc sys.com$
Name Null? Type
----------------------------------------- -------- ----------------------------
OBJ# NOT NULL NUMBER
COL# NUMBER
COMMENT$ VARCHAR2(4000)
SQL>
The column is optional and sys.col$
does not contain comment information.
I assume, I have no knowledge, that this was done in order to only have one system of dealing with comments rather than multiple.
Maybe the easiest way is. Get the DeviceId Nuget package
And use it like
string deviceId = new DeviceIdBuilder()
.AddMachineName()
.AddMacAddress()
.AddProcessorId()
.AddMotherboardSerialNumber()
.ToString();
You can personalize the info used to generate the ID
The getContentResolver()
method is also used when you query a Contact
, using a Cursor
object. I have used getContentResolver()
to query the Android phone Contacts
app, looking for contact info from a person's phone number, to include in my app. The different elements in a query (as shown below) represent what kind of contact details you want, and if they should be ordered, etc. Here is another example.
From the Content Provider Basics page from Android docs.
// Queries the user dictionary and returns results
mCursor = getContentResolver().query(
UserDictionary.Words.CONTENT_URI, // The content URI of the words table
mProjection, // The columns to return for each row
mSelectionClause // Selection criteria
mSelectionArgs, // Selection criteria
mSortOrder); // The sort order for the returned rows
All of the above responses seem to obscure the simplicity of the answer or have some nuances that are not explained.
If the file is shared publicly, you can generate a direct download link by just knowing the file ID. The URL must be in the form " https://drive.google.com/uc?id=[FILEID]&export=download" This works as of 11-22-2019. This does not require the receiver to log in to google but does require the file to be shared publicly.
In your browser, navigate to drive.google.com.
Right click on the file, and click "Get a shareable link"
Edit the URL so it is in the following format, replacing "[FILEID]" with the ID of your shared file:
That's your direct download link. If you click on it in your browser the file will now be "pushed" to your browser, opening the download dialog, allowing you to save or open the file. You can also use this link in your download scripts.
So the equivalent curl command would be:
curl -L "https://drive.google.com/uc?id=AgOATNfjpovfFrft9QYa-P1IeF9e7GWcH&export=download" > phlat-1.0.tar.gz
You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.
I had same problem. i fixed it. i was using Codeblocks and i save my .cpp file on desktop instead of saving it in Codeblocks file where MinGW is located. So i copied all dll files from MinGW>>bin folder to where my .cpp file was saved.
Of course it would be more simple if you extend jQuery like this:
$.fn.addClassDelay = function(className,delay) {
var $addClassDelayElement = $(this), $addClassName = className;
$addClassDelayElement.addClass($addClassName);
setTimeout(function(){
$addClassDelayElement.removeClass($addClassName);
},delay);
};
after that you can use this function like addClass:
$('div').addClassDelay('clicked',1000);
Setting cookie in the express is easy
npm install cookie parser
const cookieParser = require('cookie-parser');
app.use(cookieParser());
res.cookie('cookieName', '1', { expires: new Date(Date.now() + 900000), httpOnly: true })
console.dir(req.cookies.cookieName)
It's worth noting also that the yank registers are the same as the macro buffers. In other words, you can simply write out your whole command in your document (including your pasted snippet), then "by
to yank it to the b
register, and then run it with @b
.
No one has mentioned this yet, and this may not be a common problem, but I had a similar problem with Xcode 5: Make sure you have a default keychain selected in the Mac's Keychain Access. I trying out a fresh install of Mountain Lion and deleted one keychain, which happened to be the default. After setting another keychain as the default (right-click on the keychain and select Make Keychain "Keychain_name" default"), Xcode was able to set up the valid signing identities.
Try the following:
T[] r1 = new T[size1];
T[] r2 = new T[size2];
List<T> targetList = new List<T>(r1);
targetList.Concat(r2);
T[] targetArray = targetList.ToArray();
In fact, your data is not well design. You'd better use something like :
$scope.steps = [
{stepName: "companyName", isComplete: true},
{stepName: "businessType", isComplete: true},
{stepName: "physicalAddress", isComplete: true}
];
Then it is easy to do what you want :
<div ng-repeat="step in steps">
Step {{step.stepName}} status : {{step.isComplet}}
</div>
Example: http://jsfiddle.net/rX7ba/
No, but you can use the s///
substitution operator and the \s
whitespace assertion to get the same result.
In [21]: df = pd.DataFrame([(1,2,3), ('foo','bar','baz'), (4,5,6)])
In [22]: df
Out[22]:
0 1 2
0 1 2 3
1 foo bar baz
2 4 5 6
Set the column labels to equal the values in the 2nd row (index location 1):
In [23]: df.columns = df.iloc[1]
If the index has unique labels, you can drop the 2nd row using:
In [24]: df.drop(df.index[1])
Out[24]:
1 foo bar baz
0 1 2 3
2 4 5 6
If the index is not unique, you could use:
In [133]: df.iloc[pd.RangeIndex(len(df)).drop(1)]
Out[133]:
1 foo bar baz
0 1 2 3
2 4 5 6
Using df.drop(df.index[1])
removes all rows with the same label as the second row. Because non-unique indexes can lead to stumbling blocks (or potential bugs) like this, it's often better to take care that the index is unique (even though Pandas does not require it).
Not directly, but you can extend the class to modify its get method. Here is a ready to use example: http://www.java2s.com/Code/Java/Collections-Data-Structure/ExtendedVersionofjavautilHashMapthatprovidesanextendedgetmethodaccpetingadefaultvalue.htm
Not exactly the same as NUnit's Value
(or TestCase
) attributes, but MSTest has the DataSource
attribute, which allows you to do a similar thing.
You can hook it up to database or XML file - it is not as straightforward as NUnit's feature, but it does the job.
Note that cp A B; rm A
is exactly mv A B
. It'll be faster too, as you don't have to actually copy the bytes (assuming the destination is on the same filesystem), just rename the file. So you want cp A B; mv A C
In the default settings, VS Code uses the following fonts (14 pt) in descending order:
How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.
Sometimes you do get focus but no cursor in a text field. In this case you would do this:
document.getElementById(frmObj.id).select();
Try to login via the terminal using the following command:
mysql -u root -p
It will then prompt for your password. If this fails, then definitely the username or password is incorrect. If this works, then your database's password needs to be enclosed in quotes:
database_password: "0000"
Because %
is only defined for integer types. That's the modulus operator.
5.6.2 of the standard:
The operands of * and / shall have arithmetic or enumeration type; the operands of % shall have integral or enumeration type. [...]
As Oli pointed out, you can use fmod()
. Don't forget to include math.h
.
cache: false,
url: "addInterview_Code.asp",
type: "POST",
datatype: "text",
data: strData,
success: function (html) {
alert('successful : ' + html);
$("#result").html("Successful");
},
error: function(data, errorThrown)
{
alert('request failed :'+errorThrown);
}
For the first one remove the spaces. Whitespace matters for the set command.
set guifont=Monaco:h20
For the second one it should be (the h specifies the height)
set guifont=Monospace:h20
My recommendation for setting the font is to do (if your version supports it)
set guifont=*
This will pop up a menu that allows you to select the font. After selecting the font, type
set guifont?
To show what the current guifont is set to. After that copy that line into your vimrc or gvimrc. If there are spaces in the font add a \
to escape the space.
set guifont=Monospace\ 20
Here is a quick fix:
All the pros will probably hate me for this answer. But I got the same error on a server: Fatal error: Uncaught Error: Call to undefined function mysql_connect() that was using PHP 7. Did not have time to rewrite all the mysql code so a quick, temporary fix if anyone needs it is in CPANEL to look for PHP Configuration and change the version for that account to something like PHP 5.4 instead of PHP 7. Then the code worked fine without the above error.