Try renaming your 'proguard-rules.txt' file to 'proguard-android.txt' and remove the reference to 'proguard-rules.txt' in your gradle file. The getDefaultProguardFile(...)
call references a different default proguard file, one provided by Google and not that in your project. So remove this as well, so that here the gradle file reads:
buildTypes {
release {
runProguard true
proguardFile 'proguard-android.txt'
}
}
I believe those installers make changes to the path. Did you try closing and re-opening the CMD window after running them and before the last attempt to install the gem that wants devkit present?
Also, be sure you are using the right devkit installer for your version of Ruby. The documentation at devkit wiki page has a requirements note saying:
For RubyInstaller versions 1.8.7, 1.9.2, and 1.9.3 use the DevKit 4.5.2
try: window.document......
var body = window.document.getElementsByTagName("body")[0];
According to the Twitter Bootstrap documentation: http://getbootstrap.com/css/#helper-classes-center
<!-- Button -->
<div class="form-group">
<label class="col-md-4 control-label" for="singlebutton"></label>
<div class="col-md-4 center-block">
<button id="singlebutton" name="singlebutton" class="btn btn-primary center-block">
Next Step!
</button>
</div>
</div>
All the class center-block
does is to tell the element to have a margin of 0 auto, the auto being the left/right margins. However, unless the class text-center or css text-align:center; is set on the parent, the element does not know the point to work out this auto calculation from so will not center itself as anticipated.
See an example of the code above here: https://jsfiddle.net/Seany84/2j9pxt1z/
This worked for me:
git ls-files -m | xargs -L 1 chmod 644
1) Database: Change Database default collation as utf8mb4
.
2) Table: Change table collation as CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
.
Query:
ALTER TABLE Tablename CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_bin
3) Code:
INSERT INTO tablename (column1, column2, column3, column4, column5, column6, column7)
VALUES ('273', '3', 'Hdhdhdhhzhzhzzhjzj ??? ?', 49, 1, '2016-09-13 08:02:29', '2016-09-13 08:02:29')
4) Set utf8mb4
in database connection:
$database_connection = new mysqli($server, $user, $password, $database_name);
$database_connection->set_charset('utf8mb4');
var userName = document.querySelector('#numberField');
userName.addEventListener('input', restrictNumber);
function restrictNumber (e) {
var newValue = this.value.replace(new RegExp(/[^\d]/,'ig'), "");
this.value = newValue;
}
_x000D_
<input type="text" id="numberField">
_x000D_
If you are interested in determining this in a script, you can try the following:
sc \\server_name query | grep MSSQL
Note: grep is part of gnuwin32 tools
Easy peasy:
var date = DateTime.Parse("14/11/2011"); // may need some Culture help here
Console.Write(date.ToString("yyyy-MM-dd"));
Take a look at DateTime.ToString() method, Custom Date and Time Format Strings and Standard Date and Time Format Strings
string customFormattedDateTimeString = DateTime.Now.ToString("yyyy-MM-dd");
Try this
$("div#date").text().trim().replace(/\W/g,'/');
Look a regular expression http://regexone.com/lesson/misc_meta_characters
enjoy us ;-)
In my windows machine, I solved this by adding the below code snippet in rules
object of .eslintrc.js
file present in my current project's directory.
"prettier/prettier": [
"error",
{
"endOfLine": "auto"
},
],
This worked on my Mac as well
In Router at end add html5Mode(true);
app.config(function($routeProvider,$locationProvider) {
$routeProvider.when('/home', {
templateUrl:'/html/home.html'
});
$locationProvider.html5Mode(true);
})
In html head add base tag
<html>
<head>
<meta charset="utf-8">
<base href="/">
</head>
thanks To @plus- for detailing the above answer
Just listen to what the warning is telling you:
Reshape your data either X.reshape(-1, 1) if your data has a single feature/column and X.reshape(1, -1) if it contains a single sample.
For your example type(if you have more than one feature/column):
temp = temp.reshape(1,-1)
For one feature/column:
temp = temp.reshape(-1,1)
Add your MAVEN_HOME
environment variable, edit your Path to include %MAVEN_HOME%/bin
then try creating the project manually with Maven:
mvn archetype:generate -DgroupId=com.program -DartifactId=Program -DarchetypeArtifactId=maven-archetype-webapp -DinteractiveMode=false
Then import the existing Maven project to Eclipse.
To apply J. B. Rainsberger and sschaef's comments to specifically answer the question... To use a cherry-pick range on this example:
git checkout a
git cherry-pick b..f
or
git checkout a
git cherry-pick c^..f
In a Ruby on Rails application (especially with something like the Prawn gem and the Prawnto Rails plugin), you can accomplish this a little more simply than a full on script (like the previous PHP example).
In your controller:
def index
respond_to do |format|
format.html # Your HTML view
format.pdf { render :layout => false }
end
end
The render :layout => false part tells the browser to open up the "Would you like to download this file?" prompt instead of attempting to render the PDF. Then you would be able to link to the file normally: http://mysite.com/myawesomepdf.pdf
If you use Wordpress you can just use the wordpress build in function with the video id provided wp_get_attachment_metadata($videoID):
wp_get_attachment_metadata($videoID);
helped me a lot. thats why i'm posting it, although its just for wordpress users.
I finally could figure the issue out.
To get the Key Alias: I copied the keytool.exe and my keystore file into C:\Program Files\Java\jdk1.7.0_71\bin folder. Then from command prompt I wrote: keytool -list -v -keystore <name>.keystore
It will also ask for keystore password then. Then it will show you the key alias and Certificate fingerprints and other info.
Then I again tried to Generate Signed Apk for the project, I provided keystore, keystore password, key alias and provided the same password. Then it asks for master password, I tried with the same and it failed. With the reset option I reset the master password here.
I had the same problem. To fix it in Jboss 7 AS, I copy the oracle driver jar file to Jboss module folder. Example: ../jboss-as-7.1.1.Final/modules/org/hibernate/main
.
You also need to change "module.xml"
<module xmlns="urn:jboss:module:1.1" name="org.hibernate">
<resources>
<resource-root path="hibernate-core-4.0.1.Final.jar"/>
<resource-root path="hibernate-commons-annotations-4.0.1.Final.jar"/>
<resource-root path="hibernate-entitymanager-4.0.1.Final.jar"/>
<resource-root path="hibernate-infinispan-4.0.1.Final.jar"/>
<resource-root path="ojdbc6.jar"/>
</resources>
<dependencies>
<module name="asm.asm"/>
<module name="javax.api"/>
<module name="javax.persistence.api"/>
<module name="javax.transaction.api"/>
<module name="javax.validation.api"/>
<module name="org.antlr"/>
<module name="org.apache.commons.collections"/>
<module name="org.dom4j"/>
<module name="org.infinispan" optional="true"/>
<module name="org.javassist"/>
<module name="org.jboss.as.jpa.hibernate" slot="4" optional="true"/>
<module name="org.jboss.logging"/>
<module name="org.hibernate.envers" services="import" optional="true"/>
</dependencies>
Alternatively you could use SciPy
from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)
and for the record to sample integers it's
stats.randint(10, 20).rvs(50)
As far as I can tell, this is currently not possible - a cast is always needed.
To make it possible, the .d.ts of react would need to be modified so that the signature of the onChange of a SELECT element used a new SelectFormEvent. The new event type would expose target, which exposes value. Then the code could be typesafe.
Otherwise there will always be the need for a cast to any.
I could encapsulate all that in a MYSELECT tag.
Nope.
Can use:
IS_COOL NUMBER(1,0)
1 - true
0 - false
--- enjoy Oracle
Or use char Y/N as described here
Matt Turner's answer is definitely the right answer. However, in the spirit of Ken Williams' answer, you could also do:
capture.output(cat(sdata, sep=""))
Twitter now has a sass-ready version of bootstrap with gem included, so it is easier than ever to add it to Rails.
Simply add to your gemfile the following:
gem 'sass-rails', '>= 3.2' # sass-rails needs to be higher than 3.2
gem 'bootstrap-sass', '~> 3.1.1'
bundle install
and restart your server to make the files available through the pipeline.
There is also support for compass and sass-only: https://github.com/twbs/bootstrap-sass
Click File > Preferences > Keyboard Shortcuts:
Search for copyLinesDownAction
or copyLinesUpAction
in your keyboard shortcuts
Usually it is SHIFT+ALT + ?
Update for Ubuntu:
It seems that Ubuntu is hiding that shortcut from being seen by VSCode (i.e. it uses it probably by its own). There is an issue about that on GitHub.
In order to work in Ubuntu you will have to define your own shortcut, e.g. to copy the line using ctrl+shift+alt+j and CTRL +SHIFT + ALT + k you could use a keybindings.json
like this:
[
{ "key": "ctrl+shift+alt+j", "command": "editor.action.copyLinesDownAction",
"when": "editorTextFocus && !editorReadonly" },
{ "key": "ctrl+shift+alt+k", "command": "editor.action.copyLinesUpAction",
"when": "editorTextFocus && !editorReadonly" }
]
I'm surprised that nobody has mentioned the use of this
in the event handler. It works automatically in modern browsers and can be made to work in other browsers. If you use addEventListener
or attachEvent
to install your event handler, then you can make the value of this
automatically be assigned to the object the created the event.
Further, the user of programmatically installed event handlers allows you to separate javascript code from HTML which is often considered a good thing.
Here's how you would do that in your code in plain javascript:
Remove the onmouseover="zoom()"
from your HTML and install the event handler in your javascript like this:
// simplified utility function to register an event handler cross-browser
function setEventHandler(obj, name, fn) {
if (typeof obj == "string") {
obj = document.getElementById(obj);
}
if (obj.addEventListener) {
return(obj.addEventListener(name, fn));
} else if (obj.attachEvent) {
return(obj.attachEvent("on" + name, function() {return(fn.call(obj));}));
}
}
function zoom() {
// you can use "this" here to refer to the object that caused the event
// this here will refer to the calling object (which in this case is the <map>)
console.log(this.id);
document.getElementById("preview").src="http://photos.smugmug.com/photos/344290962_h6JjS-Ti.jpg";
}
// register your event handler
setEventHandler("nose", "mouseover", zoom);
You could wrap your VLOOKUP() in an IFERROR()
Edit: before Excel 2007, use =IF(ISERROR()...)
You have to style the image like this
#container img{width:100%;}
and the container with hidden overflow:
#container{width:250px; height:250px; overflow:hidden; border:1px solid #000;}
<!DOCTYPE html>
<html lang="en">
<head>
<style>
#container { width: 100%; border: 1px solid black; display: block; text-align: justify; }
object, span { display: inline-block; }
span { width: 100%; }
</style>
</head>
<div id="container">
<object>
<div>
alpha
</div>
</object>
<object>
<div>
beta
</div>
</object>
<object>
<div>
charlie
</div>
</object>
<object>
<div>
delta
</div>
</object>
<object>
<div>
epsilon
</div>
</object>
<object>
<div>
foxtrot
</div>
</object>
<span></span>
</div>
</html>
Maybe it sounds stupid but it worked for me when I had the same problem: delete the created avd and create one again through AVD Manager with a sd card of, for example, 512MB.
Check that both have the correct permissions and if not, try to change them with chmod.
And if everything still fails, repeat the process but creating both avd and sd card manually via terminal:
android create avd -n my_avd -t 7
mksdcard -l e 512M mysdcard.img
emulator -avd my_avd -sdcard mysdcard.img
Hope that helps!
You can't access the http headers, but some of the information provided in them is available in the DOM. For example, if you want to see the http referer (sic), use document.referrer. There may be others like this for other http headers. Try googling the specific thing you want, like "http referer javascript".
I know this should be obvious, but I kept searching for stuff like "http headers javascript" when all I really wanted was the referer, and didn't get any useful results. I don't know how I didn't realize I could make a more specific query.
Sure, a very similar question was asked before. Set the controller for ajax requests:
public ActionResult Show()
{
if (Request.IsAjaxRequest())
{
return PartialView("Your_partial_view", new Model());
}
else
{
return View();
}
}
Set the action link as wanted:
@Ajax.ActionLink("Show",
"Show",
null,
new AjaxOptions { HttpMethod = "GET",
InsertionMode = InsertionMode.Replace,
UpdateTargetId = "dialog_window_id",
OnComplete = "your_js_function();" })
Note that I'm using Razor view engine, and that your AjaxOptions may vary depending on what you want. Finally display it on a modal window. The jQuery UI dialog is suggested.
java.time.Period
Use the java.time.Period
class to count days.
Since Java 8 calculating the difference is more intuitive using LocalDate
, LocalDateTime
to represent the two dates
LocalDate now = LocalDate.now();
LocalDate inputDate = LocalDate.of(2018, 11, 28);
Period period = Period.between( inputDate, now);
int diff = period.getDays();
System.out.println("diff = " + diff);
cd /path/to/directories &&
find . -type d -exec mkdir -p -- /path/to/backup/{} \;
Here is a little Greasemonkey script that will add a CDN button to html pages on github
Target page will be of the form: https://cdn.rawgit.com/user/repo/master/filename.js
// ==UserScript==
// @name cdn.rawgit.com
// @namespace github.com
// @include https://github.com/*/blob/*.html
// @version 1
// @grant none
// ==/UserScript==
var buttonGroup = $(".meta .actions .button-group");
var raw = buttonGroup.find("#raw-url");
var cdn = raw.clone();
cdn.attr("id", "cdn-url");
cdn.attr("href", "https://cdn.rawgit.com" + cdn.attr("href").replace("/raw/","/") );
cdn.text("CDN");
cdn.insertBefore(raw);
The reason is another one, at least for MySQL. This is from the MySQL manual
InnoDB computes index cardinality values for a table the first time that table is accessed after startup, instead of storing such values in the table. This step can take significant time on systems that partition the data into many tables. Since this overhead only applies to the initial table open operation, to “warm up” a table for later use, access it immediately after startup by issuing a statement such as SELECT 1 FROM tbl_name LIMIT 1
For eslint:
"editor.codeActionsOnSave": { "source.fixAll.eslint": true }
The methods here that show the actual implementation are all faulty.
I don't have Java code, but just for the record, you could easily convert this C#-code:
Courtesy of the mono-project @ https://github.com/mono/mono/blob/master/mcs/class/System.Web/System.Web/HttpUtility.cs
public static string JavaScriptStringEncode(string value, bool addDoubleQuotes)
{
if (string.IsNullOrEmpty(value))
return addDoubleQuotes ? "\"\"" : string.Empty;
int len = value.Length;
bool needEncode = false;
char c;
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
{
needEncode = true;
break;
}
}
if (!needEncode)
return addDoubleQuotes ? "\"" + value + "\"" : value;
var sb = new System.Text.StringBuilder();
if (addDoubleQuotes)
sb.Append('"');
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
sb.AppendFormat("\\u{0:x4}", (int)c);
else switch ((int)c)
{
case 8:
sb.Append("\\b");
break;
case 9:
sb.Append("\\t");
break;
case 10:
sb.Append("\\n");
break;
case 12:
sb.Append("\\f");
break;
case 13:
sb.Append("\\r");
break;
case 34:
sb.Append("\\\"");
break;
case 92:
sb.Append("\\\\");
break;
default:
sb.Append(c);
break;
}
}
if (addDoubleQuotes)
sb.Append('"');
return sb.ToString();
}
This can be compacted into
// https://github.com/mono/mono/blob/master/mcs/class/System.Json/System.Json/JsonValue.cs
public class SimpleJSON
{
private static bool NeedEscape(string src, int i)
{
char c = src[i];
return c < 32 || c == '"' || c == '\\'
// Broken lead surrogate
|| (c >= '\uD800' && c <= '\uDBFF' &&
(i == src.Length - 1 || src[i + 1] < '\uDC00' || src[i + 1] > '\uDFFF'))
// Broken tail surrogate
|| (c >= '\uDC00' && c <= '\uDFFF' &&
(i == 0 || src[i - 1] < '\uD800' || src[i - 1] > '\uDBFF'))
// To produce valid JavaScript
|| c == '\u2028' || c == '\u2029'
// Escape "</" for <script> tags
|| (c == '/' && i > 0 && src[i - 1] == '<');
}
public static string EscapeString(string src)
{
System.Text.StringBuilder sb = new System.Text.StringBuilder();
int start = 0;
for (int i = 0; i < src.Length; i++)
if (NeedEscape(src, i))
{
sb.Append(src, start, i - start);
switch (src[i])
{
case '\b': sb.Append("\\b"); break;
case '\f': sb.Append("\\f"); break;
case '\n': sb.Append("\\n"); break;
case '\r': sb.Append("\\r"); break;
case '\t': sb.Append("\\t"); break;
case '\"': sb.Append("\\\""); break;
case '\\': sb.Append("\\\\"); break;
case '/': sb.Append("\\/"); break;
default:
sb.Append("\\u");
sb.Append(((int)src[i]).ToString("x04"));
break;
}
start = i + 1;
}
sb.Append(src, start, src.Length - start);
return sb.ToString();
}
}
You need to merge the remote branch into your current branch by running git pull
.
If your local branch is already up-to-date, you may also need to run git pull --rebase
.
A quick google search also turned up this same question asked by another SO user: Cannot push to GitHub - keeps saying need merge. More details there.
I had a similar issues where I was receiving this error on a project.
“Could not load type [Namespace].Global
Error in Line 1 etc etc
After spending some time I suspect a function with possible errors in a Class ..later commenting that specific function my problem get resolved.
I dont know why Visual Studio did't give me that specific error at debugging time. But this error might occure due to some errors in class file..
In Bootstrap 3 they do not have separate classes for different styles of labels.
http://getbootstrap.com/components/
However, you can customize bootstrap classes that way. In your css file
.lb-sm {
font-size: 12px;
}
.lb-md {
font-size: 16px;
}
.lb-lg {
font-size: 20px;
}
Alternatively, you can use header tags to change the sizes. For example, here is a medium sized label and a small-sized label
<link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<h3>Example heading <span class="label label-default">New</span></h3>_x000D_
<h6>Example heading <span class="label label-default">New</span></h6>
_x000D_
They might add size classes for labels in future Bootstrap versions.
You have to replace string line
QString line = in.readLine();
into while:
QFile file("/home/hamad/lesson11.txt");
if(!file.open(QIODevice::ReadOnly)) {
QMessageBox::information(0, "error", file.errorString());
}
QTextStream in(&file);
while(!in.atEnd()) {
QString line = in.readLine();
QStringList fields = line.split(",");
model->appendRow(fields);
}
file.close();
It seems pretty hard to have a regex that does exactly what you want (i.e. accept only the cases that you need and reject all others and return some groups for the three components). I've give it a try and come up with this:
^(\*|(\d+(\.(\d+(\.(\d+|\*))?|\*))?))$
IMO (I've not tested extensively) this should work fine as a validator for the input, but the problem is that this regex doesn't offer a way of retrieving the components. For that you still have to do a split on period.
This solution is not all-in-one, but most times in programming it doesn't need to. Of course this depends on other restrictions that you might have in your code.
If you want to use a the openFileInput
method from a Context for this, you can use the following code.
This will create a BufferArrayOutputStream
and append each byte as it's read from the file to it.
/**
* <p>
* Creates a InputStream for a file using the specified Context
* and returns the Bytes read from the file.
* </p>
*
* @param context The context to use.
* @param file The file to read from.
* @return The array of bytes read from the file, or null if no file was found.
*/
public static byte[] read(Context context, String file) throws IOException {
byte[] ret = null;
if (context != null) {
try {
InputStream inputStream = context.openFileInput(file);
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
int nextByte = inputStream.read();
while (nextByte != -1) {
outputStream.write(nextByte);
nextByte = inputStream.read();
}
ret = outputStream.toByteArray();
} catch (FileNotFoundException ignored) { }
}
return ret;
}
Very simple way to sort List with int values in Descending order:
li.Sort((a,b)=> b-a);
Hope that this helps!
I thinks this is the best example for using randomUUID :
The only issue with promises is that IE doesn't support them. Edge does, but there's plenty of IE 10 and 11 out there: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise (compatibility at the bottom)
So, JavaScript is single-threaded. If you're not making an asynchronous call, it will behave predictably. The main JavaScript thread will execute one function completely before executing the next one, in the order they appear in the code. Guaranteeing order for synchronous functions is trivial - each function will execute completely in the order it was called.
Think of the synchronous function as an atomic unit of work. The main JavaScript thread will execute it fully, in the order the statements appear in the code.
But, throw in the asynchronous call, as in the following situation:
showLoadingDiv(); // function 1
makeAjaxCall(); // function 2 - contains async ajax call
hideLoadingDiv(); // function 3
This doesn't do what you want. It instantaneously executes function 1, function 2, and function 3. Loading div flashes and it's gone, while the ajax call is not nearly complete, even though makeAjaxCall()
has returned. THE COMPLICATION is that makeAjaxCall()
has broken its work up into chunks which are advanced little by little by each spin of the main JavaScript thread - it's behaving asychronously. But that same main thread, during one spin/run, executed the synchronous portions quickly and predictably.
So, the way I handled it: Like I said the function is the atomic unit of work. I combined the code of function 1 and 2 - I put the code of function 1 in function 2, before the asynch call. I got rid of function 1. Everything up to and including the asynchronous call executes predictably, in order.
THEN, when the asynchronous call completes, after several spins of the main JavaScript thread, have it call function 3. This guarantees the order. For example, with ajax, the onreadystatechange event handler is called multiple times. When it reports it's completed, then call the final function you want.
I agree it's messier. I like having code be symmetric, I like having functions do one thing (or close to it), and I don't like having the ajax call in any way be responsible for the display (creating a dependency on the caller). BUT, with an asynchronous call embedded in a synchronous function, compromises have to be made in order to guarantee order of execution. And I have to code for IE 10 so no promises.
Summary: For synchronous calls, guaranteeing order is trivial. Each function executes fully in the order it was called. For a function with an asynchronous call, the only way to guarantee order is to monitor when the async call completes, and call the third function when that state is detected.
For a discussion of JavaScript threads, see: https://medium.com/@francesco_rizzi/javascript-main-thread-dissected-43c85fce7e23 and https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop
Also, another similar, highly rated question on this subject: How should I call 3 functions in order to execute them one after the other?
You copied using Cells.
If so, no need to PasteSpecial since you are copying data at exactly the same format.
Here's your code with some fixes.
Dim x As Workbook, y As Workbook
Dim ws1 As Worksheet, ws2 As Worksheet
Set x = Workbooks.Open("path to copying book")
Set y = Workbooks.Open("path to pasting book")
Set ws1 = x.Sheets("Sheet you want to copy from")
Set ws2 = y.Sheets("Sheet you want to copy to")
ws1.Cells.Copy ws2.cells
y.Close True
x.Close False
If however you really want to paste special, use a dynamic Range("Address") to copy from.
Like this:
ws1.Range("Address").Copy: ws2.Range("A1").PasteSpecial xlPasteValues
y.Close True
x.Close False
Take note of the :
colon after the .Copy
which is a Statement Separating
character.
Using Object.PasteSpecial
requires to be executed in a new line.
Hope this gets you going.
Step1. $ cd [your working path of code]
Step2. $ svn commit [your server path ] -m 'Add commit message'
For help use $ svn help commit
I would "inject" the starttime variable instead, otherwise you have a circular dependency between the packages.
main.go
var StartTime = time.Now()
func main() {
otherPackage.StartTime = StartTime
}
otherpackage.go
var StartTime time.Time
Correct solution with "File" class to get the directory - the "path" of the file:
String path = new File("C:\\Temp\\your directory\\yourfile.txt").getParent();
which will return:
path = "C:\\Temp\\your directory"
Following Justin's example, the command below works in Postgres:
alter table foo alter column col2 set default 'bar';
I always try to stick with POSIX sh
instead of using Bash extensions, since one of the major points of scripting is portability (besides connecting programs, not replacing them).
In sh
, there is an easy way to check for an "is-prefix" condition.
case $HOST in node*)
# Your code here
esac
Given how old, arcane and crufty sh is (and Bash is not the cure: It's more complicated, less consistent and less portable), I'd like to point out a very nice functional aspect: While some syntax elements like case
are built-in, the resulting constructs are no different than any other job. They can be composed in the same way:
if case $HOST in node*) true;; *) false;; esac; then
# Your code here
fi
Or even shorter
if case $HOST in node*) ;; *) false;; esac; then
# Your code here
fi
Or even shorter (just to present !
as a language element -- but this is bad style now)
if ! case $HOST in node*) false;; esac; then
# Your code here
fi
If you like being explicit, build your own language element:
beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
Isn't this actually quite nice?
if beginswith node "$HOST"; then
# Your code here
fi
And since sh
is basically only jobs and string-lists (and internally processes, out of which jobs are composed), we can now even do some light functional programming:
beginswith() { case $2 in "$1"*) true;; *) false;; esac; }
checkresult() { if [ $? = 0 ]; then echo TRUE; else echo FALSE; fi; }
all() {
test=$1; shift
for i in "$@"; do
$test "$i" || return
done
}
all "beginswith x" x xy xyz ; checkresult # Prints TRUE
all "beginswith x" x xy abc ; checkresult # Prints FALSE
This is elegant. Not that I'd advocate using sh
for anything serious -- it breaks all too quickly on real world requirements (no lambdas, so we must use strings. But nesting function calls with strings is not possible, pipes are not possible, etc.)
add these dependecies to your .pom file:
<dependency>
<groupId>org.hsqldb</groupId>
<artifactId>hsqldb</artifactId>
<version>2.5.0</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>com.healthmarketscience.jackcess</groupId>
<artifactId>jackcess-encrypt</artifactId>
<version>3.0.0</version>
</dependency>
<dependency>
<groupId>net.sf.ucanaccess</groupId>
<artifactId>ucanaccess</artifactId>
<version>5.0.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>commons-logging</groupId>
<artifactId>commons-logging</artifactId>
<version>1.2</version>
</dependency>
and add to your code to call a driver:
Connection conn = DriverManager.getConnection("jdbc:ucanaccess://{file_location}/{accessdb_file_name.mdb};memory=false");
You can check if the row exists, and then INSERT or UPDATE, but this guarantees you will be performing two SQL operations instead of one:
A better solution is to always UPDATE first, and if no rows were updated, then do an INSERT, like so:
update table1
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
if @@ROWCOUNT = 0
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')
This will either take one SQL operations, or two SQL operations, depending on whether the row already exists.
But if performance is really an issue, then you need to figure out if the operations are more likely to be INSERT's or UPDATE's. If UPDATE's are more common, do the above. If INSERT's are more common, you can do that in reverse, but you have to add error handling.
BEGIN TRY
insert into table1(id, name, itemname, itemcatName, itemQty)
values('val1', 'val2', 'val3', 'val4', 'val5')
END TRY
BEGIN CATCH
update table1
set name = 'val2', itemname = 'val3', itemcatName = 'val4', itemQty = 'val5'
where id = 'val1'
END CATCH
To be really certain if you need to do an UPDATE or INSERT, you have to do two operations within a single TRANSACTION. Theoretically, right after the first UPDATE or INSERT (or even the EXISTS check), but before the next INSERT/UPDATE statement, the database could have changed, causing the second statement to fail anyway. This is exceedingly rare, and the overhead for transactions may not be worth it.
Alternately, you can use a single SQL operation called MERGE to perform either an INSERT or an UPDATE, but that's also probably overkill for this one-row operation.
Consider reading about SQL transaction statements, race conditions, SQL MERGE statement.
index.html (index.html should be in templates folder)
<!doctype html>
<html>
<head>
<title>The jQuery Example</title>
<h2>jQuery-AJAX in FLASK. Execute function on button click</h2>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"> </script>
<script type=text/javascript> $(function() { $("#mybutton").click(function (event) { $.getJSON('/SomeFunction', { },
function(data) { }); return false; }); }); </script>
</head>
<body>
<input type = "button" id = "mybutton" value = "Click Here" />
</body>
</html>
test.py
from flask import Flask, jsonify, render_template, request
app = Flask(__name__)
@app.route('/')
def index():
return render_template('index.html')
@app.route('/SomeFunction')
def SomeFunction():
print('In SomeFunction')
return "Nothing"
if __name__ == '__main__':
app.run()
As has been mentioned, as of PHP 5.6+ you can (should!) use the ...
token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:
<?php
function variadic($arg1, $arg2)
{
// Do stuff
echo $arg1.' '.$arg2;
}
$array = ['Hello', 'World'];
// 'Splat' the $array in the function call
variadic(...$array);
// 'Hello World'
Note: array items are mapped to arguments by their position in the array, not their keys.
As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array
.
Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.
(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)
This is great for making sure an array contains items of a specific type:
<?php
// Define the function...
function variadic($var, SomeClass ...$items)
{
// $items will be an array of objects of type `SomeClass`
}
// Then you can call...
variadic('Hello', new SomeClass, new SomeClass);
// or even splat both ways
$items = [
new SomeClass,
new SomeClass,
];
variadic('Hello', ...$items);
<script type="text/javascript">
function file_upload() {
var imgpath = document.getElementById("<%=FileUpload1.ClientID %>").value;
if (imgpath == "") {
alert("Upload your Photo...");
document.file.word.focus();
return false;
}
else {
// code to get File Extension..
var arr1 = new Array;
arr1 = imgpath.split("\\");
var len = arr1.length;
var img1 = arr1[len - 1];
var filext = img1.substring(img1.lastIndexOf(".") + 1);
// Checking Extension
if (filext == "bmp" || filext == "gif" || filext == "png" || filext == "jpg" || filext == "jpeg" ) {
alert("Successfully Uploaded...")
return false;
}
else {
alert("Upload Photo with Extension ' bmp , gif, png , jpg , jpeg '");
document.form.word.focus();
return false;
}
}
}
function Doc_upload() {
var imgpath = document.getElementById("<%=FileUpload2.ClientID %>").value;
if (imgpath == "") {
alert("Upload Agreement...");
document.file.word.focus();
return false;
}
else {
// code to get File Extension..
var arr1 = new Array;
arr1 = imgpath.split("\\");
var len = arr1.length;
var img1 = arr1[len - 1];
var filext = img1.substring(img1.lastIndexOf(".") + 1);
// Checking Extension
if (filext == "txt" || filext == "pdf" || filext == "doc") {
alert("Successfully Uploaded...")
return false;
}
else {
alert("Upload File with Extension ' txt , pdf , doc '");
document.form.word.focus();
return false;
}
}
}
</script>
I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.
Add:
"resolveJsonModule": true,
To tsconfig.json
Import like:
import * as nameOfJson from 'path/to/file.json';
Stop ng test
, start again.
Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports
unfortunately none of the above worked. I finally could do it using the following stuffs: This solution works 100% (adapt it to your need)
.g-recaptcha-wrapper {_x000D_
position: relative;_x000D_
border: 1px solid #ededed;_x000D_
background: #f9f9f9;_x000D_
border-radius: 4px;_x000D_
padding: 0;_x000D_
#topHider {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 2px !important;_x000D_
width: 100%;_x000D_
background-color: #f9f9f9;_x000D_
}_x000D_
#rightHider {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 295px;_x000D_
height: 100% !important;_x000D_
width: 15px;_x000D_
background-color: #f9f9f9;_x000D_
}_x000D_
#leftHider {_x000D_
position: absolute;_x000D_
top: 0;_x000D_
left: 0;_x000D_
height: 100% !important;_x000D_
width: 2px;_x000D_
background-color: #f9f9f9;_x000D_
}_x000D_
#bottomHider {_x000D_
position: absolute;_x000D_
bottom: 1px;_x000D_
left: 0;_x000D_
height: 2px !important;_x000D_
width: 100%;_x000D_
background-color: #f9f9f9;_x000D_
}_x000D_
}
_x000D_
<div class="g-recaptcha-wrapper">_x000D_
<re-captcha #captchaRef="reCaptcha" (resolved)="onCaptchaResolved($event)" siteKey="{{captchaSiteKey}}"></re-captcha>_x000D_
<div id="topHider"></div>_x000D_
<div id="rightHider"></div>_x000D_
<div id="bottomHider"></div>_x000D_
<div id="leftHider"></div>_x000D_
</div>
_x000D_
Usually form is submitted on Enter when you have focus on input elements.
We can disable Enter key (code 13
) on input elements within a form:
$('form input').on('keypress', function(e) {
return e.which !== 13;
});
You can use Pillow.
pip install Pillow
image = base64.b64decode(str(base64String))
fileName = 'test.jpeg'
imagePath = FILE_UPLOAD_DIR + fileName
img = Image.open(io.BytesIO(image))
img.save(imagePath, 'jpeg')
return fileName
reference for complete source code: https://abhisheksharma.online/convert-base64-blob-to-image-file-in-python/
Display the Query Designer with CTRL + SHIFT + Q
I also feel xcode should have this function. So I made an extension to do it: Swimat
Simple install by brew cask install swimat
You can give it a try, see https://github.com/Jintin/Swimat for more information.
Use CharField
for phone field in the model and the localflavor
app for form validation:
This gets a view controller from the storyboard and presents it.
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let secondViewController = storyboard.instantiateViewController(withIdentifier: "secondViewControllerId") as! SecondViewController
self.present(secondViewController, animated: true, completion: nil)
Change the storyboard name, view controller name, and view controller id as appropriate.
As long as your program's in a sane state, you can also call (void)puts(your_string)
to print it to stdout. Same principle applies to all functions available to the debugger, actually.
You were on the right track with response.getOutputStream()
, but you're not using its output anywhere in your code. Essentially what you need to do is to stream the PDF file's bytes directly to the output stream and flush the response. In Spring you can do it like this:
@RequestMapping(value="/getpdf", method=RequestMethod.POST)
public ResponseEntity<byte[]> getPDF(@RequestBody String json) {
// convert JSON to Employee
Employee emp = convertSomehow(json);
// generate the file
PdfUtil.showHelp(emp);
// retrieve contents of "C:/tmp/report.pdf" that were written in showHelp
byte[] contents = (...);
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_PDF);
// Here you have to set the actual filename of your pdf
String filename = "output.pdf";
headers.setContentDispositionFormData(filename, filename);
headers.setCacheControl("must-revalidate, post-check=0, pre-check=0");
ResponseEntity<byte[]> response = new ResponseEntity<>(contents, headers, HttpStatus.OK);
return response;
}
Notes:
showHelp
is not a good ideabyte[]
: example hereshowHelp()
to avoid overwriting the file if two users send a request at the same timeWhile gcc 3.2.3 was more forgiving of the issue, gcc 4.1.2 is highlighting a potentially serious issue for the linking of your program later. Rather then trying to suppress the error you should make the forward declaration match the function declaration.
If you intended for the function to be globally available (as per the forward declaration) then don't subsequently declare it as static. Likewise if it's indented to be locally scoped then make the forward declaration static to match.
I'm certain there are better ways of doing this, but I have in the past used a method something like the following to serialize an object into a string that I can log:
private string ObjectToXml(object output)
{
string objectAsXmlString;
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(output.GetType());
using (System.IO.StringWriter sw = new System.IO.StringWriter())
{
try
{
xs.Serialize(sw, output);
objectAsXmlString = sw.ToString();
}
catch (Exception ex)
{
objectAsXmlString = ex.ToString();
}
}
return objectAsXmlString;
}
You'll see that the method might also return the exception rather than the serialized object, so you'll want to ensure that the objects you want to log are serializable.
Local Computer FQDN via dotNet class
[System.Net.Dns]::GetHostEntry([string]$env:computername).HostName
or
[System.Net.Dns]::GetHostEntry([string]"localhost").HostName
Reference:
note: GetHostByName method is obsolete
Local computer FQDN via WMI query
$myFQDN=(Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain
Write-Host $myFQDN
Reference:
I had a similar problem. None of the answers helped. In my case, I had two removed remote repositories showing up permanently.
My last idea was to remove all references to it by hand.
Let's say the repository is called “Repo”. I did:
find .git -name Repo
So, I deleted the corresponding files and directories from the .git folder (this folder could be found in your Rails app or on your computer https://stackoverflow.com/a/19538763/6638513).
Then I did:
grep Repo -r .git
This found some text files in which I removed the corresponding lines. Now, everything seems to be fine.
Usually, you should leave this job to git.
Simply last
would work here:
for my $entry (@array){
if ($string eq "text"){
last;
}
}
If you have nested loops, then last
will exit from the innermost loop. Use labels in this case:
LBL_SCORE: {
for my $entry1 (@array1) {
for my $entry2 (@array2) {
if ($entry1 eq $entry2) { # Or any condition
last LBL_SCORE;
}
}
}
}
Given a last
statement will make the compiler to come out from both the loops. The same can be done in any number of loops, and labels can be fixed anywhere.
I don't think there is a "apache-common-like" tool to compare maps since the equality of 2 maps is very ambiguous and depends on the developer needs and the map implementation...
For exemple if you compare two hashmaps in java: - You may want to just compare key/values are the same - You may also want to compare if the keys are ordered the same way - You may also want to compare if the remaining capacity is the same ... You can compare a lot of things!
What such a tool would do when comparing 2 different map implementations such that: - One map allow null keys - The other throw runtime exception on map2.get(null)
You'd better to implement your own solution according to what you really need to do, and i think you already got some answers above :)
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
As mentioned in the other answers, previous versions of openssl used a weak key derivation function to derive an AES encryption key from the password. However, openssl v1.1.1 supports a stronger key derivation function, where the key is derived from the password using pbkdf2
with a randomly generated salt, and multiple iterations of sha256 hashing (10,000 by default).
To encrypt a file:
openssl aes-256-cbc -e -salt -pbkdf2 -iter 10000 -in plaintextfilename -out encryptedfilename
To decrypt a file:
openssl aes-256-cbc -d -salt -pbkdf2 -iter 10000 -in encryptedfilename -out plaintextfilename
The C++ specification itself (old version but good enough for this) leaves this open.
There are four signed integer types: '
signed char
', 'short int
', 'int
', and 'long int
'. In this list, each type provides at least as much storage as those preceding it in the list. Plain ints have the natural size suggested by the architecture of the execution environment* ;[Footnote: that is, large enough to contain any value in the range of INT_MIN and INT_MAX, as defined in the header
<climits>
. --- end foonote]
Try deleting the virtualenv you created. Then create a new virtualenv with:
virtualenv flask
Then:
cd flask
Now let's activate the virtualenv
source bin/activate
Now you should see (flask)
on the left of the command line.
Edit: In windows there is no "source" that's a linux thing, instead execute the activate.bat file, here I do it using Powershell: PS C:\DEV\aProject> & .\Flask\Scripts\activate
)
Let's install flask:
pip install flask
Then create a file named hello.py
(NOTE: see UPDATE Flask 1.0.2
below):
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
app.run()
and run it with:
python hello.py
UPDATE Flask 1.0.2
With the new flask release there is no need to run the app from your script. hello.py
should look like this now:
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
and run it with:
FLASK_APP=hello.py flask run
Make sure to be inside the folder where hello.py
is when running the latest command.
All the steps before the creation of the hello.py apply for this case as well
list all containers with info and ID
docker ps
docker stop CONTAINER ID
It is about string concatenation performance. It's potentially significant if your have dense logging statements.
(Prior to SLF4J 1.7) But only two parameters are possible
Because the vast majority of logging statements have 2 or fewer parameters, so SLF4J API up to version 1.6 covers (only) the majority of use cases. The API designers have provided overloaded methods with varargs parameters since API version 1.7.
For those cases where you need more than 2 and you're stuck with pre-1.7 SLF4J, then just use either string concatenation or new Object[] { param1, param2, param3, ... }
. There should be few enough of them that the performance is not as important.
I wrote this pattern:
Pattern SPECIAL_REGEX_CHARS = Pattern.compile("[{}()\\[\\].+*?^$\\\\|]");
And use it in this method:
String escapeSpecialRegexChars(String str) {
return SPECIAL_REGEX_CHARS.matcher(str).replaceAll("\\\\$0");
}
Then you can use it like this, for example:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*" + escapeSpecialRegexChars(text) + ".*");
}
We needed to do that because, after escaping, we add some regex expressions. If not, you can simply use \Q
and \E
:
Pattern toSafePattern(String text)
{
return Pattern.compile(".*\\Q" + text + "\\E.*")
}
<link rel="SHORTCUT ICON" href="favicon.ico" type="image/x-icon" />
<link rel="ICON" href="favicon.ico" type="image/ico" />
Excellent tool for cross-browser favicon - http://www.convertico.com/
I think Michal's answer is the best, but we can take it a step further and dynamically load an Android CSS as per the original question:
var isAndroid = /(android)/i.test(navigator.userAgent);
if (isAndroid) {
var css = document.createElement("link");
css.setAttribute("rel", "stylesheet");
css.setAttribute("type", "text/css");
css.setAttribute("href", "/css/android.css");
document.body.appendChild(css);
}
Yor $.post
has no data. You need to pass the form data. You can use serialize()
to post the form data. Try this
$("#post-btn").click(function(){
$.post("process.php", $('#reg-form').serialize() ,function(data){
alert(data);
});
});
I was getting same kinda error but after copying the ojdbc14.jar into lib folder, no more exception.(copy ojdbc14.jar from somewhere and paste it into lib folder inside WebContent.)
I would be careful when using Guava's ComparisonChain
because it creates an instance of it per element been compared so you would be looking at a creation of N x Log N
comparison chains just to compare if you are sorting, or N
instances if you are iterating and checking for equality.
I would instead create a static Comparator
using the newest Java 8 API if possible or Guava's Ordering
API which allows you to do that, here is an example with Java 8:
import java.util.Comparator;
import static java.util.Comparator.naturalOrder;
import static java.util.Comparator.nullsLast;
private static final Comparator<Person> COMPARATOR = Comparator
.comparing(Person::getName, nullsLast(naturalOrder()))
.thenComparingInt(Person::getAge);
@Override
public int compareTo(@NotNull Person other) {
return COMPARATOR.compare(this, other);
}
Here is how to use the Guava's Ordering
API: https://github.com/google/guava/wiki/OrderingExplained
The answer is Yes, but you should consider the following 3 points.
No two main method parameter should be the same
Eg.
public static void main(int i)
public static void main(int i, int j)
public static void main(double j)
public static void main(String[] args)
Java’s actual main method is the one with (String[] args)
, So the Actual execution starts from public static void main(String[] args), so the main method with (String[] args)
is must in a class unless if it is not a child class.
In order for other main methods to execute you need to call them from inside the (String[] args)
main method.
Here is a detailed video about the same: https://www.youtube.com/watch?v=Qlhslsluhg4&feature=youtu.be
Virtualenvs are broken. Sometimes simple way is to delete venv folders and recreate virutalenvs.
You can define this style in values/styles.xml to perform a more former Splash :
<style name="Theme.UserDialog" parent="android:style/Theme.Dialog">
<item name="android:windowFrame">@null</item>
<item name="android:windowIsFloating">true</item>
<item name="android:windowIsTranslucent">true</item>
<item name="android:windowNoTitle">true</item>
<item name="android:background">@android:color/transparent</item>
<item name="android:windowBackground">@drawable/trans</item>
</style>
And use it AndroidManifest.xml:
<activity android:name=".SplashActivity"
android:configChanges="orientation"
android:screenOrientation="sensor"
android:theme="@style/Theme.UserDialog">
I had this problem too, somehow my code did not present the exact values but rounded the number in seconds to 0.0 (if milliseconds was under 1 second). What helped me out is adding the decimal to the division value.
double time_seconds = time_milliseconds / 1000.0; // add the decimal
System.out.println(time_milliseconds); // Now this should give you the right value.
I found the answer in the official website
$ vi ~/.profile
# add the following line
export PATH=/opt/local/bin:/opt/local/sbin:$PATH
And now restart the terminal or type source !$
(equivalent to source ~/.profile
)
Although my experience with DFD diagrams is limited I can tell you that a DFD shows you how the data moves (flows) between the various modules. Furthermore a DFD can be partitioned in levels, that is in the Initial Level you see the system (say, a System to Rent a Movie) as a whole (called the Context Level). That level could be broken down into another Level that contains activities (say, rent a movie, return a movie) and how the data flows into those activities (could be a name, number of days, whatever). Now you can make a sublevel for each activity detailing the many tasks or scenarios of those activities. And so on, so forth. Remember that the data is always passing between levels.
Now as for the flowchart just remember that a flowchart describes an algorithm!
dovers gives us his great answer and based on it you can try use it like
public static class CellDataFormat
{
public static string General { get { return "General"; } }
public static string Number { get { return "0"; } }
// Your custom format
public static string NumberDotTwoDigits { get { return "0.00"; } }
public static string Currency { get { return "$#,##0.00;[Red]$#,##0.00"; } }
public static string Accounting { get { return "_($* #,##0.00_);_($* (#,##0.00);_($* \" - \"??_);_(@_)"; } }
public static string Date { get { return "m/d/yy"; } }
public static string Time { get { return "[$-F400] h:mm:ss am/pm"; } }
public static string Percentage { get { return "0.00%"; } }
public static string Fraction { get { return "# ?/?"; } }
public static string Scientific { get { return "0.00E+00"; } }
public static string Text { get { return "@"; } }
public static string Special { get { return ";;"; } }
public static string Custom { get { return "#,##0_);[Red](#,##0)"; } }
}
Define "necessary".
It is necessary if you want the browser to know what the type of the file is. PHP automatically sets the Content-Type
header to text/html
if you don't override it so your browser is treating it as an HTML file that doesn't contain any HTML. If your output contained any HTML you'd see very different outcomes. If you were to send:
<b><i>test</i></b>
a Content-Type: text/html
would output:
test
whereas Content-Type: text/plain
would output:
<b><i>test</i></b>
TLDR Version: If you really are only outputing text then it doesn't really matter, but it IS wrong.
You can use a2enmod
or a2dismod
to enable/disable modules by name.
From terminal, run: sudo a2enmod php5
to enable PHP5 (or some other module), then sudo service apache2 reload
to reload the Apache2 configuration.
I'd recommend using JQuery's keyup and keydown methods on the document, as it normalizes the event codes, to make one solution crossbrowser.
For the right click, you can use oncontextmenu, however beware it can be buggy in IE8. See a chart of compatibility here:
http://www.quirksmode.org/dom/events/contextmenu.html
<p onclick="selectMe(1)" oncontextmenu="selectMe(2)">Click me</p>
$(document).keydown(function(event){
if(event.which=="17")
cntrlIsPressed = true;
});
$(document).keyup(function(){
cntrlIsPressed = false;
});
var cntrlIsPressed = false;
function selectMe(mouseButton)
{
if(cntrlIsPressed)
{
switch(mouseButton)
{
case 1:
alert("Cntrl + left click");
break;
case 2:
alert("Cntrl + right click");
break;
default:
break;
}
}
}
What you can do is set your default database using the sp_defaultdb system stored procedure. Log in as you have done and then click the New Query button. After that simply run the sp_defaultdb command as follows:
Exec sp_defaultdb @loginame='login', @defdb='master'
I got this error on my ubuntu box until I ran eclipse as root and installed from there:
$ gksudo eclipse
Eclipse was trying to download the packages to /usr/lib/* where I don't have write permissions
You have too many redundant nested arrays inside your jSON data, but it is possible to retrieve the information. Though like others have said you might want to clean it up.
use each() wrap within another each() until the last array.
for result.data[0].stuff[0].onetype[0]
in jQuery you could do the following:
`
$.each(data.result.data, function(index0, v) {
$.each(v, function (index1, w) {
$.each(w, function (index2, x) {
alert(x.id);
});
});
});
`
Workaround:
t = time()
t2 = time(t.hour+1, t.minute, t.second, t.microsecond)
You can also omit the microseconds, if you don't need that much precision.
you can try these:
document.getElementById("RootNode").onclick = function(){/*do something*/};
or
$('#RootNode').click(function(){/*do something*/});
or
$(document).on("click", "#RootNode", function(){/*do something*/});
There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload
or DOMReady
event, like:
//in Vanilla JavaScript
window.addEventListener("load", function(){
document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
$('#RootNode').click(function(){/*do something*/});
});
if you have the property "MyProperty" on your data-class, then you bind the IsChecked like this.... (the converter is optional, but sometimes you need that)
<Window.Resources>
<local:MyBoolConverter x:Key="MyBoolConverterKey"/>
</Window.Resources>
<checkbox IsChecked="{Binding Path=MyProperty, Converter={StaticResource MyBoolConverterKey}}"/>
As some of my servers are on an old Ubuntu LTS versions, I can't easily upgrade git to the latest version (which supports the -C option as described in some answers).
This trick works well for me, especially because it does not have the side effect of some other answers that leave you in a different directory from where you started.
pushd /X/Y
git pull
popd
Or, doing it as a one-liner:
pushd /X/Y; git pull; popd
Both Linux and Windows have pushd and popd commands.
I wrote a small CLI in Python and added GFM support. It's called Grip (Github Readme Instant Preview).
Install it with:
$ pip install grip
And to use it, simply:
$ grip
Then visit localhost:5000
to view the readme.md
file at that location.
You can also specify your own file:
$ grip CHANGES.md
And change port:
$ grip 8080
And of course, specifically render GitHub-Flavored Markdown, optionally with repository context:
$ grip --gfm --context=username/repo issue.md
Notable features:
stdin
and export to stdout
added in 3.0Hope this helps someone here. Check it out.
Average Shortest One Liner:
let avg = [1,2,3].reduce((a,v,i)=>(a*i+v)/(i+1));
Sum Shortest One Liner:
let sum = [1,2,3].reduce((a,b)=>a+b);
Use format
method with a specific pattern to extract the time.
Working example
var myDate = "2017-08-30T14:24:03";_x000D_
console.log(moment(myDate).format("HH:mm")); // 24 hour format_x000D_
console.log(moment(myDate).format("hh:mm a")); // use 'A' for uppercase AM/PM_x000D_
console.log(moment(myDate).format("hh:mm:ss A")); // with milliseconds
_x000D_
<script src="https://momentjs.com/downloads/moment.js"></script>
_x000D_
You can use JavaMail API to handle your email tasks. JavaMail API is available in JavaEE package and its jar is available for download. Sadly it cannot be used directly in an Android application since it uses AWT components which are completely incompatible in Android.
You can find the Android port for JavaMail at the following location: http://code.google.com/p/javamail-android/
Add the jars to your application and use the SMTP method
Pure and short bash.
f=$(cat numbers.txt)
echo $(( ${f//$'\n'/+} ))
I have to ask a question in return: is your GenSet
"checked" or "unchecked"?
What does that mean?
Checked: strong typing. GenSet
knows explicitly what type of objects it contains (i.e. its constructor was explicitly called with a Class<E>
argument, and methods will throw an exception when they are passed arguments that are not of type E
. See Collections.checkedCollection
.
-> in that case, you should write:
public class GenSet<E> {
private E[] a;
public GenSet(Class<E> c, int s) {
// Use Array native method to create array
// of a type only known at run time
@SuppressWarnings("unchecked")
final E[] a = (E[]) Array.newInstance(c, s);
this.a = a;
}
E get(int i) {
return a[i];
}
}
Unchecked: weak typing. No type checking is actually done on any of the objects passed as argument.
-> in that case, you should write
public class GenSet<E> {
private Object[] a;
public GenSet(int s) {
a = new Object[s];
}
E get(int i) {
@SuppressWarnings("unchecked")
final E e = (E) a[i];
return e;
}
}
Note that the component type of the array should be the erasure of the type parameter:
public class GenSet<E extends Foo> { // E has an upper bound of Foo
private Foo[] a; // E erases to Foo, so use Foo[]
public GenSet(int s) {
a = new Foo[s];
}
...
}
All of this results from a known, and deliberate, weakness of generics in Java: it was implemented using erasure, so "generic" classes don't know what type argument they were created with at run time, and therefore can not provide type-safety unless some explicit mechanism (type-checking) is implemented.
My suggestion to you is to write your own utility service. You can include the service in each controller or create a parent controller, assign the utility service to your scope and then every child controller will inherit this without you having to include it.
Example: http://plnkr.co/edit/NI7V9cLkQmEtWO36CPXy?p=preview
var app = angular.module('plunker', []);
app.controller('MainCtrl', function($scope, Utils) {
$scope.utils = Utils;
});
app.controller('ChildCtrl', function($scope, Utils) {
$scope.undefined1 = Utils.isUndefinedOrNull(1); // standard DI
$scope.undefined2 = $scope.utils.isUndefinedOrNull(1); // MainCtrl is parent
});
app.factory('Utils', function() {
var service = {
isUndefinedOrNull: function(obj) {
return !angular.isDefined(obj) || obj===null;
}
}
return service;
});
Or you could add it to the rootScope as well. Just a few options for extending angular with your own utility functions.
For me path for templateUrl was not correct
I was using
shopping-list-edit.component.html
Whereas it should have been
./shopping-list-edit.component.html
Silly mistake but happens when starting out. Hope that helps somebody in distress.
If it is a new project simply you can do like this :
$ git clone --recurse-submodules https://github.com/chaconinc/YourProjectName
If it is already installed than :
$ cd YourProjectName (for the cases you are not at right directory)
$ git submodule init
$ git submodule update
You can use the phpmyadmin setup page (./phpmyadmin/setup) to generate a new config file (config.inc.php
) for you. This file is found at the root of the phpMyAdmin directory.
Just create the config folder as prompted in setup page, add your servers, then click the 'Save' button. This will create a new config file in the config folder you just created.
You now have only to move the config.inc.php
file to the main phpMyAdmin folder, or just copy the lines concerning the servers if you got some old configuration done already you'd like to keep.
Don't forget to delete the config folder afterwards.
Have a look at wxArt2d it is a complete framework for 2d editing and plotting. See the screenshots for more examples.
Some interesting features:
In query browser right click on database and select processlist
There's only one registered mediatype for SVG, and that's the one you listed, image/svg+xml
. You can of course serve SVG as XML too, though browsers tend to behave differently in some scenarios if you do, for example I've seen cases where SVG used in CSS backgrounds fail to display unless served with the image/svg+xml
mediatype.
For me what works here is to using a version manager such as pyenv, which I strongly recommend to get your project environments and package versions well managed and separate from that of the operative system.
I had this same error after an OS update, but was easily fixed with pyenv install 3.7-dev
(the version I use).
df_buy['BUY'] = df_buy['BUY'].astype('float')
df_buy['BUY'] = ['€ {:,.2f}'.format(i) for i in list(df_buy['BUY'])]
In my case, "Sept8" in a csv file generated using R was converted into "8-Sept" by Excel 2013. The problem was solved by using write.xlsx2() function in the xlsx package to generate the output file in xlsx format, which can be loaded by Excel without unwanted conversion. So, if you are given a csv file, you can try loading it into R and converting it into xlsx using the write.xlsx2() function.
In order to support refactoring correctly (rename class), then you should use either:
MyClass.class.getName(); // full name with package
or (thanks to @James Van Huis):
MyClass.class.getSimpleName(); // class name and no more
Move all of your state and your handleClick
function from Header
to your MainWrapper
component.
Then pass values as props to all components that need to share this functionality.
class MainWrapper extends React.Component {
constructor() {
super();
this.state = {
sidbarPushCollapsed: false,
profileCollapsed: false
};
this.handleClick = this.handleClick.bind(this);
}
handleClick() {
this.setState({
sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
profileCollapsed: !this.state.profileCollapsed
});
}
render() {
return (
//...
<Header
handleClick={this.handleClick}
sidbarPushCollapsed={this.state.sidbarPushCollapsed}
profileCollapsed={this.state.profileCollapsed} />
);
Then in your Header's render() method, you'd use this.props
:
<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>
This one always keeps the right frame:
public extension UIView {
@discardableResult
public func addBlur(style: UIBlurEffect.Style = .extraLight) -> UIVisualEffectView {
let blurEffect = UIBlurEffect(style: style)
let blurBackground = UIVisualEffectView(effect: blurEffect)
addSubview(blurBackground)
blurBackground.translatesAutoresizingMaskIntoConstraints = false
blurBackground.bottomAnchor.constraint(equalTo: bottomAnchor).isActive = true
blurBackground.topAnchor.constraint(equalTo: topAnchor).isActive = true
blurBackground.leadingAnchor.constraint(equalTo: leadingAnchor).isActive = true
blurBackground.trailingAnchor.constraint(equalTo: trailingAnchor).isActive = true
return blurBackground
}
}
The following works lists all *.txt
files in the current dir, except those that begin with a number.
This works in bash
, dash
, zsh
and all other POSIX compatible shells.
for FILE in /some/dir/*.txt; do # for each *.txt file
case "${FILE##*/}" in # if file basename...
[0-9]*) continue ;; # starts with digit: skip
esac
## otherwise, do stuff with $FILE here
done
In line one the pattern /some/dir/*.txt
will cause the for
loop to iterate over all files in /some/dir
whose name end with .txt
.
In line two a case statement is used to weed out undesired files. – The ${FILE##*/}
expression strips off any leading dir name component from the filename (here /some/dir/
) so that patters can match against only the basename of the file. (If you're only weeding out filenames based on suffixes, you can shorten this to $FILE
instead.)
In line three, all files matching the case
pattern [0-9]*
) line will be skipped (the continue
statement jumps to the next iteration of the for
loop). – If you want to you can do something more interesting here, e.g. like skipping all files which do not start with a letter (a–z) using [!a-z]*
, or you could use multiple patterns to skip several kinds of filenames e.g. [0-9]*|*.bak
to skip files both .bak
files, and files which does not start with a number.
I have done the following to overcome the problem (ex.js script)
$ cat ex.js
import { Stack } from 'es-collections';
console.log("Successfully Imported");
$ node ex.js
/Users/nsaboo/ex.js:1
(function (exports, require, module, __filename, __dirname) { import { Stack } from 'es-collections';
^^^^^^
SyntaxError: Unexpected token import
at createScript (vm.js:80:10)
at Object.runInThisContext (vm.js:152:10)
at Module._compile (module.js:624:28)
at Object.Module._extensions..js (module.js:671:10)
at Module.load (module.js:573:32)
at tryModuleLoad (module.js:513:12)
at Function.Module._load (module.js:505:3)
at Function.Module.runMain (module.js:701:10)
at startup (bootstrap_node.js:194:16)
at bootstrap_node.js:618:3
# npm package installation
npm install --save-dev babel-preset-env babel-cli es-collections
# .babelrc setup
$ cat .babelrc
{
"presets": [
["env", {
"targets": {
"node": "current"
}
}]
]
}
# execution with node
$ npx babel ex.js --out-file ex-new.js
$ node ex-new.js
Successfully Imported
# or execution with babel-node
$ babel-node ex.js
Successfully Imported
It's best practice only to escape the quotes when you need to - if you can get away without escaping it, then do!
The only times you should need to escape are when trying to put "
inside a string, or '
in a character:
String quotes = "He said \"Hello, World!\"";
char quote = '\'';
If you need to create each ArrayList item in a single line then you can use this code
private void createFile(String file, ArrayList<String> arrData)
throws IOException {
FileWriter writer = new FileWriter(file + ".txt");
int size = arrData.size();
for (int i=0;i<size;i++) {
String str = arrData.get(i).toString();
writer.write(str);
if(i < size-1)**//This prevent creating a blank like at the end of the file**
writer.write("\n");
}
writer.close();
}
From the Java 11 BigDecimal
docs:
When a
MathContext
object is supplied with a precision setting of 0 (for example,MathContext.UNLIMITED
), arithmetic operations are exact, as are the arithmetic methods which take noMathContext
object. (This is the only behavior that was supported in releases prior to 5.)As a corollary of computing the exact result, the rounding mode setting of a
MathContext
object with a precision setting of 0 is not used and thus irrelevant. In the case of divide, the exact quotient could have an infinitely long decimal expansion; for example, 1 divided by 3.If the quotient has a nonterminating decimal expansion and the operation is specified to return an exact result, an
ArithmeticException
is thrown. Otherwise, the exact result of the division is returned, as done for other operations.
To fix, you need to do something like this:
a.divide(b, 2, RoundingMode.HALF_UP)
where 2 is the scale and RoundingMode.HALF_UP is rounding mode
For more details see this blog post.
First, Google created the "use less secure accounts method" function:
https://myaccount.google.com/security
Then created the another permission:
https://accounts.google.com/b/0/DisplayUnlockCaptcha
Hope it helps.
I tried all the method above.
Nothing of those worked for me.
Finally, I created a new DB and switched to it. everything was fine. Luckily, it wasn't so important DB (for self education purpose) so the damage wasn't so big.
Just wondering.. is that really possible in MySQL? it will delete t1 and t2? or I just misunderstood the question.
But if you just want to delete table1 with multiple join conditions, just don't alias the table you want to delete
this:
DELETE t1,t2
FROM table1 AS t1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
should be written like this to work in MSSQL:
DELETE table1
FROM table1
INNER JOIN table2 t2 ...
INNER JOIN table3 t3 ...
to contrast how the other two common RDBMS do a delete operation:
http://mssql-to-postgresql.blogspot.com/2007/12/deleting-duplicates-in-postgresql-ms.html
echo json_decode(file_get_contents('https://iplocation.hirak.cc/?ip='.$_SERVER['REMOTE_ADDR']))->country;
// for ip=190.2.145.41 output: Natherlands
Explination: previous api provide result like this for my ip (for exemple);
{
ip: "105.103.124.4",
country_code: "DZ",
country: "Algeria",
attribution: "Data from https://lite.ip2location.com/"
}
so to access to the country, we will need to decode the result as stdClass, to be accessible, because the result is text format, we add the json_decode() to the file_get_contents(), & from json_decode() returning stdClass (the same format) will access to country by ->country
Icarus answered a very similar question for me. Its not using "yum", but should still work for your purposes. Try,
wget http://mirror.olnevhost.net/pub/apache/maven/maven-3/3.0.5/binaries/apache-maven-3.0.5-bin.tar.gz
basically just go to the maven site. Find the version of maven you want. The file type and use the mirror for the wget statement above.
Afterwards the process is easy
run the following to extract the tar,
tar xvf apache-maven-3.0.5-bin.tar.gz
move maven to /usr/local/apache-maven
mv apache-maven-3.0.5 /usr/local/apache-maven
Next add the env variables to your ~/.bashrc file
export M2_HOME=/usr/local/apache-maven
export M2=$M2_HOME/bin
export PATH=$M2:$PATH
Execute these commands
source ~/.bashrc
6:. Verify everything is working with the following command
mvn -version
If you want to plot a single line connecting all the points in the list
plt.plot(li[:])
plt.show()
This will plot a line connecting all the pairs in the list as points on a Cartesian plane from the starting of the list to the end. I hope that this is what you wanted.
I had the same problem, when I used a inline-block on my menu I had the space between each "li" I found a simple solution, I don't remember where I found it, anyway here is what I did.
<li><a href="index.html" title="home" class="active">Home</a></li><!---->
<li><a href="news.html" title="news">News</a></li><!---->
<li><a href="about.html" title="about">About Us</a></li><!---->
<li><a href="contact.html" title="contact">Contact Us</a></li>
You add a comment sign between each end of, and start of : "li" Then the horizontal space disappear. Hope that answer to the question Thanks
For those coming across this in the future:
If you would like to see a list of relations for several schemas:
$psql mydatabase
mydatabase=# SET search_path TO public, usa; #schema examples
SET
mydatabase=# \dt
List of relations
Schema | Name | Type | Owner
--------+-----------------+-------+----------
public | counties | table | postgres
public | spatial_ref_sys | table | postgres
public | states | table | postgres
public | us_cities | table | postgres
usa | census2010 | table | postgres
I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:
Adding my answers for a couple of reasons:
What helped me was another option under Maven called as "Update Project" and then when I click it this window opens which has a checkbox that says "Force update of Snapshot/Releases". The real purpose of this checkbox is different I know but somehow it resolved the dependencies issue.
The length of the text that you are providing in each line is different, this is the problem, so if the second word is too long (see2.txt
is long 8 char which corresponds to a single tab lenght) it prints out a tab which goes to the next tabulation point.
One way to solve it is to programmatically add a pad to the f.getName()
text so each text generated: see.txt
or see2.txt
has the same lenght (for example see.txt_
and see2.txt
) so each tab automatically goes to the same tabulation point.
If you are developing with JDK 1.5 you can solve this using java.util.Formatter:
String format = "%-20s %5d\n";
System.out.format(format, "test", 1);
System.out.format(format, "test2", 20);
System.out.format(format, "test3", 5000);
this example will give you this print:
test 1
test2 20
test3 5000
GUID has longstanding usage in areas where it isn't necessarily a 128-bit value in the same way as a UUID. For example, the RSS specification defines GUIDs to be any string of your choosing, as long as it's unique, with an "isPermalink" attribute to specify that the value you're using is just a permalink back to the item being syndicated.
A Relation object passes unknown method calls through to an Eloquent query Builder, which is set up to only select the related objects. That Builder in turn passes unknown method calls through to its underlying query Builder.
This means you can use the exists()
or count()
methods directly from a relation object:
$model->relation()->exists(); // bool: true if there is at least one row
$model->relation()->count(); // int: number of related rows
Note the parentheses after relation
: ->relation()
is a function call (getting the relation object), as opposed to ->relation
which a magic property getter set up for you by Laravel (getting the related object/objects).
Using the count
method on the relation object (that is, using the parentheses) will be much faster than doing $model->relation->count()
or count($model->relation)
(unless the relation has already been eager-loaded) since it runs a count query rather than pulling all of the data for any related objects from the database, just to count them. Likewise, using exists
doesn't need to pull model data either.
Both exists()
and count()
work on all relation types I've tried, so at least belongsTo
, hasOne
, hasMany
, and belongsToMany
.
Don't forget to import Foundation
or UIKit
.
import Foundation
let trimmedString = " aaa "".trimmingCharacters(in: .whitespaces)
print(trimmedString)
Result:
"aaa"
Otherwise you'll get:
error: value of type 'String' has no member 'trimmingCharacters'
return self.trimmingCharacters(in: .whitespaces)
There is a pretty nice infinite scroll plugin here
I've never programmed one myself, but I would imagine this is how it works.
An event is bound to the the window scrolling
$(window).scroll(myInfinteScrollFunction);
The called function checks if scroll top is greater than the window size
function myInfiniteScrollFunction() {
if($(window).scrollTop() == $(window).height())
makeAjaxRequest();
}
An AJAX request is made, specifying which result # to start at, how many to grab, and any other parameters necessary for the data pull.
$.ajax({
type: "POST",
url: "myAjaxFile.php",
data: {"resultNum": 30, "numPerPage": 50, "query": "interesting%20icons" },
success: myInfiniteLoadFunction(msg)
});
The ajax returns some (most-likely JSON formatted) content, and passes them into the loadnig function.
Hope that makes sense.
Linux Mint 19.3
I installed Java Oracle manually, like this:
$ sudo ln -s /usr/lib/jvm/java-1.8.0_211/bin/javac /usr/bin/javac
When creating subdirectories hanging off from a non-existing parent directory(s) you must pass the -p
flag to mkdir
... Please update your Dockerfile with
RUN mkdir -p ...
I tested this and it's correct.
They're both joins and where that do the same thing.
Give a look at In MySQL queries, why use join instead of where?
file = open("filename.txt", newline='')
for row in self.data:
print(row)
Save data to a variable(file
), so you need a with
.
Maybe you forgot the await before returning your collection
This should work for you:
var movies = _db.Movies.OrderBy(c => c.Category).ThenBy(n => n.Name)
This will work from JS without coupling to HTML:
document.getElementById("click-button").onclick = onClickFunction;
function onClickFunction()
{
return functionWithArguments('You clicked the button!');
}
function functionWithArguments(text) {
document.getElementById("some-div").innerText = text;
}
I believe you could addClass to the element. But either way you'd have to use Jquery or reg JS
div {
opacity:0;
transition:opacity 1s linear;*
}
div.SomeClass {
opacity:1;
}
In my case, I was trying to find out if any library I was including in my project was redefining my window.player
. So, at the begining of my code, I just did:
Object.defineProperty(window, 'player', {
get: () => this._player,
set: v => {
console.log('window.player has been redefined!');
this._player = v;
}
});
I had the same issue. I wanted icons to appear by pressing the button but without any movement and sliding the enviroment, just like bulb: on and off, appeared and dissapeared, so I needed to make an empty div with fixed sizes.
width: 13px;
min-width: 13px;
did the trick for me
def _GetHtmlPage(self, addr):
headers = { 'User-Agent' : self.userAgent,
' Cookie' : self.cookies}
req = urllib2.Request(addr)
response = urllib2.urlopen(req)
print "ResponseInfo="
print response.info()
resultsHtml = unicode(response.read(), self.encoding)
return resultsHtml
Why not just set add path to to the bin of the app. For MacVim, I did the following.
export PATH=/Applications/MacVim.app/Contents/bin:$PATH
An alias, is another option I tried.
alias mvim='/Applications/MacVim.app/Contents/bin/mvim'
alias gvim=mvim
With the export PATH I can call all of the commands in the app. Arguments passed well for my test with MacVim. Whereas the alias, I had to alias each command in the bin.
mvim README.txt
gvim Anotherfile.txt
Enjoy the power of alias and PATH. However, you do need to monitor changes when the OS is upgraded.
You should be using DATEADD
is Sql server so if try this simple select you will see the affect
Select DATEADD(Month, -1, getdate())
Result
2013-04-20 14:08:07.177
in your case try this query
SELECT name
FROM (
SELECT name FROM
Hist_answer
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
UNION ALL
SELECT name FROM
Hist_internet
WHERE id_city='34324' AND datetime >= DATEADD(month,-1,GETDATE())
) x
GROUP BY name ORDER BY name
$_SERVER['REQUEST_URI']
For more details on what info is available in the $_SERVER array, see the PHP manual page for it.
If you also need the query string (the bit after the ?
in a URL), that part is in this variable:
$_SERVER['QUERY_STRING']
It makes absolutely no sense to use @Override when implementing an interface method. There's no advantage to using it in that case--the compiler will already catch your mistake, so it's just unnecessary clutter.
Thanks to @dahlbyk, the author of Posh-Git, for posting his config as a gist. It helped me resolve my configuration issue.
[diff]
tool = bc3
[difftool]
prompt = false
[difftool "bc3"]
cmd = \"c:/program files (x86)/beyond compare 3/bcomp.exe\" \"$LOCAL\" \"$REMOTE\"
[merge]
tool = bc3
[mergetool]
prompt = false
keepBackup = false
[mergetool "bc3"]
cmd = \"c:/program files (x86)/beyond compare 3/bcomp.exe\" \"$LOCAL\" \"$REMOTE\" \"$BASE\" \"$MERGED\"
trustExitCode = true
[alias]
dt = difftool
mt = mergetool
I was unable to solve this problem with the solutions stated here (although the answer stated has, no doubt, cleared my concepts). I faced this problem two times and each time I have tried different solutions (in the Eclipse IDE).
main
methods in different classes of my project. So, I had deleted the main
method from subsequent classes.Lose the contentType: "application/json; charset=utf-8",
. You're not sending JSON to the server, you're sending a normal POST query (that happens to contain a JSON string).
That should make what you have work.
Thing is, you don't need to use JSON.stringify
or json_decode
here at all. Just do:
data: {myData:postData},
Then in PHP:
$obj = $_POST['myData'];
I just had this problem, and this was my solution:
#floatingMenu + * {
margin-top: 35px;
}
Adjust for the height of your floatingMenu. If you don't know for sure that it's a div following then you can use *
rather than div
. This is all valid CSS2.
It seems having msysgit (Git for Windows) installed is causing the problem.
In most cases you'll have a pretty recent version of Git for Windows installed. Cited from https://code.google.com/p/tortoisegit/:
There was a security issue in Git, see here. Git for Windows < 1.9.5 is affected - so you should update, TortoiseGit itself is not affected (using the default configuration; only if libgit2 is manually enabled for checkout/fetching). TortoiseGit 1.8.13.0 includes all fixes.
But it seems Aptana Studio Installer won't accept any pre-installed version of Git for Windows!
What you need to do:
That's it !!!
My app manage a lot of images and it died with a OutOfMemoryError. This helped me. In the Manifest.xml Add
<application
....
android:largeHeap="true">
Convert.ToString(FileUpload1.PostedFile.FileName);
Constructor The constructor is a method that's automatically called during the creation of an object from a class. ... Simply put, the constructor aids in constructing things. In React, the constructor is no different. It can be used to bind event handlers to the component and/or initializing the local state of the component.Jan 23, 2019
getInitialState In ES6 classes, you can define the initial state by assigning this.state in the constructor:
Look at this example
var Counter = createReactClass({
getInitialState: function() {
return {count: this.props.initialCount};
},
// ...
});
With createReactClass(), you have to provide a separate getInitialState method that returns the initial state:
Apparently, your class "Format" is involved in the problem. Check your declaration of this class, especially if you did it inside another class you probably forgot the @implementation or something similar.
If you know the range of the inputs (which you do since your function takes an int
), you can precompute a table of primes less than or equal to the square root of the max input (2^31-1 in this case), and then test for divisibility by each prime in the table less than or equal to the square root of the number given.
Update OkHttp 3.0, the getAcceptedIssuers()
function must return an empty array instead of null
.
Arrays.stream(ints).forEach(list::add);
This basically does 1 (iterate over the array) with 2 (using Java 8). (with 1 and 2 referring to your original question)
You can check Visual Studio Downloads for available Visual Studio Community
, Visual Studio Professional
, Visual Studio Enterprise
and Visual Studio Code
download links.
Update!
There is no direct links of Visual Studio 2015
at Visual Studio Downloads anymore. but the below links still works.
OR simply click on direct links below (for .iso/.exe file):
VSCode area:
My suggested name for this technique (including multiple top-level classes in a single source file) would be "mess". Seriously, I don't think it's a good idea - I'd use a nested type in this situation instead. Then it's still easy to predict which source file it's in. I don't believe there's an official term for this approach though.
As for whether this actually changes between implementations - I highly doubt it, but if you avoid doing it in the first place, you'll never need to care :)
I had a similar issue and I had to delete everything from the bin and obj folders and rebuild to get past my issue. Hope this helps.
For the special date of January 1, 1970 there are multiple options.
For any other starting date you need to get the difference between the two dates in seconds. Subtracting two dates gives a timedelta
object, which as of Python 2.7 has a total_seconds()
function.
>>> (t-datetime.datetime(1970,1,1)).total_seconds()
1256083200.0
The starting date is usually specified in UTC, so for proper results the datetime
you feed into this formula should be in UTC as well. If your datetime
isn't in UTC already, you'll need to convert it before you use it, or attach a tzinfo
class that has the proper offset.
As noted in the comments, if you have a tzinfo
attached to your datetime
then you'll need one on the starting date as well or the subtraction will fail; for the example above I would add tzinfo=pytz.utc
if using Python 2 or tzinfo=timezone.utc
if using Python 3.
I just had the same problem.
By using Task Manager to kill the build process and exiting Eclipse with no projects open, I was able to get back into Eclipse and clean the project without opening it. I then restarted Eclipse again,loaded my project and all OK.
It might be so late, anyway here is my way in converting Matrix to vector:
library(gdata)
vector_data<- unmatrix(yourdata,byrow=T))
hope that will help
You can also do it by toggling between display: block on hover and display:none without hover to produce the effect.
edit (sorry I thought you wanted VBA).
Anytime you try to read a non-existent value from the registry, you get back a Null. Thus all you have to do is check for a Null value.
Use IsNull
not IsEmpty
.
Const HKEY_LOCAL_MACHINE = &H80000002
strComputer = "."
Set objRegistry = GetObject("winmgmts:\\" & _
strComputer & "\root\default:StdRegProv")
strKeyPath = "SOFTWARE\Microsoft\Windows NT\CurrentVersion"
strValueName = "Test Value"
objRegistry.GetStringValue HKEY_LOCAL_MACHINE,strKeyPath,strValueName,strValue
If IsNull(strValue) Then
Wscript.Echo "The registry key does not exist."
Else
Wscript.Echo "The registry key exists."
End If
vim -c 'execute "silent !echo " . &fileencoding | q' {filename}
aliased somewhere in my bash configuration as
alias vic="vim -c 'execute \"silent \!echo \" . &fileencoding | q'"
so I just type
vic {filename}
On my vanilla OSX Yosemite, it yields more precise results than "file -I":
$ file -I pdfs/udocument0.pdf
pdfs/udocument0.pdf: application/pdf; charset=binary
$ vic pdfs/udocument0.pdf
latin1
$
$ file -I pdfs/t0.pdf
pdfs/t0.pdf: application/pdf; charset=us-ascii
$ vic pdfs/t0.pdf
utf-8
You didn't hear it from me, the PM for Razor, but in Razor 2 (Web Pages 2 and MVC 4) we'll have conditional attributes built into Razor(as of MVC 4 RC tested successfully), so you can just say things like this...
<input type="text" id="@strElementID" class="@strCSSClass" />
If strCSSClass is null then the class attribute won't render at all.
SSSHHH...don't tell. :)
Please remove all jar files of Http from libs folder and add below dependencies in gradle file :
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4.3'
Thanks.
Instead of specifying a deployment target in pod post install, you can delete the pod deployment target, which causes the deployment target to be inherited from the podfile platform.
You may need to run pod install for the effect to take place.
platform :ios, '12.0'
post_install do |installer|
installer.pods_project.targets.each do |target|
target.build_configurations.each do |config|
config.build_settings.delete 'IPHONEOS_DEPLOYMENT_TARGET'
end
end
end
Tested and working!
with https, user & password
<?php
//Data, connection, auth
$dataFromTheForm = $_POST['fieldName']; // request data from the form
$soapUrl = "https://connecting.website.com/soap.asmx?op=DoSomething"; // asmx URL of WSDL
$soapUser = "username"; // username
$soapPassword = "password"; // password
// xml post structure
$xml_post_string = '<?xml version="1.0" encoding="utf-8"?>
<soap:Envelope xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/">
<soap:Body>
<GetItemPrice xmlns="http://connecting.website.com/WSDL_Service"> // xmlns value to be set to your WSDL URL
<PRICE>'.$dataFromTheForm.'</PRICE>
</GetItemPrice >
</soap:Body>
</soap:Envelope>'; // data from the form, e.g. some ID number
$headers = array(
"Content-type: text/xml;charset=\"utf-8\"",
"Accept: text/xml",
"Cache-Control: no-cache",
"Pragma: no-cache",
"SOAPAction: http://connecting.website.com/WSDL_Service/GetPrice",
"Content-length: ".strlen($xml_post_string),
); //SOAPAction: your op URL
$url = $soapUrl;
// PHP cURL for https connection with auth
$ch = curl_init();
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, 1);
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_USERPWD, $soapUser.":".$soapPassword); // username and password - declared at the top of the doc
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_ANY);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $xml_post_string); // the SOAP request
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// converting
$response = curl_exec($ch);
curl_close($ch);
// converting
$response1 = str_replace("<soap:Body>","",$response);
$response2 = str_replace("</soap:Body>","",$response1);
// convertingc to XML
$parser = simplexml_load_string($response2);
// user $parser to get your data out of XML response and to display it.
?>
In my case (after renaming application namespace manually) I had to reselect the Startup object in Project properties.
Difference in output of map and flatMap:
1.flatMap
val a = sc.parallelize(1 to 10, 5)
a.flatMap(1 to _).collect()
Output:
1, 1, 2, 1, 2, 3, 1, 2, 3, 4, 1, 2, 3, 4, 5, 1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 5, 6, 7, 1, 2, 3, 4, 5, 6, 7, 8, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10
2.map
:
val a = sc.parallelize(List("dog", "salmon", "salmon", "rat", "elephant"), 3)
val b = a.map(_.length).collect()
Output:
3 6 6 3 8
Take a look here: http://longgoldenears.blogspot.com/2007/09/triple-equals-in-javascript.html
The 3 equal signs mean "equality without type coercion". Using the triple equals, the values must be equal in type as well.
0 == false // true
0 === false // false, because they are of a different type
1 == "1" // true, automatic type conversion for value only
1 === "1" // false, because they are of a different type
null == undefined // true
null === undefined // false
'0' == false // true
'0' === false // false
However, I might not be taking the best approach, but this is how I have created some Switch
like UIs in few of my apps.
Here is the code -
<RadioGroup
android:checkedButton="@+id/offer"
android:id="@+id/toggle"
android:layout_width="match_parent"
android:layout_height="30dp"
android:layout_marginBottom="@dimen/margin_medium"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:layout_marginTop="@dimen/margin_medium"
android:background="@drawable/pink_out_line"
android:orientation="horizontal">
<RadioButton
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:layout_marginLeft="1dp"
android:id="@+id/search"
android:background="@drawable/toggle_widget_background"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:button="@null"
android:gravity="center"
android:text="Search"
android:textColor="@color/white" />
<RadioButton
android:layout_marginRight="1dp"
android:layout_marginTop="1dp"
android:layout_marginBottom="1dp"
android:id="@+id/offer"
android:layout_width="0dp"
android:layout_height="match_parent"
android:layout_weight="1"
android:background="@drawable/toggle_widget_background"
android:button="@null"
android:gravity="center"
android:text="Offers"
android:textColor="@color/white" />
</RadioGroup>
pink_out_line.xml
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<corners android:radius="2dp" />
<solid android:color="#80000000" />
<stroke
android:width="1dp"
android:color="@color/pink" />
</shape>
toggle_widget_background.xml
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@color/pink" android:state_checked="true" />
<item android:drawable="@color/dark_pink" android:state_pressed="true" />
<item android:drawable="@color/transparent" />
</selector>
use the val() function
Use gson to convert your object to JSON and pass it through intent. In the new Activity convert the JSON to an object.
In your build.gradle
, add this to your dependencies
implementation 'com.google.code.gson:gson:2.8.4'
In your Activity, convert the object to json-string:
Gson gson = new Gson();
String myJson = gson.toJson(vp);
intent.putExtra("myjson", myjson);
In your receiving Activity, convert the json-string back to the original object:
Gson gson = new Gson();
YourObject ob = gson.fromJson(getIntent().getStringExtra("myjson"), YourObject.class);
For Kotlin it's quite the same
Pass the data
val gson = Gson()
val intent = Intent(this, YourActivity::class.java)
intent.putExtra("identifier", gson.toJson(your_object))
startActivity(intent)
Receive the data
val gson = Gson()
val yourObject = gson.fromJson<YourObject>(intent.getStringExtra("identifier"), YourObject::class.java)
Sounds like more work than its worth.
1) Why not just have a single JavaScript variable that stores a reference to the currently selected element\jQuery object.
2) Why not add a class to the currently selected element. Then you could query the DOM for the ".active" class or something.
vehicle[] car = new vehicle[N];
You can use input text with "list" attribute, which refers to the datalist of values.
<input type="text" name="city" list="cityname">_x000D_
<datalist id="cityname">_x000D_
<option value="Boston">_x000D_
<option value="Cambridge">_x000D_
</datalist>
_x000D_
This creates a free text input field that also has a drop-down to select predefined choices. Attribution for example and more information: https://www.w3.org/wiki/HTML/Elements/datalist
"Then" is a command in bash, thus it needs a ";" or a newline before it.
#!/bin/bash
echo "start\n"
for f in *.jpg
do
fname=$(basename "$f")
echo "fname is $fname\n"
fname="${filename%.*}"
echo "fname is $fname\n"
if [$[fname%2] -eq 1 ]
then
echo "removing $fname\n"
rm $f
fi
done
The API Guide has it all wrong (really Google?). With Maps API v2 you do not need to enable a layer to show yourself, there is a simple call to the GoogleMaps instance you created with your map.
The actual documentation that Google provides gives you your answer. You just need to
// map is a GoogleMap object
map.isMyLocationEnabled = true
// map is a GoogleMap object
map.setMyLocationEnabled(true);
and watch the magic happen.
Just make sure that you have location permission and requested it at runtime on API Level 23 (M) or above
I resolved the problem using useCORS: true
option
html2canvas(document.getElementsByClassName("droppable-area")[0], { useCORS:true}).then(function (canvas){
var imgBase64 = canvas.toDataURL();
// console.log("imgBase64:", imgBase64);
var imgURL = "data:image/" + imgBase64;
var triggerDownload = $("<a>").attr("href", imgURL).attr("download", "layout_"+new Date().getTime()+".jpeg").appendTo("body");
triggerDownload[0].click();
triggerDownload.remove();
});
Another way to do this is with union:
INSERT INTO Data ( Col1 )
select 'hello'
union
select 'world'
Storing with json or serialized array is the best solution for now. With some situations (trimming " ' characters) json might be getting trouble but serialize should be great choice.
Note: If you change serialized data manually, you need to be careful about character count.
You can use the selectInstances
method in Eclipse Collections. This will involved creating a new collection however so will not be as efficient as the accepted solution which uses casting.
List<CharSequence> parent =
Arrays.asList("1","2","3", new StringBuffer("4"));
List<String> strings =
Lists.adapt(parent).selectInstancesOf(String.class);
Assert.assertEquals(Arrays.asList("1","2","3"), strings);
I included StringBuffer
in the example to show that selectInstances
not only downcasts the type, but will also filter if the collection contains mixed types.
Note: I am a committer for Eclipse Collections.
Seems you need to use JToggleButton
:
JToggleButton tb = new JToggleButton("push me");
tb.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent e) {
JToggleButton btn = (JToggleButton) e.getSource();
btn.setText(btn.isSelected() ? "pushed" : "push me");
}
});
As of Powershell v3, PSsessions allow for any native cmdlet to be run on a remote machine
$session = New-PSsession -Computername "YourServerName"
Invoke-Command -Session $Session -ScriptBlock {Restart-Service "YourServiceName"}
Remove-PSSession $Session
See here for more information
In Laravel 5.6, assuming the name of your subfolder' is Api
:
In your controller, you need these two lines:
namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
And in your route file api.php
, you need:
Route::resource('/myapi', 'Api\MyController');
Are the files on the same server as the PHP script? If so, just keep the files out of the web root and make sure your PHP script has read permissions for wherever they're stored.
As of Python 3.5 you can simply do:
from pathlib import Path
Path(__file__).stem
See more here: https://docs.python.org/3.5/library/pathlib.html#pathlib.PurePath.stem
For example, I have a file under my user directory named test.py
with this inside:
from pathlib import Path
print(Path(__file__).stem)
print(__file__)
running this outputs:
>>> python3.6 test.py
test
test.py