I applied CSS styling to an anchored HREF attribute fully emulating the push button behaviors I needed (hover, active, background-color, etc., etc.). HTML markup is much simpler a-n-d eliminates the get/post complexity associated with using a form-based approach.
<a class="GYM" href="http://www.spufalcons.com/index.aspx?tab=gymnastics&path=gym">Gymnastics</a>
Actually, this example helped me to understand what does (function($) {})(jQuery);
mean.
Consider this:
// Clousure declaration (aka anonymous function)
var f = function(x) { return x*x; };
// And use of it
console.log( f(2) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function(x) { return x*x; })(2) ); // Gives: 4
And now consider this:
jQuery
is a variable holding jQuery object.$
is a variable
name like any other (a
, $b
, a$b
etc.) and it doesn't have any
special meaning like in PHP.Knowing that we can take another look at our example:
var $f = function($) { return $*$; };
var jQuery = 2;
console.log( $f(jQuery) ); // Gives: 4
// An inline version (immediately invoked)
console.log( (function($) { return $*$; })(jQuery) ); // Gives: 4
For a concrete example of accessing the SMS/MMS database, take a look at gTalkSMS.
Join on one-to-many relation in JPQL looks as follows:
select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName
When several properties are specified in select
clause, result is returned as Object[]
:
Object[] temp = (Object[]) em.createNamedQuery("...")
.setParameter("groupName", groupName)
.getSingleResult();
String fname = (String) temp[0];
String lname = (String) temp[1];
By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table
to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:
@Entity @Table(name = "Users")
public class User implements Serializable { ... }
First thing that should pop in a developer head while formatting a number into char sequence should be care of such details like do it will be possible to reverse the operation.
And other aspect is providing proper result. So you want to truncate the number or round it.
So before you start you should ask your self, am i interested on the value or not.
To achieve your goal you have multiple options but most of them refer to Format and Formatter, but i just suggest to look in this answer.
I just had this problem. This is what worked for me:
pip install botocore==1.13.20
What you could do is creating an instance of a GregorianCalendar
and then set the Date
as a start time:
Date date;
Calendar myCal = new GregorianCalendar();
myCal.setTime(date);
However, another approach is to not use Date
at all. You could use an approach like this:
private Calendar startTime;
private long duration;
private long startNanos; //Nano-second precision, could be less precise
...
this.startTime = Calendar.getInstance();
this.duration = 0;
this.startNanos = System.nanoTime();
public void setEndTime() {
this.duration = System.nanoTime() - this.startNanos;
}
public Calendar getStartTime() {
return this.startTime;
}
public long getDuration() {
return this.duration;
}
In this way you can access both the start time and get the duration from start to stop. The precision is up to you of course.
I had this problem and found that removing the following folder helped, even with the non-Express edition.Express:
C:\Users\<user>\Documents\IISExpress
I also suggest using contourf(Z)
. For my problem, I wanted to visualize a 3D histogram in 2D, but the contours were too smooth to represent a top view of histogram bars.
So in my case, I prefer to use jucestain's answer. The default shading faceted
of pcolor()
is more suitable.
However, pcolor()
does not use the last row and column of the plotted matrix. For this, I used the padarray()
function:
pcolor(padarray(Z,[1 1],0,'post'))
Sorry if that is not really related to the original post
$('select').on('change', function (e) {
var optionSelected = $("option:selected", this);
var valueSelected = this.value;
....
});
in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.
As others have noted, in Notepad++ 6.0 and later, it is possible to use the "Replace" feature to delete all lines that begin with ";" or "#".
Tao provides a regular expression that serves as a starting point, but it does not account for white-space that may exist before the ";" or "#" character on a given line. For example, lines that begin with ";" or "#" but are "tabbed-in" will not be deleted when using Tao's regular expression, ^(#|;).*\r\n
.
Tao's regular expression does not account for the caveat mentioned in BoltClock's answer, either: variances in newline characters across systems.
An improvement is to use ^(\s)*(#|;).*(\r\n|\r|\n)?
, which accounts for leading white-space and the newline character variances. Also, the trailing ?
handles cases in which the last line of the file begins with #
or ;
, but does not end with a newline.
For the curious, it is possible to discern which type of newline character is used in a given document (and more than one type may be used): View -> Show Symbol -> Show End of Line.
This is really just an expansion of BBB's answer which lead to to get my experiment working.
This script will simply create a file /tmp/testfile when you click on the button that says "Open Script".
This requires 3 files.
The File Tree:
root@test:/var/www/html# tree testscript/
testscript/
+-- index.html
+-- testexec.php
+-- test.sh
1. The main WebPage:
root@test:/var/www/html# cat testscript/index.html
<form action="/testscript/testexec.php">
<input type="submit" value="Open Script">
</form>
2. The PHP Page that runs the script and redirects back to the main page:
root@test:/var/www/html# cat testscript/testexec.php
<?php
shell_exec("/var/www/html/testscript/test.sh");
header('Location: http://192.168.1.222/testscript/index.html?success=true');
?>
3. The Script :
root@test:/var/www/html# cat testscript/test.sh
#!/bin/bash
touch /tmp/testfile
With lodash (or underscore) You may do
var my_object = { a:undefined, b:2, c:4, d:undefined, e:null };
var passedKeys = _.reject(Object.keys(my_object), function(key){ return _.isUndefined(my_object[key]) || _.isNull(my_object[key]) })
newObject = {};
_.each(passedKeys, function(key){
newObject[key] = my_object[key];
});
Otherwise, with vanilla JavaScript, you can do
var my_object = { a:undefined, b:2, c:4, d:undefined };
var new_object = {};
Object.keys(my_object).forEach(function(key){
if (typeof my_object[key] != 'undefined' && my_object[key]!=null){
new_object[key] = my_object[key];
}
});
Not to use a falsey test, because not only "undefined" or "null" will be rejected, also is other falsey value like "false", "0", empty string, {}. Thus, just to make it simple and understandable, I opted to use explicit comparison as coded above.
Don't build it if you can buy it.
I heard this quote recently, and it really seems fitting as a guide line. Ask yourself this... How much time was spent working on the file handling portion of your app? I suspect a fair amount of time was spent optimizing this code for performance. If you had been using a relational database all along, you would have spent considerably less time handling this portion of your application. You would have had more time for the true "business" aspect of your app.
boolean compare(String str1, String str2) {
if (str1 == null || str2 == null)
return str1 == str2;
return str1.equals(str2);
}
Your .mobile
div has the following styles on it:
.mobile {
display: none !important;
visibility: hidden !important;
}
Therefore you need to override the visibility
property with visible
in addition to overriding the display
property with block
. Like so:
.visible-sm {
display: block !important;
visibility: visible !important;
}
I like Open DBDiff.
While not the most complete tool, it works great, it's free, and it's very easy to use.
Search (Ctrl+F) your harddrive(s) for: SDK Manager.exe or adb.exe
The local names for a function are decided when the function is defined:
>>> x = 1
>>> def inc():
... x += 5
...
>>> inc.__code__.co_varnames
('x',)
In this case, x
exists in the local namespace. Execution of x += 5
requires a pre-existing value for x
(for integers, it's like x = x + 5
), and this fails at function call time because the local name is unbound - which is precisely why the exception UnboundLocalError
is named as such.
Compare the other version, where x
is not a local variable, so it can be resolved at the global scope instead:
>>> def incg():
... print(x)
...
>>> incg.__code__.co_varnames
()
Similar question in faq: http://docs.python.org/faq/programming.html#why-am-i-getting-an-unboundlocalerror-when-the-variable-has-a-value
$(document.body).on('hidden.bs.modal', function () {
$('#myModal').removeData('bs.modal')
});
I know this post is old, but in case someone is searching google i think i should mention what fixed my problem. After the 3 steps from above the error message was gone but the screen still stayed black and opening an .apk got stuck on file transfer. It had something to do with a VPN application (in my case Hamachi). I just closed it and then the emulator ran fine. This post prompted me to do so: https://groups.google.com/forum/#!searchin/genymotion-users/network/genymotion-users/QAX_UrAzEn0/o947IXpsDuIJ
You wanted to change the layout at runtime on button click. But that is not possible and as it has been rightly stated above, you need to restart the activity. You will come across a similar problem when u plan on changing the theme based on user's selection but it will not reflect in runtime. You will have to restart the activity.
You can specify both max post size and max file size limit in php.ini
post_max_size = 64M
upload_max_filesize = 64M
This page provides great understanding about the constructor
and destructor
attribute implementation and the sections within within ELF that allow them to work. After digesting the information provided here, I compiled a bit of additional information and (borrowing the section example from Michael Ambrus above) created an example to illustrate the concepts and help my learning. Those results are provided below along with the example source.
As explained in this thread, the constructor
and destructor
attributes create entries in the .ctors
and .dtors
section of the object file. You can place references to functions in either section in one of three ways. (1) using either the section
attribute; (2) constructor
and destructor
attributes or (3) with an inline-assembly call (as referenced the link in Ambrus' answer).
The use of constructor
and destructor
attributes allow you to additionally assign a priority to the constructor/destructor to control its order of execution before main()
is called or after it returns. The lower the priority value given, the higher the execution priority (lower priorities execute before higher priorities before main() -- and subsequent to higher priorities after main() ). The priority values you give must be greater than100
as the compiler reserves priority values between 0-100 for implementation. Aconstructor
or destructor
specified with priority executes before a constructor
or destructor
specified without priority.
With the 'section' attribute or with inline-assembly, you can also place function references in the .init
and .fini
ELF code section that will execute before any constructor and after any destructor, respectively. Any functions called by the function reference placed in the .init
section, will execute before the function reference itself (as usual).
I have tried to illustrate each of those in the example below:
#include <stdio.h>
#include <stdlib.h>
/* test function utilizing attribute 'section' ".ctors"/".dtors"
to create constuctors/destructors without assigned priority.
(provided by Michael Ambrus in earlier answer)
*/
#define SECTION( S ) __attribute__ ((section ( S )))
void test (void) {
printf("\n\ttest() utilizing -- (.section .ctors/.dtors) w/o priority\n");
}
void (*funcptr1)(void) SECTION(".ctors") =test;
void (*funcptr2)(void) SECTION(".ctors") =test;
void (*funcptr3)(void) SECTION(".dtors") =test;
/* functions constructX, destructX use attributes 'constructor' and
'destructor' to create prioritized entries in the .ctors, .dtors
ELF sections, respectively.
NOTE: priorities 0-100 are reserved
*/
void construct1 () __attribute__ ((constructor (101)));
void construct2 () __attribute__ ((constructor (102)));
void destruct1 () __attribute__ ((destructor (101)));
void destruct2 () __attribute__ ((destructor (102)));
/* init_some_function() - called by elf_init()
*/
int init_some_function () {
printf ("\n init_some_function() called by elf_init()\n");
return 1;
}
/* elf_init uses inline-assembly to place itself in the ELF .init section.
*/
int elf_init (void)
{
__asm__ (".section .init \n call elf_init \n .section .text\n");
if(!init_some_function ())
{
exit (1);
}
printf ("\n elf_init() -- (.section .init)\n");
return 1;
}
/*
function definitions for constructX and destructX
*/
void construct1 () {
printf ("\n construct1() constructor -- (.section .ctors) priority 101\n");
}
void construct2 () {
printf ("\n construct2() constructor -- (.section .ctors) priority 102\n");
}
void destruct1 () {
printf ("\n destruct1() destructor -- (.section .dtors) priority 101\n\n");
}
void destruct2 () {
printf ("\n destruct2() destructor -- (.section .dtors) priority 102\n");
}
/* main makes no function call to any of the functions declared above
*/
int
main (int argc, char *argv[]) {
printf ("\n\t [ main body of program ]\n");
return 0;
}
output:
init_some_function() called by elf_init()
elf_init() -- (.section .init)
construct1() constructor -- (.section .ctors) priority 101
construct2() constructor -- (.section .ctors) priority 102
test() utilizing -- (.section .ctors/.dtors) w/o priority
test() utilizing -- (.section .ctors/.dtors) w/o priority
[ main body of program ]
test() utilizing -- (.section .ctors/.dtors) w/o priority
destruct2() destructor -- (.section .dtors) priority 102
destruct1() destructor -- (.section .dtors) priority 101
The example helped cement the constructor/destructor behavior, hopefully it will be useful to others as well.
Use a collection of some sort - this will make the code more readable and hide away all those constants. A simple way would be with a list:
// Declared with constants
private static List<Integer> myConstants = new ArrayList<Integer>(){{
add(12);
add(16);
add(19);
}};
// Wherever you are checking for presence of the constant
if(myConstants.contains(x)){
// ETC
}
As Bohemian points out the list of constants can be static so it's accessible in more than one place.
For anyone interested, the list in my example is using double brace initialization. Since I ran into it recently I've found it nice for writing quick & dirty list initializations.
volatile
tells the compiler that your variable may be changed by other means, than the code that is accessing it. e.g., it may be a I/O-mapped memory location. If this is not specified in such cases, some variable accesses can be optimised, e.g., its contents can be held in a register, and the memory location not read back in again.
dep and clg alphabets validation is not working
var selectedRow = null;
function validateform() {
var table = document.getElementById("mytable");
var rowCount = table.rows.length;
console.log(rowCount);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
return false;
}
var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id")
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var dept = "`@#$%^&*()+=-[]\\\';,./{}|\":<>?~_";
if (dept.match(a)) {
alert("special charachers found");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
console.log(table);
var row = table.insertRow(rowCount);
row.setAttribute('id', rowCount);
var cell0 = row.insertCell(0);
var cell1 = row.insertCell(1);
var cell2 = row.insertCell(2);
var cell3 = row.insertCell(3);
var cell4 = row.insertCell(4);
var cell5 = row.insertCell(5);
var cell6 = row.insertCell(6);
var cell7 = row.insertCell(7);
cell0.innerHTML = rowCount;
cell1.innerHTML = x;
cell2.innerHTML = y;
cell3.innerHTML = z;
cell4.innerHTML = a;
cell5.innerHTML = b;
cell6.innerHTML = '<Button type="button" onclick=onEdit("' + x + '","' + y + '","' + z + '","' + a + '","' + b + '","' + rowCount + '")>Edit</BUTTON>';
cell7.innerHTML = '<Button type="button" onclick=deletefunction(' + rowCount + ')>Delete</BUTTON>';
}
function emptyfunction() {
document.getElementById("usrname").value = "";
document.getElementById("usremail").value = "";
document.getElementById("usrage").value = "";
document.getElementById("usrdpt").value = "";
document.getElementById("usrclg").value = "";
}
function onEdit(x, y, z, a, b, rowCount) {
selectedRow = rowCount;
console.log(selectedRow);
document.forms["myform"]["usrname"].value = x;
document.forms["myform"]["usremail"].value = y;
document.forms["myform"]["usrage"].value = z;
document.forms["myform"]["usrdpt"].value = a;
document.forms["myform"]["usrclg"].value = b;
document.getElementById('Add').style.display = 'none';
document.getElementById('update').style.display = 'block';
}
function deletefunction(rowCount) {
document.getElementById("mytable").deleteRow(rowCount);
}
function onUpdatefunction() {
var row = document.getElementById(selectedRow);
console.log(row);
var x = document.forms["myform"]["usrname"].value;
if (x == "") {
alert("name must be filled out");
document.myForm.x.focus();
return false;
}
var y = document.forms["myform"]["usremail"].value;
if (y == "") {
alert("email must be filled out");
document.myForm.y.focus();
return false;
}
var mail = /[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}/
if (mail.test(y)) {
//alert("email must be a valid format");
//return false ;
} else {
alert("not a mail id");
return false;
}
var z = document.forms["myform"]["usrage"].value;
if (z == "") {
alert("age must be filled out");
document.myForm.z.focus();
return false;
}
if (isNaN(z) || z < 1 || z > 100) {
alert("The age must be a number between 1 and 100");
return false;
}
var a = document.forms["myform"]["usrdpt"].value;
if (a == "") {
alert("Dept must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (a.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
var b = document.forms["myform"]["usrclg"].value;
if (b == "") {
alert("College must be filled out");
return false;
}
var letters = /^[A-Za-z]+$/;
if (b.test(letters)) {
//Your logice will be here.
} else {
alert("Please enter only alphabets");
return false;
}
row.cells[1].innerHTML = x;
row.cells[2].innerHTML = y;
row.cells[3].innerHTML = z;
row.cells[4].innerHTML = a;
row.cells[5].innerHTML = b;
}
_x000D_
<html>
<head>
</head>
<body>
<form name="myform">
<h1>
<center> Admission form </center>
</h1>
<center>
<tr>
<td>Name :</td>
<td><input type="text" name="usrname" PlaceHolder="Enter Your First Name" required></td>
</tr>
<tr>
<td> Email ID :</td>
<td><input type="text" name="usremail" PlaceHolder="Enter Your email address" pattern="[^@]+@[a-zA-Z]+\.[a-zA-Z]{2,6}" required></td>
</tr>
<tr>
<td>Age :</td>
<td><input type="number" name="usrage" PlaceHolder="Enter Your Age" required></td>
</tr>
<tr>
<td>Dept :</td>
<td><input type="text" name="usrdpt" PlaceHolder="Enter Dept"></td>
</tr>
<tr>
<td>College :</td>
<td><input type="text" name="usrclg" PlaceHolder="Enter college"></td>
</tr>
</center>
<center>
<br>
<br>
<tr>
<td>
<Button type="button" onclick="validateform()" id="Add">Add</button>
</td>
<td>
<Button type="button" onclick="onUpdatefunction()" style="display:none;" id="update">update</button>
</td>
<td><button type="reset">Reset</button></td>
</tr>
</center>
<br><br>
<center>
<table id="mytable" border="1">
<tr>
<th>SNO</th>
<th>Name</th>
<th>Email ID</th>
<th>Age</th>
<th>Dept</th>
<th>College</th>
</tr>
</center>
</table>
</form>
</body>
</html>
_x000D_
If you're attempting to do this in a .NET Standard library, here's a simple solution, with all of the risks of just returning true
in your handler. I leave safety up to you.
var handler = new HttpClientHandler();
handler.ClientCertificateOptions = ClientCertificateOption.Manual;
handler.ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
};
var client = new HttpClient(handler);
I tried with the code below and it is working. The code is self explanatory, please let me know if you have any questions.
<?php
class FlxZipArchive extends ZipArchive
{
public function addDir($location, $name)
{
$this->addEmptyDir($name);
$this->addDirDo($location, $name);
}
private function addDirDo($location, $name)
{
$name .= '/';
$location .= '/';
$dir = opendir ($location);
while ($file = readdir($dir))
{
if ($file == '.' || $file == '..') continue;
$do = (filetype( $location . $file) == 'dir') ? 'addDir' : 'addFile';
$this->$do($location . $file, $name . $file);
}
}
}
?>
<?php
$the_folder = '/path/to/folder/to/be/zipped';
$zip_file_name = '/path/to/zip/archive.zip';
$za = new FlxZipArchive;
$res = $za->open($zip_file_name, ZipArchive::CREATE);
if($res === TRUE)
{
$za->addDir($the_folder, basename($the_folder));
$za->close();
}
else{
echo 'Could not create a zip archive';
}
?>
/q isn't a valid parameter. /y: Suppresses prompting to confirm overwriting
Also ..\txt means directory txt under the parent directory, not the root directory. The root directory would be: \ And please mention the error you get
Try:
move files\*.txt \
Edit: Try:
move \files\*.txt \
Edit 2:
move C:\files\*.txt C:\txt
This should be tested in mysql, not postgresql:
SELECT table_schema, # "DB Name",
Round(Sum(data_length + index_length) / 1024 / 1024, 1) # "DB Size in MB"
FROM information_schema.tables
GROUP BY table_schema;
Well, according to me to it is O(2^n)
as in this function only recursion is taking the considerable time (divide and conquer). We see that, the above function will continue in a tree until the leaves are approaches when we reach to the level F(n-(n-1))
i.e. F(1)
. So, here when we jot down the time complexity encountered at each depth of tree, the summation series is:
1+2+4+.......(n-1)
= 1((2^n)-1)/(2-1)
=2^n -1
that is order of 2^n [ O(2^n) ]
.
I use this.
var iframe = parent.document.getElementById("theiframe");
var innerDoc = iframe.contentDocument || iframe.contentWindow.document;
var currentFrame = innerDoc.location.href;
The optimal solution is probably one that does not include an additional database read operation prior to saving the model instance, nor any further django-library. This is why laffuste's solutions is preferable. In the context of an admin site, one can simply override the save_model
-method, and invoke the form's has_changed
method there, just as in Sion's answer above. You arrive at something like this, drawing on Sion's example setting but using changed_data
to get every possible change:
class ModelAdmin(admin.ModelAdmin):
fields=['name','mode']
def save_model(self, request, obj, form, change):
form.changed_data #output could be ['name']
#do somethin the changed name value...
#call the super method
super(self,ModelAdmin).save_model(request, obj, form, change)
save_model
:https://docs.djangoproject.com/en/1.10/ref/contrib/admin/#django.contrib.admin.ModelAdmin.save_model
changed_data
-method for a Field:https://docs.djangoproject.com/en/1.10/ref/forms/api/#django.forms.Form.changed_data
The php.js project has JavaScript implementations of many of PHP's functions. base64_encode
and base64_decode
are included.
The .encode
method gets applied to a Unicode string to make a byte-string; but you're calling it on a byte-string instead... the wrong way 'round! Look at the codecs
module in the standard library and codecs.open
in particular for better general solutions for reading UTF-8 encoded text files. However, for the csv
module in particular, you need to pass in utf-8 data, and that's what you're already getting, so your code can be much simpler:
import csv
def unicode_csv_reader(utf8_data, dialect=csv.excel, **kwargs):
csv_reader = csv.reader(utf8_data, dialect=dialect, **kwargs)
for row in csv_reader:
yield [unicode(cell, 'utf-8') for cell in row]
filename = 'da.csv'
reader = unicode_csv_reader(open(filename))
for field1, field2, field3 in reader:
print field1, field2, field3
PS: if it turns out that your input data is NOT in utf-8, but e.g. in ISO-8859-1, then you do need a "transcoding" (if you're keen on using utf-8 at the csv
module level), of the form line.decode('whateverweirdcodec').encode('utf-8')
-- but probably you can just use the name of your existing encoding in the yield
line in my code above, instead of 'utf-8'
, as csv
is actually going to be just fine with ISO-8859-* encoded bytestrings.
//program to find number of repeating characters in a string
//Developed by Rahul Lakhmara
import java.util.*;
public class CountWordsInString {
public static void main(String[] args) {
String original = "I am rahul am i sunil so i can say am i";
// making String type of array
String[] originalSplit = original.split(" ");
// if word has only one occurrence
int count = 1;
// LinkedHashMap will store the word as key and number of occurrence as
// value
Map<String, Integer> wordMap = new LinkedHashMap<String, Integer>();
for (int i = 0; i < originalSplit.length - 1; i++) {
for (int j = i + 1; j < originalSplit.length; j++) {
if (originalSplit[i].equals(originalSplit[j])) {
// Increment in count, it will count how many time word
// occurred
count++;
}
}
// if word is already present so we will not add in Map
if (wordMap.containsKey(originalSplit[i])) {
count = 1;
} else {
wordMap.put(originalSplit[i], count);
count = 1;
}
}
Set word = wordMap.entrySet();
Iterator itr = word.iterator();
while (itr.hasNext()) {
Map.Entry map = (Map.Entry) itr.next();
// Printing
System.out.println(map.getKey() + " " + map.getValue());
}
}
}
How about using inputStreamReader.ready() to find out?
import java.io.InputStreamReader;
/// ...
InputStreamReader reader = new InputStreamReader(inputStream);
if (reader.ready()) {
// do something
}
// ...
Fragment
can be thought of as non-root components in a composite tree of ui elements while activities sit at the top in the forest of composites(ui trees).
A rule of thumb on when not to use Fragment
is when as a child the fragment has a conflicting attribute, e.g., it may be immersive or may be using a different style all together or has some other architectural / logical difference and doesn't fit in the existing tree homogeneously.
A rule of thumb on when to prefer Activity
over Fragment
is when the task (or set of coherent task) is fully independent and reusable and does some heavy weight lifting and should not be burdened further to conform to another parent-child composite (SRP violation, second responsibility would be to conform to the composite). For e.g., a MediaCaptureActivity
that captures audio, video, photos etc and allows for edits, noise removal, annotations on photos etc and so on. This activity/module may have child fragments that do more granular work and conform to a common display theme.
Something like:
$('#test').append('<div id="newdiv">Hello</div>').hide().show('slow');
should do it?
Edit: sorry, mistake in code and took Matt's suggestion on board too.
Here is the theme I use to accomplish this:
<style name="AppTheme" parent="@android:style/Theme.NoTitleBar">
<!-- Default Background Screen -->
<item name="android:background">@color/default_blue</item>
<item name="android:windowTranslucentStatus">true</item>
</style>
jQuery
collections have a built in iterator with .each
:
$("input[name^='card']").each(function () {
console.log($(this).val());
}
I suggest this ugly method but it works:
length = 1
lenghtafterpadding = 3
newlength = '0' * (lenghtafterpadding - len(str(length))) + str(length)
I came here to find a lighter solution than this one!
When you declare:
new Vue({
el: '#app',
data () {
return {}
}
)}
That is typically your root Vue instance that the rest of the application descends from. This hangs off the root element declared in an html document, for example:
<html>
...
<body>
<div id="app"></div>
</body>
</html>
The other syntax is declaring a component which can be registered and reused later. For example, if you create a single file component like:
// my-component.js
export default {
name: 'my-component',
data () {
return {}
}
}
You can later import this and use it like:
// another-component.js
<template>
<my-component></my-component>
</template>
<script>
import myComponent from 'my-component'
export default {
components: {
myComponent
}
data () {
return {}
}
...
}
</script>
Also, be sure to declare your data
properties as functions, otherwise they are not going to be reactive.
You could use the Add-Content cmdlet. Maybe it is a little faster than the other solutions, because I don't retrieve the content of the first file.
gc .\file2.txt| Add-Content -Path .\file1.txt
echo are you sure?
read x
if [ "$x" = "yes" ]
then
# do the dangerous stuff
fi
Like many others, I needed to convert a C# project to Java. I did not find a complete solution on the web regarding out and ref modifiers. But, I was able to take the information I found, and expand upon it to create my own classes to fulfill the requirements. I wanted to make a distinction between ref and out parameters for code clarity. With the below classes, it is possible. May this information save others time and effort.
An example is included in the code below.
//*******************************************************************************************
//XOUT CLASS
//*******************************************************************************************
public class XOUT<T>
{
public XOBJ<T> Obj = null;
public XOUT(T value)
{
Obj = new XOBJ<T>(value);
}
public XOUT()
{
Obj = new XOBJ<T>();
}
public XOUT<T> Out()
{
return(this);
}
public XREF<T> Ref()
{
return(Obj.Ref());
}
};
//*******************************************************************************************
//XREF CLASS
//*******************************************************************************************
public class XREF<T>
{
public XOBJ<T> Obj = null;
public XREF(T value)
{
Obj = new XOBJ<T>(value);
}
public XREF()
{
Obj = new XOBJ<T>();
}
public XOUT<T> Out()
{
return(Obj.Out());
}
public XREF<T> Ref()
{
return(this);
}
};
//*******************************************************************************************
//XOBJ CLASS
//*******************************************************************************************
/**
*
* @author jsimms
*/
/*
XOBJ is the base object that houses the value. XREF and XOUT are classes that
internally use XOBJ. The classes XOBJ, XREF, and XOUT have methods that allow
the object to be used as XREF or XOUT parameter; This is important, because
objects of these types are interchangeable.
See Method:
XXX.Ref()
XXX.Out()
The below example shows how to use XOBJ, XREF, and XOUT;
//
// Reference parameter example
//
void AddToTotal(int a, XREF<Integer> Total)
{
Total.Obj.Value += a;
}
//
// out parameter example
//
void Add(int a, int b, XOUT<Integer> ParmOut)
{
ParmOut.Obj.Value = a+b;
}
//
// XOBJ example
//
int XObjTest()
{
XOBJ<Integer> Total = new XOBJ<>(0);
Add(1, 2, Total.Out()); // Example of using out parameter
AddToTotal(1,Total.Ref()); // Example of using ref parameter
return(Total.Value);
}
*/
public class XOBJ<T> {
public T Value;
public XOBJ() {
}
public XOBJ(T value) {
this.Value = value;
}
//
// Method: Ref()
// Purpose: returns a Reference Parameter object using the XOBJ value
//
public XREF<T> Ref()
{
XREF<T> ref = new XREF<T>();
ref.Obj = this;
return(ref);
}
//
// Method: Out()
// Purpose: returns an Out Parameter Object using the XOBJ value
//
public XOUT<T> Out()
{
XOUT<T> out = new XOUT<T>();
out.Obj = this;
return(out);
}
//
// Method get()
// Purpose: returns the value
// Note: Because this is combersome to edit in the code,
// the Value object has been made public
//
public T get() {
return Value;
}
//
// Method get()
// Purpose: sets the value
// Note: Because this is combersome to edit in the code,
// the Value object has been made public
//
public void set(T anotherValue) {
Value = anotherValue;
}
@Override
public String toString() {
return Value.toString();
}
@Override
public boolean equals(Object obj) {
return Value.equals(obj);
}
@Override
public int hashCode() {
return Value.hashCode();
}
}
You might want a variant of exists ... perldoc -f "-f"
-X FILEHANDLE
-X EXPR
-X DIRHANDLE
-X A file test, where X is one of the letters listed below. This unary operator takes one argument,
either a filename, a filehandle, or a dirhandle, and tests the associated file to see if something is
true about it. If the argument is omitted, tests $_, except for "-t", which tests STDIN. Unless
otherwise documented, it returns 1 for true and '' for false, or the undefined value if the file
doesn’t exist. Despite the funny names, precedence is the same as any other named unary operator.
The operator may be any of:
-r File is readable by effective uid/gid.
-w File is writable by effective uid/gid.
-x File is executable by effective uid/gid.
-o File is owned by effective uid.
-R File is readable by real uid/gid.
-W File is writable by real uid/gid.
-X File is executable by real uid/gid.
-O File is owned by real uid.
-e File exists.
-z File has zero size (is empty).
-s File has nonzero size (returns size in bytes).
-f File is a plain file.
-d File is a directory.
-l File is a symbolic link.
-p File is a named pipe (FIFO), or Filehandle is a pipe.
-S File is a socket.
-b File is a block special file.
-c File is a character special file.
-t Filehandle is opened to a tty.
-u File has setuid bit set.
-g File has setgid bit set.
-k File has sticky bit set.
-T File is an ASCII text file (heuristic guess).
-B File is a "binary" file (opposite of -T).
-M Script start time minus file modification time, in days.
Given sheet 2:
ColumnA
-------
apple
orange
You can flag the rows in sheet 1 where a value exists in sheet 2:
ColumnA ColumnB
------- --------------
pear =IF(ISERROR(VLOOKUP(A1,Sheet2!A:A,1,FALSE)),"Keep","Delete")
apple =IF(ISERROR(VLOOKUP(A2,Sheet2!A:A,1,FALSE)),"Keep","Delete")
cherry =IF(ISERROR(VLOOKUP(A3,Sheet2!A:A,1,FALSE)),"Keep","Delete")
orange =IF(ISERROR(VLOOKUP(A4,Sheet2!A:A,1,FALSE)),"Keep","Delete")
plum =IF(ISERROR(VLOOKUP(A5,Sheet2!A:A,1,FALSE)),"Keep","Delete")
The resulting data looks like this:
ColumnA ColumnB
------- --------------
pear Keep
apple Delete
cherry Keep
orange Delete
plum Keep
You can then easily filter or sort sheet 1 and delete the rows flagged with 'Delete'.
Use ==
:
pip install django_modeltranslation==0.4.0-beta2
While it's probably not the correct way to do it, something that I've found to be a simple workaround is to simply use a box-shadow rather than a border... This doesn't break the grid system. For example, in your case:
HTML
<div class="container">
<div class="row" >
<div class="span12">
<div class="row">
<div class="span4">
1
</div>
<div class="span4">
2
</div>
<div class="span4">
3
</div>
</div>
</div>
</div>
</div>
CSS
.span12{
-moz-box-shadow: 0 0 2px black;
-webkit-box-shadow: 0 0 2px black;
box-shadow: 0 0 2px black;
}
I use this subtle alias:
alias vim='gnome-terminal -- vim'
-x is deprecated now. We need to use -- instead
-v
is the "inverted match" flag, so piping is a very good way:
grep "loom" ~/projects/**/trunk/src/**/*.@(h|cpp)| grep -v "gloom"
You don't need to write a program to do this in Linux. Just pipe the serial port through netcat:
netcat www.example.com port </dev/ttyS0 >/dev/ttyS0
Just replace the address and port information. Also, you may be using a different serial port (i.e. change the /dev/ttyS0
part). You can use the stty or setserial commands to change the parameters of the serial port (baud rate, parity, stop bits, etc.).
I would expect the optimiser to ensure there is no real difference outside weird edge cases.
As with anything, the only real way to tell is to measure your specific cases.
That said, I've always used COUNT(*)
.
Could there be any problem if i replace Method-1 by Method-2?
No, just use map[key] = value
. The two options are equivalent.
Regarding Dictionary<>
vs. Hashtable
: When you start Reflector, you see that the indexer setters of both classes call this.Insert(key, value, add: false);
and the add
parameter is responsible for throwing an exception, when inserting a duplicate key. So the behavior is the same for both classes.
try this :
mWebView.loadUrl(mWebView.getUrl().toString());
For the benefit of anyone searching for similar, see worksheet .UsedRange
,
e.g. ? ActiveSheet.UsedRange.Rows.Count
and loops such as
For Each loopRow in Sheets(1).UsedRange.Rows: Print loopRow.Row: Next
[Extracted from question]
If you are getting this error: "Could not load type MvcApplication", look at the Output path of your project and make sure it is set to 'bin\'. The problem is that the AspNetCompiler cannot find the files if they are not in the default location.
Another side effect of changing the output folder is that you will not be able to debug your code and it comes up with a message saying that the Assembly info cannot be found.
The R package data.table
provides both fast and memory efficient ordering of data.tables with a straightforward syntax (a part of which Matt has highlighted quite nicely in his answer). There has been quite a lot of improvements and also a new function setorder()
since then. From v1.9.5+
, setorder()
also works with data.frames.
First, we'll create a dataset big enough and benchmark the different methods mentioned from other answers and then list the features of data.table.
require(plyr)
require(doBy)
require(data.table)
require(dplyr)
require(taRifx)
set.seed(45L)
dat = data.frame(b = as.factor(sample(c("Hi", "Med", "Low"), 1e8, TRUE)),
x = sample(c("A", "D", "C"), 1e8, TRUE),
y = sample(100, 1e8, TRUE),
z = sample(5, 1e8, TRUE),
stringsAsFactors = FALSE)
The timings reported are from running system.time(...)
on these functions shown below. The timings are tabulated below (in the order of slowest to fastest).
orderBy( ~ -z + b, data = dat) ## doBy
plyr::arrange(dat, desc(z), b) ## plyr
arrange(dat, desc(z), b) ## dplyr
sort(dat, f = ~ -z + b) ## taRifx
dat[with(dat, order(-z, b)), ] ## base R
# convert to data.table, by reference
setDT(dat)
dat[order(-z, b)] ## data.table, base R like syntax
setorder(dat, -z, b) ## data.table, using setorder()
## setorder() now also works with data.frames
# R-session memory usage (BEFORE) = ~2GB (size of 'dat')
# ------------------------------------------------------------
# Package function Time (s) Peak memory Memory used
# ------------------------------------------------------------
# doBy orderBy 409.7 6.7 GB 4.7 GB
# taRifx sort 400.8 6.7 GB 4.7 GB
# plyr arrange 318.8 5.6 GB 3.6 GB
# base R order 299.0 5.6 GB 3.6 GB
# dplyr arrange 62.7 4.2 GB 2.2 GB
# ------------------------------------------------------------
# data.table order 6.2 4.2 GB 2.2 GB
# data.table setorder 4.5 2.4 GB 0.4 GB
# ------------------------------------------------------------
data.table
's DT[order(...)]
syntax was ~10x faster than the fastest of other methods (dplyr
), while consuming the same amount of memory as dplyr
.
data.table
's setorder()
was ~14x faster than the fastest of other methods (dplyr
), while taking just 0.4GB extra memory. dat
is now in the order we require (as it is updated by reference).
Speed:
data.table's ordering is extremely fast because it implements radix ordering.
The syntax DT[order(...)]
is optimised internally to use data.table's fast ordering as well. You can keep using the familiar base R syntax but speed up the process (and use less memory).
Memory:
Most of the times, we don't require the original data.frame or data.table after reordering. That is, we usually assign the result back to the same object, for example:
DF <- DF[order(...)]
The issue is that this requires at least twice (2x) the memory of the original object. To be memory efficient, data.table therefore also provides a function setorder()
.
setorder()
reorders data.tables by reference
(in-place), without making any additional copies. It only uses extra memory equal to the size of one column.
Other features:
It supports integer
, logical
, numeric
, character
and even bit64::integer64
types.
Note that
factor
,Date
,POSIXct
etc.. classes are allinteger
/numeric
types underneath with additional attributes and are therefore supported as well.
In base R, we can not use -
on a character vector to sort by that column in decreasing order. Instead we have to use -xtfrm(.)
.
However, in data.table, we can just do, for example, dat[order(-x)]
or setorder(dat, -x)
.
class DataHelper{
private static function __renameArrayKeysRecursive($map = [], &$array = [], $level = 0, &$storage = []) {
foreach ($map as $old => $new) {
$old = preg_replace('/([\.]{1}+)$/', '', trim($old));
if ($new) {
if (!is_array($new)) {
$array[$new] = $array[$old];
$storage[$level][$old] = $new;
unset($array[$old]);
} else {
if (isset($array[$old])) {
static::__renameArrayKeysRecursive($new, $array[$old], $level + 1, $storage);
} else if (isset($array[$storage[$level][$old]])) {
static::__renameArrayKeysRecursive($new, $array[$storage[$level][$old]], $level + 1, $storage);
}
}
}
}
}
/**
* Renames array keys. (add "." at the end of key in mapping array if you want rename multidimentional array key).
* @param type $map
* @param type $array
*/
public static function renameArrayKeys($map = [], &$array = [])
{
$storage = [];
static::__renameArrayKeysRecursive($map, $array, 0, $storage);
unset($storage);
}
}
Use:
DataHelper::renameArrayKeys([
'a' => 'b',
'abc.' => [
'abcd' => 'dcba'
]
], $yourArray);
I came up with a simple work around below which is easy to remember too :-)
select * from
(select cast (xmlCol as varchar(max)) texty
from myTable (NOLOCK)
) a
where texty like '%MySearchText%'
Oracle Workshop for Weblogic is supposed to have a pretty nice jsp editor but I've never used it. You needn't be using Weblogic to use it.
Reinstalling python based on instructions from here solved this problem for me: How can I install a previous version of Python 3 in macOS using homebrew?
I copied a picture (instead of text) that I had in my excel 2007 file and that solved the problem for me. The picture copied to the (then empty) clipboard. I could then copy cells normally even after clearing the clipboard of the picture. I think a graph object should also do the trick.
The first thing is to know the difference between an instance of a class, and the class itself. A class models certain properties, and the behaviour of the whole in the context of those properties. An instance will define specific values for those properties.
Anything bound to the static keyword is available in the context of the class rather than in the context of an instance of the class
As a corollary to the above
The lifetime of a static field/method is equivalent to the lifetime of your application
E.g. Say, car has the property colour, and exhibits the behaviour 'motion'. An instance of the car would be a Red Volkswagen Beetle in motion at 25kmph.
Now a static property of the car would be the number of wheels (4) on the road, and this would apply to all cars.
HTH
Sample:
Label label = new Label();
label.HorizontalContentAlignment = HorizontalAlignment.Center;
Our HTML:
<div id="addnew">
<input type="text" id="id">
<input type="text" id="content">
<input type="button" value="Add" id="submit">
</div>
<div id="check">
<input type="text" id="input">
<input type="button" value="Search" id="search">
</div>
JS (writing to the txt file):
function writeToFile(d1, d2){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 8, false, 0);
fh.WriteLine(d1 + ',' + d2);
fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
var id = document.getElementById("id").value;
var content = document.getElementById("content").value;
writeToFile(id, content);
}
checking a particular row:
function readFile(){
var fso = new ActiveXObject("Scripting.FileSystemObject");
var fh = fso.OpenTextFile("data.txt", 1, false, 0);
var lines = "";
while (!fh.AtEndOfStream) {
lines += fh.ReadLine() + "\r";
}
fh.Close();
return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
var input = document.getElementById("input").value;
if (input != "") {
var text = readFile();
var lines = text.split("\r");
lines.pop();
var result;
for (var i = 0; i < lines.length; i++) {
if (lines[i].match(new RegExp(input))) {
result = "Found: " + lines[i].split(",")[1];
}
}
if (result) { alert(result); }
else { alert(input + " not found!"); }
}
}
Put these inside a .hta
file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.
I did this to get around it and move on, in my case I'm not using an 'input' element, instead I use an image, when I tried setting the "onclick" attribute for this image I experienced the same problem, so I tried wrapping the image with an "a" element and making the reference point to the function like this.
var rowIndex = 1;
var linkDeleter = document.createElement('a');
linkDeleter.setAttribute('href', "javascript:function(" + rowIndex + ");");
var imgDeleter = document.createElement('img');
imgDeleter.setAttribute('alt', "Delete");
imgDeleter.setAttribute('src', "Imagenes/DeleteHS.png");
imgDeleter.setAttribute('border', "0");
linkDeleter.appendChild(imgDeleter);
You are probably printing from a signed char array. Either print from an unsigned char array or mask the value with 0xff: e.g. ar[i] & 0xFF. The c0 values are being sign extended because the high (sign) bit is set.
It is possible to use full C# 6.0 features in Visual Studio 2013 if you have Resharper.
You have to enable Resharper Build and voilá!
In Resharper Options -> Build - enable Resharper Build and in "Use MSBuild.exe version" choose "Latest Installed"
This way Resharper is going to build your C# 6.0 Projects and will also not underline C# 6.0 code as invalid.
I am also using this although I have Visual Studio 2015 because:
I am putting this here, as I was looking for a solution for this problem for some time now and maybe it will help someone else.
it's worked good for me
CREATE TABLE dbto.table_name like dbfrom.table_name;
insert into dbto.table_name select * from dbfrom.table_name;
Check official website https://aws.amazon.com/free/compute/lightsail-vs-ec2/
Amazon Lightsail – The Power of AWS, the Simplicity of a VPS https://aws.amazon.com/blogs/aws/amazon-lightsail-the-power-of-aws-the-simplicity-of-a-vps/
Amazon EC2 vs Amazon Lightsail (comparison on point )
Source : https://www.vpsbenchmarks.com/compare/features/ec2_vs_lightsail
If you want to rollback last migration.
php artisan migrate:rollback
If you want to rollback specific migration then go to migration table and set highest value of that record in batch. Then.
php artisan migrate:rollback
Currently i'm working on laravel 5.8 if not working any other version of laravel please inform to me.
In your question, it seems that you want to avoid rounding the numbers as well? I think .format() will round the numbers using half-up, afaik?
so if you want to round, 200.3456 should be 200.35 for a precision of 2. but in your case, if you just want the first 2 and then discard the rest?
You could multiply it by 100 and then cast to an int (or taking the floor of the number), before dividing by 100 again.
200.3456 * 100 = 20034.56;
(int) 20034.56 = 20034;
20034/100.0 = 200.34;
You might have issues with really really big numbers close to the boundary though. In which case converting to a string and substring'ing it would work just as easily.
First of all, public static
non-final
fields are evil. Spring does not allow injecting to such fields for a reason.
Your workaround is valid, you don't even need getter/setter, private
field is enough. On the other hand try this:
@Value("${my.name}")
public void setPrivateName(String privateName) {
Sample.name = privateName;
}
(works with @Autowired
/@Resource
). But to give you some constructive advice: Create a second class with private
field and getter instead of public static
field.
Or use JodaTime:
DateTime lastWeek = new DateTime().minusDays(7);
If what you're saying is that you want to get all inputs inside a form that have a value without worrying about the input type, try this:
Example: http://jsfiddle.net/nfLfa/
var $inputs = $('form').find(':checked,:selected,:text,textarea').filter(function() {
return $.trim( this.value ) != '';
});
Now you should have a set of input elements that have some value.
You can put the values in an array:
var array = $inputs.map(function(){
return this.value;
}).get();
Or you could serialize them:
var serialized = $inputs.serialize();
I know that I'm a few years late, but I came across this issue and took an unorthodox approach. I wanted to do it without making a new class, so this is what I came up with:
int x = 0;
new Thread((new Runnable() {
int x;
public void run() {
// stuff with x and whatever else you want
}
public Runnable pass(int x) {
this.x = x;
return this;
}
}).pass(x)).start();
I use .bat file with this commad to do that.
for /f %%F in ('dir /b /ad /s ^| findstr /iles "Bin"') do RMDIR /s /q "%%F"
for /f %%F in ('dir /b /ad /s ^| findstr /iles "Obj"') do RMDIR /s /q "%%F"
Why don't you go for awk:
awk '/Start pattern/,/End pattern/' filename
I f you want just the first element try this: b = (a-set()).pop()
There is no limit. It only depends on your free memory and system maximum file size. But that doesn't mean you shouldn't take precautionary measure in tackling memory usage in your database. Always create a script that can delete rows that are out of use or that will keep total no of rows within a particular figure, say a thousand.
Go to magento/var/report
and open the file with the Error log record number name i.e 673618173351
in your case. In that file you can find the complete description of the error.
For log files like system.log
and exception.log
, go to magento/var/log/
.
What is that BasePagerAdapter
? You should use one of the standard pager adapters -- either FragmentPagerAdapter
or FragmentStatePagerAdapter
, depending on whether you want Fragments that are no longer needed by the ViewPager
to either be kept around (the former) or have their state saved (the latter) and re-created if needed again.
Sample code for using ViewPager
can be found here
It is true that the management of fragments in a view pager across activity instances is a little complicated, because the FragmentManager
in the framework takes care of saving the state and restoring any active fragments that the pager has made. All this really means is that the adapter when initializing needs to make sure it re-connects with whatever restored fragments there are. You can look at the code for FragmentPagerAdapter
or FragmentStatePagerAdapter
to see how this is done.
private function downloadFile($url, $path)
{
$newfname = $path;
$file = fopen ($url, 'rb');
if ($file) {
$newf = fopen ($newfname, 'wb');
if ($newf) {
while(!feof($file)) {
fwrite($newf, fread($file, 1024 * 8), 1024 * 8);
}
}
}
if ($file) {
fclose($file);
}
if ($newf) {
fclose($newf);
}
}
In my case I forgot it was packaging conflict jar vs pom. I forgot to write
<packaging>pom</packaging>
In every child pom.xml file
That's because req
and res
are two different objects.
You need to look for the property on the same object you added it to.
use the itoa()
function included in stdlib.h
char buffer[7]; //the ASCII of the integer will be stored in this char array
itoa(-31596,buffer,10); //(integer, yourBuffer, base)
To check function or method of class is callable or not that means we can call that function.
Class A:
def __init__(self,val):
self.val = val
def bar(self):
print "bar"
obj = A()
callable(obj.bar)
True
callable(obj.__init___)
False
def foo(): return "s"
callable(foo)
True
callable(foo())
False
I was running in to the same issue, but have just managed a full uninstall by means of trusty old CMD:
D:\vs_ultimate.exe /uninstall /force
Where D: is the location of your installation media (mounted iso, etc).
You could also pass /passive (no user input required - just progress displayed) or /quiet to the above command line.
EDIT: Adding link below to MSDN article mentioning that this forcibly removes ALL installed components.
Also, to ensure link rot doesn't invalidate this, adding brief text below from original article.
Starting with Visual Studio 2013, you can forcibly remove almost all components. A few core components – like the .NET Framework and VC runtimes – are left behind because of their ubiquity, though you can remove those separately from Programs and Features if you really want.
Warning: This will remove all components regardless of whether other products require them. This may cause other products to function incorrectly or not function at all.
Good luck!
MacPorts is the way to go.
Like @user475443 pointed, MacPorts has many many more packages. With brew you'll find yourself trapped soon because the formula you need doesn't exist.
MacPorts is a native application: C + TCL. You don't need Ruby at all. To install Ruby on Mac OS X you might need MacPorts, so just go with MacPorts and you'll be happy.
MacPorts is really stable, in 8 years I never had a problem with it, and my entire Unix ecosystem relay on it.
If you are a PHP developer you can install the last version of Apache (Mac OS X uses 2.2), PHP and all the extensions you need, then upgrade all with one command. Forget to do the same with Homebrew.
MacPorts support groups.
foo@macpro:~/ port select --summary
Name Selected Options
==== ======== =======
db none db46 none
gcc none gcc42 llvm-gcc42 mp-gcc48 none
llvm none mp-llvm-3.3 none
mysql mysql56 mysql56 none
php php55 php55 php56 none
postgresql postgresql94 postgresql93 postgresql94 none
python none python24 python25-apple python26-apple python27 python27-apple none
If you have both PHP55 and PHP56 installed (with many different extensions), you can swap between them with just one command. All the relative extensions are part of the group and they will be activated within the chosen group: php55 or php56. I'm not sure Homebrew has this feature.
Rubists like to rewrite everything in Ruby, because the only thing they are at ease is Ruby itself.
Uri myUri = Uri.parse("http://www.google.com");
Here's the doc http://developer.android.com/reference/android/net/Uri.html#parse%28java.lang.String%29
you can do this---
<input type="button" onClic="changebackColor">
function changebackColor(){
document.body.style.backgroundColor = "black";
document.getElementByID("divID").style.backgroundColor = "black";
window.setTimeout("yourFunction()",10000);
}
One option is to put the subquery in a LEFT JOIN
:
select sum ( t.graduates ) - t1.summedGraduates
from table as t
left join
(
select sum ( graduates ) summedGraduates, id
from table
where group_code not in ('total', 'others' )
group by id
) t1 on t.id = t1.id
where t.group_code = 'total'
group by t1.summedGraduates
Perhaps a better option would be to use SUM
with CASE
:
select sum(case when group_code = 'total' then graduates end) -
sum(case when group_code not in ('total','others') then graduates end)
from yourtable
The omp_get_num_threads()
function returns the number of threads that are currently in the team executing the parallel region from which it is called. You are calling it outside of the parallel region, which is why it returns 1
.
define margin and padding for the element is facing the problem:
#element_id {margin: 0; padding: 0}
and see if problem exists. IE renders the page with to more unwanted inheritance. you should stop it from doing so.
This can be accomplished by Unmarshaling into a map[string]json.RawMessage
.
var objmap map[string]json.RawMessage
err := json.Unmarshal(data, &objmap)
To further parse sendMsg
, you could then do something like:
var s sendMsg
err = json.Unmarshal(objmap["sendMsg"], &s)
For say
, you can do the same thing and unmarshal into a string:
var str string
err = json.Unmarshal(objmap["say"], &str)
EDIT: Keep in mind you will also need to export the variables in your sendMsg struct to unmarshal correctly. So your struct definition would be:
type sendMsg struct {
User string
Msg string
}
From Install Curl Extension for PHP in Ubuntu:
sudo apt-get install php5-curl
After installing libcurl, you should restart the web server with one of the following commands,
sudo /etc/init.d/apache2 restart
or
sudo service apache2 restart
I couldn't find any solution to this problem, until I found out the files didn't exist! This took me a long time to figure out, because the Solution Explorer shows the files!
But when I click on Index.cshtml I get this error:
So that was the reason for this error to show. I hope this answer helps somebody.
You should install Google Drivers from: http://developer.android.com/sdk/win-usb.html#top That works for me every time
After long searching and try, nothing solved my problem except
style = "height:100%;"
on the children div
and for parent apply this
.parent {
display: flex;
flex-direction: column;
}
also, I am using bootstrap and this did not corrupt the responsive for me.
We had the same issue with our Azure DevOps repositories after our domain changed, i.e. from @xy.com to @xyz.com. To fix this issue, we generated a fresh personal access token with the following permissions:
Code: read & write Packaging: read
Then we opened the Windows Credential Manager, added a new generic windows credential with the following details:
Internet or network address: "git:{projectname}@dev.azure.com/{projectname}" - alternatively you should use your git repository name here.
User name: "Personal Access Token"
Password: {The generated Personal Access Token}
Afterwards all our git operations were working again. Hope this helps someone else!
I got the error message in the title from o.s.b.d.LoggingFailureAnalysisReporter
along with the message "APPLICATION FAILED TO START". It turned out that I hadn't added -Dspring.profiles.active=dev
to my Eclipse debug configuration so I had no active profile.
The most likely reason for the error is that the certificate authority that issued your SSL certificate is trusted on your desktop, but not on your mobile.
If you purchased the certificate from a common certification authority, it shouldn't be an issue - but if it is a less common one it is possible that your phone doesn't have it. You may need to accept it as a trusted publisher (although this is not ideal if you are pushing the site to the public as they won't be willing to do this.)
You might find looking at a list of Trusted CAs for Android helps to see if yours is there or not.
I've investigated A LOT on how to properly manage 404s in MVC (specifically MVC3), and this, IMHO is the best solution I've come up with:
In global.asax:
public class MvcApplication : HttpApplication
{
protected void Application_EndRequest()
{
if (Context.Response.StatusCode == 404)
{
Response.Clear();
var rd = new RouteData();
rd.DataTokens["area"] = "AreaName"; // In case controller is in another area
rd.Values["controller"] = "Errors";
rd.Values["action"] = "NotFound";
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
}
}
}
ErrorsController:
public sealed class ErrorsController : Controller
{
public ActionResult NotFound()
{
ActionResult result;
object model = Request.Url.PathAndQuery;
if (!Request.IsAjaxRequest())
result = View(model);
else
result = PartialView("_NotFound", model);
return result;
}
}
Edit:
If you're using IoC (e.g. AutoFac), you should create your controller using:
var rc = new RequestContext(new HttpContextWrapper(Context), rd);
var c = ControllerBuilder.Current.GetControllerFactory().CreateController(rc, "Errors");
c.Execute(rc);
Instead of
IController c = new ErrorsController();
c.Execute(new RequestContext(new HttpContextWrapper(Context), rd));
(Optional)
Explanation:
There are 6 scenarios that I can think of where an ASP.NET MVC3 apps can generate 404s.
Generated by ASP.NET:
Generated by ASP.NET MVC:
Scenario 2: URL matches a route, but specifies a controller that doesn't exist.
Scenario 3: URL matches a route, but specifies an action that doesn't exist.
Manually generated:
Scenario 4: An action returns an HttpNotFoundResult by using the method HttpNotFound().
Scenario 5: An action throws an HttpException with the status code 404.
Scenario 6: An actions manually modifies the Response.StatusCode property to 404.
Objectives
(A) Show a custom 404 error page to the user.
(B) Maintain the 404 status code on the client response (specially important for SEO).
(C) Send the response directly, without involving a 302 redirection.
Solution Attempt: Custom Errors
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Errors/NotFound"/>
</customErrors>
</system.web>
Problems with this solution:
Solution Attempt: HTTP Errors
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
Solution Attempt: HTTP Errors with Replace
<system.webServer>
<httpErrors errorMode="Custom" existingResponse="Replace">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
Solution Attempt customErrors and HTTP Errors
<system.web>
<customErrors mode="On">
<error statusCode="404" redirect="~/Errors/NotFound"/>
</customError>
</system.web>
and
<system.webServer>
<httpErrors errorMode="Custom">
<remove statusCode="404"/>
<error statusCode="404" path="App/Errors/NotFound" responseMode="ExecuteURL"/>
</httpErrors>
</system.webServer>
Problems with this solution:
People that have troubled with this before even tried to create their own libraries (see http://aboutcode.net/2011/02/26/handling-not-found-with-asp-net-mvc3.html). But the previous solution seems to cover all the scenarios without the complexity of using an external library.
img {_x000D_
width: 200px;_x000D_
}
_x000D_
<img src="https://image.ibb.co/gmmneK/children_593313_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/e0RLzK/entrepreneur_1340649_340.jpg"/>_x000D_
_x000D_
<img src="https://image.ibb.co/cks4Rz/typing_849806_340.jpg"/>
_x000D_
please see the above code.
As already written in answers you need to drop constraints (created automatically by sql) related to all columns that you are trying to delete.
Perform followings steps to do the needful.
exec sp_helpconstraint '<your table name>'
alter table <your_table_name>
drop constraint <constraint_name_that_you_copied_in_1>
(It'll be something like this only or similar format)Alter table <YourTableName> Drop column column1, column2
etcNo. Servlets are not Thread safe
This is allows accessing more than one threads at a time
if u want to make it Servlet as Thread safe ., U can go for
Implement SingleThreadInterface(i)
which is a blank Interface there is no
methods
or we can go for synchronize methods
we can make whole service method as synchronized by using synchronized
keyword in front of method
Example::
public Synchronized class service(ServletRequest request,ServletResponse response)throws ServletException,IOException
or we can the put block of the code in the Synchronized block
Example::
Synchronized(Object)
{
----Instructions-----
}
I feel that Synchronized block is better than making the whole method
Synchronized
$(this).attr('data-original-title', 'click here to publish')
.tooltip('fixTitle')
.tooltip('show');
Useful if you need to change a tooltip's text after it has been initialized with attr 'data-original-title'.
when using javascript objects, you can also just use "dot notation" to add an item, (which JSLint prefers)
var myArray = { name : "john" };
//will initiate a key-value array with one item "name" and the value "john"
myArray.lastName = "smith";
//will add a key named lastName with the value "smith"
//Object {name: "john", lastName: "smith"}
Here is a screenshot from testing in the Chrome console
I had a simmilar problem, but in my case I was put a row in the leading of the Listview, and it was consumming all the space, of course. I just had to take the Row out of the leading, and it was solved. I would recomend to check if the problem is a widget larger than its containner can have.
Use File
's getParentFile()
method and String.lastIndexOf()
to retrieve just the immediate parent directory.
Mark's comment is a better solution thanlastIndexOf()
:
file.getParentFile().getName();
These solutions only works if the file has a parent file (e.g., created via one of the file constructors taking a parent File
). When getParentFile()
is null you'll need to resort to using lastIndexOf
, or use something like Apache Commons' FileNameUtils.getFullPath()
:
FilenameUtils.getFullPathNoEndSeparator(file.getAbsolutePath());
=> C:/aaa/bbb/ccc/ddd
There are several variants to retain/drop the prefix and trailing separator. You can either use the same FilenameUtils
class to grab the name from the result, use lastIndexOf
, etc.
My issue was similar to Q---ten's, but in my case it was that I had forgotten to provide the self argument to a class function:
class A:
def fn(a, b, c=True):
pass
Should become
class A:
def fn(self, a, b, c=True):
pass
This faulty implementation is hard to see when calling the class method as:
a_obj = A()
a.fn(a_val, b_val, c=False)
Which will yield a TypeError: got multiple values for argument
. Hopefully, the rest of the answers here are clear enough for anyone to be able to quickly understand and fix the error. If not, hope this answer helps you!
Create a new datafile by running the following command:
alter tablespace TABLE_SPACE_NAME add datafile 'D:\oracle\Oradata\TEMP04.dbf'
size 2000M autoextend on;
Try adding "bDestroy": true to the options object literal, e.g.
$('#dataTable').dataTable({
...
....
"bDestroy": true
});
Source: iodocs.com
or Remove the first:
$(document).ready(function() {
$('#example').dataTable();
} );
In your case is the best option vjk.
I was having trouble with Dan's proposed solution, but this worked for me:
import json
import csv
f = open('test.json')
data = json.load(f)
f.close()
f=csv.writer(open('test.csv','wb+'))
for item in data:
f.writerow([item['pk'], item['model']] + item['fields'].values())
Where "test.json" contained the following:
[
{"pk": 22, "model": "auth.permission", "fields":
{"codename": "add_logentry", "name": "Can add log entry", "content_type": 8 } },
{"pk": 23, "model": "auth.permission", "fields":
{"codename": "change_logentry", "name": "Can change log entry", "content_type": 8 } }, {"pk": 24, "model": "auth.permission", "fields":
{"codename": "delete_logentry", "name": "Can delete log entry", "content_type": 8 } }
]
use the jquery UI draggable, much simpler http://jqueryui.com/draggable/
If anyone is still looking for an easy way to decompile an APK (with resource decompiling), have a look at the tools I have created: https://github.com/dirkvranckaert/AndroidDecompiler
Just checkout the project locally and run the script as documented and you'll get all the resources and sources decompiled.
If both data frames have the same column names then you should add one data frame inside ggplot()
call and also name x and y values inside aes()
of ggplot()
call. Then add first geom_line()
for the first line and add second geom_line()
call with data=df2
(where df2 is your second data frame). If you need to have lines in different colors then add color=
and name for eahc line inside aes()
of each geom_line()
.
df1<-data.frame(x=1:10,y=rnorm(10))
df2<-data.frame(x=1:10,y=rnorm(10))
ggplot(df1,aes(x,y))+geom_line(aes(color="First line"))+
geom_line(data=df2,aes(color="Second line"))+
labs(color="Legend text")
Form elements can be accessed via the form's DOM element by name, not by "id" value. Give your form elements names if you want to access them like that, or else access them directly by "id" value:
document.getElementById("color").disabled = true;
edit — oh also, as pointed out by others, it's just "text", not "TextBox", for the "type" attribute.
You might want to invest a little time in reading some front-end development tutorials.
If your requirements are to have no duplicates, you should be using a HashSet.
HashSet.Add will return false when the item already exists (if that even matters to you).
You can use the constructor that @pstrjds links to below (or here) to define the equality operator or you'll need to implement the equality methods in RemoteDevice
(GetHashCode
& Equals
).
Try This.....
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Timer1.Start()
End Sub
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
Label12.Text = TimeOfDay.ToString("h:mm:ss tt")
End Sub
it clears stdin
buffer before reading. From the man page:
For output streams, fflush() forces a write of all user-space buffered data for the given output or update stream via the stream's underlying write function. For input streams, fflush() discards any buffered data that has been fetched from the underlying file, but has not been consumed by the application.
Note: This is Linux-specific, using fflush()
on input streams is undefined by the standard, however, most implementations behave the same as in Linux.
With VSCode you can find the merge conflicts easily with the following UI.
(if you do not have the topbar, set "editor.codeLens": true
in User Preferences)
It indicates the current change that you have and incoming change from the server. This makes it easy to resolve the conflicts - just press the buttons above <<<< HEAD
.
If you have multiple changes and want to apply all of them at once - open command palette (View -> Command Palette) and start typing merge - multiple options will appear including Merge Conflict: Accept Incoming
, etc.
Never ever mix more languages.
<script type="text/javascript">
var data = @Json.Encode(Model); // !!!! export data !!!!
for(var prop in data){
console.log( prop + " "+ data[prop]);
}
In case of problem you can also try
@Html.Raw(Json.Encode(Model));
Python3.6.8
In [1]: a = 'which option is the fastest'
In [2]: %%timeit
...: ''.join(a).upper()
762 ns ± 11.4 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [3]: %%timeit
...: map(lambda x:x.upper(), a)
209 ns ± 5.73 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [4]: %%timeit
...: map(str.upper, [i for i in a])
1.18 µs ± 11.3 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
In [5]: %%timeit
...: [i.upper() for i in a]
3.2 µs ± 64.1 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
If you need a string or list as the output and not an iterator (this is for Python3), compare ''.join(string).upper()
option to this:
In [10]: %%timeit
...: [i for i in map(lambda x:x.upper(), a)]
4.32 µs ± 112 ns per loop (mean ± std. dev. of 7 runs, 100000 loops each)
The list()
function [docs] will convert a string into a list of single-character strings.
>>> list('hello')
['h', 'e', 'l', 'l', 'o']
Even without converting them to lists, strings already behave like lists in several ways. For example, you can access individual characters (as single-character strings) using brackets:
>>> s = "hello"
>>> s[1]
'e'
>>> s[4]
'o'
You can also loop over the characters in the string as you can loop over the elements of a list:
>>> for c in 'hello':
... print c + c,
...
hh ee ll ll oo
I tried to update a field with
$table->update(['field' => 'val']);
But it wasn't working, i had to modify my table Model to authorize this field to be edited : add 'field' in the array "protected $fillable"
Hope it will help someone :)
I've created a couple of map tutorials that will cover what you need
Animating the map describes howto create polylines based on a set of LatLngs. Using Google APIs on your map : Directions and Places describes howto use the Directions API and animate a marker along the path.
Take a look at these 2 tutorials and the Github project containing the sample app.
It contains some tips to make your code cleaner and more efficient:
PHP Port
Found PenguinTD's solution helpful so I ported it to PHP. Help yourself!
/**
* =====================================
* Remap Range
* =====================================
* - Convert one range to another. (including value)
*
* @param int $intValue The value in the old range you wish to convert
* @param int $oMin The minimum of the old range
* @param int $oMax The maximum of the old range
* @param int $nMin The minimum of the new range
* @param int $nMax The maximum of the new range
*
* @return float $fResult The old value converted to the new range
*/
function remapRange($intValue, $oMin, $oMax, $nMin, $nMax) {
// Range check
if ($oMin == $oMax) {
echo 'Warning: Zero input range';
return false;
}
if ($nMin == $nMax) {
echo 'Warning: Zero output range';
return false;
}
// Check reversed input range
$bReverseInput = false;
$intOldMin = min($oMin, $oMax);
$intOldMax = max($oMin, $oMax);
if ($intOldMin != $oMin) {
$bReverseInput = true;
}
// Check reversed output range
$bReverseOutput = false;
$intNewMin = min($nMin, $nMax);
$intNewMax = max($nMin, $nMax);
if ($intNewMin != $nMin) {
$bReverseOutput = true;
}
$fRatio = ($intValue - $intOldMin) * ($intNewMax - $intNewMin) / ($intOldMax - $intOldMin);
if ($bReverseInput) {
$fRatio = ($intOldMax - $intValue) * ($intNewMax - $intNewMin) / ($intOldMax - $intOldMin);
}
$fResult = $fRatio + $intNewMin;
if ($bReverseOutput) {
$fResult = $intNewMax - $fRatio;
}
return $fResult;
}
A static block executes once in the life cycle of any program, another property of static block is that it executes before the main method.
Calling p.plot
after setting the limits is why it is rescaling. You are correct in that turning autoscaling off will get the right answer, but so will calling xlim()
or ylim()
after your plot
command.
I use this quite a lot to invert the x axis, I work in astronomy and we use a magnitude system which is backwards (ie. brighter stars have a smaller magnitude) so I usually swap the limits with
lims = xlim()
xlim([lims[1], lims[0]])
This technique is usually used for multiple axis in a figure. In this context it is often required to have a colorbar that corresponds in size with the result from imshow. This can be achieved easily with the axes grid tool kit:
import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.axes_grid1 import make_axes_locatable
data = np.arange(100, 0, -1).reshape(10, 10)
fig, ax = plt.subplots()
divider = make_axes_locatable(ax)
cax = divider.append_axes('right', size='5%', pad=0.05)
im = ax.imshow(data, cmap='bone')
fig.colorbar(im, cax=cax, orientation='vertical')
plt.show()
If I get 'someObject', say via
someObject <- myMagicFunction(...)
then I usually proceed by
class(someObject)
str(someObject)
which can be followed by head(), summary(), print(), ... depending on the class you have.
Maybe use atribute disabled:
<input disabled="disabled" id="fieldName" name="fieldName" type="text" class="text_box" />
Or just use label tag: ;)
<label>
A couple of things might affect the results you're seeing:
clock_t
as a floating-point type, I don't think it is.1^4
) to do something else than compute the bitwise XOR of 1 and 4., i.e. it's 5.You're not specifying how fast your machine is, but it's not unreasonable for this to run very quickly on modern hardware, no.
If you have it, try adding a call to sleep()
between the start/stop snapshots. Note that sleep()
is POSIX though, not standard C.
Checking for null
within if
statement prevents Laravel from returning 404 immediately after the query is over.
if ( User::find( $userId ) === null ) {
return "user does not exist";
}
else {
$user = User::find( $userId );
return $user;
}
It seems like it runs double query if the user is found, but I can't seem to find any other reliable solution.
There is also a combination, you can use a return value with a recordset:
--Stored Procedure--
CREATE PROCEDURE [TestProc]
AS
BEGIN
DECLARE @Temp TABLE
(
[Name] VARCHAR(50)
)
INSERT INTO @Temp VALUES ('Mark')
INSERT INTO @Temp VALUES ('John')
INSERT INTO @Temp VALUES ('Jane')
INSERT INTO @Temp VALUES ('Mary')
-- Get recordset
SELECT * FROM @Temp
DECLARE @ReturnValue INT
SELECT @ReturnValue = COUNT([Name]) FROM @Temp
-- Return count
RETURN @ReturnValue
END
--Calling Code--
DECLARE @SelectedValue int
EXEC @SelectedValue = [TestProc]
SELECT @SelectedValue
--Results--
It is because you use a relative path.
The easy way to fix this is by using the __DIR__
magic constant, like:
require_once(__DIR__."/initcontrols/config.php");
From the PHP doc:
The directory of the file. If used inside an include, the directory of the included file is returned
Instance variable is the variable declared inside a class, but outside a method: something like:
class IronMan {
/** These are all instance variables **/
public String realName;
public String[] superPowers;
public int age;
/** Getters and setters here **/
}
Now this IronMan Class can be instantiated in another class to use these variables. Something like:
class Avengers {
public static void main(String[] a) {
IronMan ironman = new IronMan();
ironman.realName = "Tony Stark";
// or
ironman.setAge(30);
}
}
This is how we use the instance variables. Shameless plug: This example was pulled from this free e-book here here.
For Typescript users willing to set and get typed properties:
/**
* Silly wrapper to be able to type the storage keys
*/
export class TypedStorage<T> {
public removeItem(key: keyof T): void {
localStorage.removeItem(key);
}
public getItem<K extends keyof T>(key: K): T[K] | null {
const data: string | null = localStorage.getItem(key);
return JSON.parse(data);
}
public setItem<K extends keyof T>(key: K, value: T[K]): void {
const data: string = JSON.stringify(value);
localStorage.setItem(key, data);
}
}
// write an interface for the storage
interface MyStore {
age: number,
name: string,
address: {city:string}
}
const storage: TypedStorage<MyStore> = new TypedStorage<MyStore>();
storage.setItem("wrong key", ""); // error unknown key
storage.setItem("age", "hello"); // error, age should be number
storage.setItem("address", {city:"Here"}); // ok
const address: {city:string} = storage.getItem("address");
add a symbolic link
sudo ln -s /usr/lib/jvm/java-7-oracle /usr/lib/jvm/default-java
Without java-8, you'll be able to do this in one line Commons collections, and the Closure class
List<Item> list;
@SuppressWarnings("unchecked")
Map<Key, Item> map = new HashMap<Key, Item>>(){{
CollectionUtils.forAllDo(list, new Closure() {
@Override
public void execute(Object input) {
Item item = (Item) input;
put(i.getKey(), item);
}
});
}};
It looks like in the ECMAScript 6 proposal there are the Array
methods find()
and findIndex()
. MDN also offers polyfills which you can include to get the functionality of these across all browsers.
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].find(isPrime) ); // undefined, not found
console.log( [4, 5, 8, 12].find(isPrime) ); // 5
function isPrime(element, index, array) {
var start = 2;
while (start <= Math.sqrt(element)) {
if (element % start++ < 1) return false;
}
return (element > 1);
}
console.log( [4, 6, 8, 12].findIndex(isPrime) ); // -1, not found
console.log( [4, 6, 7, 12].findIndex(isPrime) ); // 2
If you do not want to use other library, here is a simple function to convert InputStream
to OutputStream
.
public static void copyStream(InputStream in, OutputStream out) throws IOException {
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
}
Now you can easily write an Inputstream
into file by using FileOutputStream
-
FileOutputStream out = new FileOutputStream(outFile);
copyStream (inputStream, out);
out.close();
Document
Document style messages can be validated against predefined schema.
In document style, SOAP message is sent as a single document.
Example of schema:
<types>
<xsd:schema> <xsd:import namespace="http://example.com/"
schemaLocation="http://localhost:8080/ws/hello?xsd=1"/>
</xsd:schema>
</types>
Example of document style soap body message
<message name="getHelloWorldAsString">
<part name="parameters" element="tns:getHelloWorldAsString"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="parameters"> element="tns:getHelloWorldAsStringResponse"/>
</message>
Document style message is loosely coupled.
RPC RPC style messages use method name and parameters to generate XML structure. messages are difficult to be validated against schema. In RPC style, SOAP message is sent as many elements.
<message name="getHelloWorldAsString">
<part name="arg0"> type="xsd:string"/>
</message>
<message name="getHelloWorldAsStringResponse">
<part name="return"
> type="xsd:string"/>
</message>
Here each parameters are discretely specified, RPC style message is tightly coupled, is typically static, requiring changes to the client when the method signature changes The rpc style is limited to very simple XSD types such as String and Integer, and the resulting WSDL will not even have a types section to define and constrain the parameters
Literal By default style. Data is serialized according to a schema, data type not specified in messages but a reference to schema(namespace) is used to build soap messages.
<soap:body>
<myMethod>
<x>5</x>
<y>5.0</y>
</myMethod>
</soap:body>
Encoded Datatype specified in each parameter
<soap:body>
<myMethod>
<x xsi:type="xsd:int">5</x>
<y xsi:type="xsd:float">5.0</y>
</myMethod>
</soap:body>
Schema free
I would sugest to init the Class from RSC:
import Foundation
import UIKit
// Don't forget the delegate!
class ViewController: UIViewController, UITextFieldDelegate {
required init(coder aDecoder: NSCoder) {
fatalError("init(coder:) has not been implemented")
}
@IBOutlet var myTextField : UITextField?
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
self.myTextField.delegate = self;
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
func textFieldShouldReturn(textField: UITextField!) -> Bool {
self.view.endEditing(true);
return false;
}
}
Use regular expression:
String s="your1string2contain3with4number";
int i=Integer.parseInt(s.replaceAll("[\\D]", ""))
output: i=1234;
If you need first number combination then you should try below code:
String s="abc123xyz456";
int i=((Number)NumberFormat.getInstance().parse(s)).intValue()
output: i=123;
"USB Web debugging" is one option
"printing it on the screen" another.
But I prefer remote debugging through 'adobe edge inspect' formally known as adobe shadow. It uses weinre internally (=WEb INspect REmote)
You just install it + a small plugin in the browser (Chrome) and a free app you can download in the play-store. Then you have all the tools like the Chrome Development tools.
It has also support for iOS and Kindle Fire
Update
Like Chris noticed, you have to pay a subscription to use edge inspect. A cheap alternative is to use weinre directly, it's the base of edge inspect. Here's an article about how to set it up.
<graphics.h>
is very old library. It's better to use something that is new
Here are some 2D libraries (platform independent) for C/C++
Also there is a free very powerful 3D open source graphics library for C++
Use this method to set margin in dp
private void setMargins (View view, int left, int top, int right, int bottom) {
if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();
final float scale = getBaseContext().getResources().getDisplayMetrics().density;
// convert the DP into pixel
int l = (int)(left * scale + 0.5f);
int r = (int)(right * scale + 0.5f);
int t = (int)(top * scale + 0.5f);
int b = (int)(bottom * scale + 0.5f);
p.setMargins(l, t, r, b);
view.requestLayout();
}
}
call the method :
setMargins(linearLayout,5,0,5,0);
In Visual Studio project properties there is an option saying "generate serialization assembly". Try turning it on for a project that generates [Containing Assembly of MyType].
With Java 8's lambdas, a convenient way is to use
org.mockito.invocation.InvocationOnMock
when(client.deleteByQuery(anyString(), anyString())).then(invocationOnMock -> {
assertEquals("myCollection", invocationOnMock.getArgument(0));
assertThat(invocationOnMock.getArgument(1), Matchers.startsWith("id:"));
}
You can use eval() for this purpose
>>> url = "'http address'"
>>> eval(url)
'http address'
while eval() poses risk , i think in this context it is safe.
Try
Html
<div class="responsive-container">
<div class="img-container">
<IMG HERE>
</div>
</div>
CSS
.img-container {
position: absolute;
top: 0;
left: 0;
height:0;
padding-bottom:100%;
}
.img-container img {
width:100%;
}
I think the difference between the two boils down to access. Environment variables are accessible by any process and Java system properties are only accessible by the process they are added to.
Also as Bohemian stated, env variables are set in the OS (however they 'can' be set through Java) and system properties are passed as command line options or set via setProperty()
.
Please use DateTimeFormatter ISO_DATE_TIME = DateTimeFormatter.ISO_DATE_TIME;
instead of DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss")
or any pattern
This fixed my problem Below
java.time.format.DateTimeParseException: Text '2019-12-18T19:00:00.000Z' could not be parsed at index 10
On Linux you can use clock_gettime()
:
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &start); // get initial time-stamp
// ... do stuff ... //
clock_gettime(CLOCK_PROCESS_CPUTIME_ID, &end); // get final time-stamp
double t_ns = (double)(end.tv_sec - start.tv_sec) * 1.0e9 +
(double)(end.tv_nsec - start.tv_nsec);
// subtract time-stamps and
// multiply to get elapsed
// time in ns
You have a couple of options:
I just set outline transparent.
input[type=text] {
outline: rgba(0, 0, 0, 0);
border-radius: 10px;
}
input[type=text]:focus {
border-color: #0079ff;
}
Simplest way,
If your query is Model.Objects.get():
get() will return single instance so you can direct use __dict__
from your instance
model_dict = Model.Objects.get().__dict__
for filter()/all():
all()/filter() will return list of instances so you can use values()
to get list of objects.
model_values = Model.Objects.all().values()
Earlier it used to be android:capitalize="words"
, which is now deprecated. The recommended alternative is to use android:inputType="textCapWords"
Please note that this will only work if your device keyboard Auto Capitalize Setting enabled.
To do this programatically, use the following method:
setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_WORDS);
For example,
package main
import (
"flag"
"fmt"
"os"
"strconv"
)
func main() {
flag.Parse()
s := flag.Arg(0)
// string to int
i, err := strconv.Atoi(s)
if err != nil {
// handle error
fmt.Println(err)
os.Exit(2)
}
fmt.Println(s, i)
}
The & and | are usually bitwise operations.
Where as && and || are usually logical operations.
For comparison purposes, it's perfectly fine provided that everything returns either a 1 or a 0. Otherwise, it can return false positives. You should avoid this though to prevent hard to read bugs.
I had this issue also and I simply found out that if you simply remove the "#" the issue goes off. Like this :
<a href="" class="disabled" ng-click="doSomething(object)">Do something</a>
Without using inline CSS you could set the text size of all your buttons using:
input[type="submit"], input[type="button"] {
font-size: 14px;
}
It is a sort of format specifier for formatting numeric results. There are additional specifiers on the link.
What N
does is that it separates numbers into thousand decimal places according to your CultureInfo and represents only 2 decimal digits in floating part as is N2
by rounding right-most digit if necessary.
N0
does not represent any decimal place but rounding is applied to it.
Let's exemplify.
using System;
using System.Globalization;
namespace ConsoleApp1
{
class Program
{
static void Main(string[] args)
{
double x = 567892.98789;
CultureInfo someCulture = new CultureInfo("da-DK", false);
// 10 means left-padded = right-alignment
Console.WriteLine(String.Format(someCulture, "{0:N} denmark", x));
Console.WriteLine("{0,10:N} us", x);
// watch out rounding 567,893
Console.WriteLine(String.Format(someCulture, "{0,10:N0}", x));
Console.WriteLine("{0,10:N0}", x);
Console.WriteLine(String.Format(someCulture, "{0,10:N5}", x));
Console.WriteLine("{0,10:N5}", x);
Console.ReadKey();
}
}
}
It yields,
567.892,99 denmark
567,892.99 us
567.893
567,893
567.892,98789
567,892.98789
You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.
<script type="text/javascript">
function readXml(xmlFile){
var xmlDoc;
if(typeof window.DOMParser != "undefined") {
xmlhttp=new XMLHttpRequest();
xmlhttp.open("GET",xmlFile,false);
if (xmlhttp.overrideMimeType){
xmlhttp.overrideMimeType('text/xml');
}
xmlhttp.send();
xmlDoc=xmlhttp.responseXML;
}
else{
xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
xmlDoc.async="false";
xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>
I am on mingw bash, so I have created ~.profile file with following: alias atom='~/AppData/Local/atom/bin/atom'
It's been solved.
The losses only save to the History over the epochs. I was running iterations instead of using the Keras built in epochs option.
so instead of doing 4 iterations I now have
model.fit(......, nb_epoch = 4)
Now it returns the loss for each epoch run:
print(hist.history)
{'loss': [1.4358016599558268, 1.399221191623641, 1.381293383180471, h1.3758836857303727]}
Visual studio is the most up to date and probably "best" free ide. Dev C++ is a little dated, and mingw doesn't compile most of boost, (except regex). Most of the other compilers are dated and fading, like mars and borland. But you can use whatever you like!
Here's one way:
create table #work
(
something decimal(8,3) not null
)
insert #work values ( 0 )
insert #work values ( 12345.6789 )
insert #work values ( 3.1415926 )
insert #work values ( 45 )
insert #work values ( 9876.123456 )
insert #work values ( -12.5678 )
select convert(varchar,convert(decimal(8,2),something))
from #work
if you want it right-aligned, something like this should do you:
select str(something,8,2) from #work
After Uri.TryCreate
you can check Uri.Scheme
to see if it HTTP(s).
You can use System.Diagnostics.Process.Start
.
Or use the WinApi directly with something like the following, which will launch explorer.exe. You can use the fourth parameter to ShellExecute to give it a starting directory.
public partial class Window1 : Window
{
public Window1()
{
ShellExecute(IntPtr.Zero, "open", "explorer.exe", "", "", ShowCommands.SW_NORMAL);
InitializeComponent();
}
public enum ShowCommands : int
{
SW_HIDE = 0,
SW_SHOWNORMAL = 1,
SW_NORMAL = 1,
SW_SHOWMINIMIZED = 2,
SW_SHOWMAXIMIZED = 3,
SW_MAXIMIZE = 3,
SW_SHOWNOACTIVATE = 4,
SW_SHOW = 5,
SW_MINIMIZE = 6,
SW_SHOWMINNOACTIVE = 7,
SW_SHOWNA = 8,
SW_RESTORE = 9,
SW_SHOWDEFAULT = 10,
SW_FORCEMINIMIZE = 11,
SW_MAX = 11
}
[DllImport("shell32.dll")]
static extern IntPtr ShellExecute(
IntPtr hwnd,
string lpOperation,
string lpFile,
string lpParameters,
string lpDirectory,
ShowCommands nShowCmd);
}
The declarations come from the pinvoke.net website.
I found a more generic solution with the most angular-native solution I can think. Basically you can pass your own comparator to the default filterFilter
function. Here's plunker as well.
Default values to an interface are not possible because interfaces only exists at compile time.
You could use a factory method for this which returns an object which implements the XI interface.
class AnotherType {}
interface IX {
a: string,
b: any,
c: AnotherType | null
}
function makeIX (): IX {
return {
a: 'abc',
b: null,
c: null
}
}
const x = makeIX();
x.a = 'xyz';
x.b = 123;
x.c = new AnotherType();
The only thing I changed with regard to your example is made the property c both AnotherType | null
. Which will be necessary to not have any compiler errors (This error was also present in your example were you initialized null to property c).
BernardSaucier has already given you an answer. My post is not an answer but an explanation as to why you shouldn't be using UsedRange
.
UsedRange
is highly unreliable as shown HERE
To find the last column which has data, use .Find
and then subtract from it.
With Sheets("Sheet1")
If Application.WorksheetFunction.CountA(.Cells) <> 0 Then
lastCol = .Cells.Find(What:="*", _
After:=.Range("A1"), _
Lookat:=xlPart, _
LookIn:=xlFormulas, _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious, _
MatchCase:=False).Column
Else
lastCol = 1
End If
End With
If lastCol > 8 Then
'Debug.Print ActiveSheet.UsedRange.Columns.Count - 8
'The above becomes
Debug.Print lastCol - 8
End If
Hope it will help u:
//create a file to write bitmap data
File f = new File(context.getCacheDir(), filename);
f.createNewFile();
//Convert bitmap to byte array
Bitmap bitmap = your bitmap;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
//write the bytes in file
FileOutputStream fos = new FileOutputStream(f);
fos.write(bitmapdata);
fos.flush();
fos.close();
In my case, it was because my form was sending to a route with a different middleware. So it blocked from sending information to this specific route.
I just noticed, you are using sync fs methods, that might block you application, here is a promise-based async way using async and q, you can execute it with START=/myfolder FILTER=".jpg" node myfile.js, assuming you put the following code in a file called myfile.js:
Q = require("q")
async = require("async")
path = require("path")
fs = require("fs")
function findFiles(startPath, filter, files){
var deferred;
deferred = Q.defer(); //main deferred
//read directory
Q.nfcall(fs.readdir, startPath).then(function(list) {
var ideferred = Q.defer(); //inner deferred for resolve of async each
//async crawling through dir
async.each(list, function(item, done) {
//stat current item in dirlist
return Q.nfcall(fs.stat, path.join(startPath, item))
.then(function(stat) {
//check if item is a directory
if (stat.isDirectory()) {
//recursive!! find files in subdirectory
return findFiles(path.join(startPath, item), filter, files)
.catch(function(error){
console.log("could not read path: " + error.toString());
})
.finally(function() {
//resolve async job after promise of subprocess of finding files has been resolved
return done();
});
//check if item is a file, that matches the filter and add it to files array
} else if (item.indexOf(filter) >= 0) {
files.push(path.join(startPath, item));
return done();
//file is no directory and does not match the filefilter -> don't do anything
} else {
return done();
}
})
.catch(function(error){
ideferred.reject("Could not stat: " + error.toString());
});
}, function() {
return ideferred.resolve(); //async each has finished, so resolve inner deferred
});
return ideferred.promise;
}).then(function() {
//here you could do anything with the files of this recursion step (otherwise you would only need ONE deferred)
return deferred.resolve(files); //resolve main deferred
}).catch(function(error) {
deferred.reject("Could not read dir: " + error.toString());
return
});
return deferred.promise;
}
findFiles(process.env.START, process.env.FILTER, [])
.then(function(files){
console.log(files);
})
.catch(function(error){
console.log("Problem finding files: " + error);
})
For SSIS you could go with:
RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE())
Expression builder screen:
Be aware, that \W
leaves the underscore. A short equivalent for [^a-zA-Z0-9]
would be [\W_]
text.replace(/[\W_]+/g," ");
\W
is the negation of shorthand \w
for [A-Za-z0-9_]
word characters (including the underscore)
$text='<span style="font-weight: bold;">Foo</span>';
$text=preg_replace( '/<span style="font-weight: bold;">(.*?)<\/span>/', '<strong>$1</strong>',$text);
Note: only work for your example.
While calling/invoking your programme you can use this command : java [-options] className [args...]
in place of [-options] provide more memory e.g -Xmx1024m or more. but this is just a workaround, u have to change ur parsing mechanism.
Floating point calculations are not exact - there is often round-off errors, and errors due to representation. (For example, 0.1 cannot be exactly represented in binary floating point.)
Because of this, directly comparing two floating point values for equality is usually not a good idea, because they can be different by a small amount, depending upon how they were computed.
The "delta", as it's called in the JUnit javadocs, describes the amount of difference you can tolerate in the values for them to be still considered equal. The size of this value is entirely dependent upon the values you're comparing. When comparing doubles, I typically use the expected value divided by 10^6.
As an alternative, if you put a space between the date and time, DateTime.Parse
will recognize the format for you. That's about as simple as you can get it. (If ParseExact
was still not being recognized)
Insert your fetched values into an array instead of echoing.
Use file_put_contents()
and insert json_encode($rows)
into that file, if $rows
is your data.
Make your Foreign key attributes nullable. That will work.
I was facing the same problem, resolved it by using the following command.
sudo xcode-select -s /Library/Developer/CommandLineTools
After running the above command then xcode-select -p command showed the following.
/Library/Developer/CommandLineTools
For a null-safe copy of an array, you can also use an optional with the Object.clone()
method provided in this answer.
int[] arrayToCopy = {1, 2, 3};
int[] copiedArray = Optional.ofNullable(arrayToCopy).map(int[]::clone).orElse(null);
You need to set JAVA_HOME to your jdk7 home directory, for example on Microsoft Windows:
or on OS X:
If you are already running as an adminstrator, make sure the user you are using has the proper server roles.
There are two problems in your code.
dbConfig.php
<?php
$conn=mysqli_connect("localhost","root","password","testDB");
if(!$conn)
{
die("Connection failed: " . mysqli_connect_error());
}
?>
index.php
include('dbConfig.php');
<!Doctype html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<meta name="description" content="$1">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="style.css">
<title>test</title>
</head>
<body>
<?php
if(isset($_POST['save']))
{
$sql = "INSERT INTO users (username, password, email)
VALUES ('".$_POST["username"]."','".$_POST["password"]."','".$_POST["email"]."')";
$result = mysqli_query($conn,$sql);
}
?>
<form action="index.php" method="post">
<label id="first"> First name:</label><br/>
<input type="text" name="username"><br/>
<label id="first">Password</label><br/>
<input type="password" name="password"><br/>
<label id="first">Email</label><br/>
<input type="text" name="email"><br/>
<button type="submit" name="save">save</button>
</form>
</body>
</html>
You simply compare your object to null
using the ==
(or !=
) operator. E.g.:
public static double calculateInventoryTotal(Book[] books) {
// First null check - the entire array
if (books == null) {
return 0;
}
double total = 0;
for (int i = 0; i < books.length; i++) {
// second null check - each individual element
if (books[i] != null) {
total += books[i].getPrice();
}
}
return total;
}
Try the JavaScript in operator.
if ('key' in myObj)
And the inverse.
if (!('key' in myObj))
Be careful! The in
operator matches all object keys, including those in the object's prototype chain.
Use myObj.hasOwnProperty('key')
to check an object's own keys and will only return true
if key
is available on myObj
directly:
myObj.hasOwnProperty('key')
Unless you have a specific reason to use the in
operator, using myObj.hasOwnProperty('key')
produces the result most code is looking for.