I had a similar issue with mongoose :
fields:
[ '[object Object]',
'[object Object]',
'[object Object]',
'[object Object]' ] }
In fact, I was using "type" as a property name in my schema :
fields: [
{
name: String,
type: {
type: String
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
To avoid that behavior, you have to change the parameter to :
fields: [
{
name: String,
type: {
type: { type: String }
},
registrationEnabled: Boolean,
checkinEnabled: Boolean
}
]
When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.
The new default toArray
method in Collection
interface allows the elements of the collection to be transferred to a newly created array of the desired runtime type. It takes IntFunction<T[]> generator
as argument and can be used as:
String[] array = set.toArray(String[]::new);
There is already a similar method Collection.toArray(T[])
and this addition means we no longer be able to pass null
as argument because in that case reference to the method would be ambiguous. But it is still okay since both methods throw a NPE anyways.
In Java 8 we can use streams API:
String[] array = set.stream().toArray(String[]::new);
We can also make use of the overloaded version of toArray() which takes IntFunction<A[]> generator
as:
String[] array = set.stream().toArray(n -> new String[n]);
The purpose of the generator function here is to take an integer (size of desired array) and produce an array of desired size. I personally prefer the former approach using method reference than the later one using lambda expression.
They serve the actual image inside CSS so there will be less HTTP requests per page.
As others have mentioned, and counter to what the method name would imply, writelines
does not add line separators. This is a textbook case for a generator. Here is a contrived example:
def item_generator(things):
for item in things:
yield item
yield '\n'
def write_things_to_file(things):
with open('path_to_file.txt', 'wb') as f:
f.writelines(item_generator(things))
Benefits: adds newlines explicitly without modifying the input or output values or doing any messy string concatenation. And, critically, does not create any new data structures in memory. IO (writing to a file) is when that kind of thing tends to actually matter. Hope this helps someone!
This works fine. just insert your jquery code in document.ready function.
$(document).ready(function(e) {
// your code here
});
example:
$(document).ready(function(e) {
$('[id^=\"btnRight\"]').click(function (e) {
$(this).prev('select').find('option:selected').remove().appendTo('#isselect_code');
});
$('[id^=\"btnLeft\"]').click(function (e) {
$(this).next('select').find('option:selected').remove().appendTo('#canselect_code');
});
});
<div>
<select id='canselect_code' name='canselect_code' multiple class='fl'>
<option value='1'>toto</option>
<option value='2'>titi</option>
</select>
<input type='button' id='btnRight_code' value=' > ' />
<br>
<input type='button' id='btnLeft_code' value=' < ' />
<select id='isselect_code' name='isselect_code' multiple class='fr'>
<option value='3'>tata</option>
<option value='4'>tutu</option>
</select>
</div>
mhata dzenyu mese. its actually
var selectedGroups = new Array();
$(".user_group[checked]").each(function() {
selectedGroups.push($(this).val());
});
After reading everyone's comments (thank you for your interest), I found that the "best" way (least amount of code, best performing) to do this was to simply sort the Array, and then grab the first value in the Array:
var myArray:Array /* of Number */ = [2,3,3,4,2,2,5,6,7,2];
myArray.sort(Array.NUMERIC);
var minValue:int = myArray[0];
This also works for an Array of Objects - you simply use the Array.sortOn() function and specify a property:
// Sample data
var myArray:Array /* of XML */ =
[
<item level="2" name="a" />
<item level="3" name="b" />
<item level="3" name="c" />
<item level="2" name="d" />
<item level="5" name="e" />
]
// Perform a descending sort on the specified attribute in Array to get the maximum value
myArray.sortOn("@level", Array.DESCENDING | Array.NUMERIC);
var lowestLevel:int = myArray[0].@level;
I hope this helps someone else someday!
One needs to install magrittr
as follows
install.packages("magrittr")
Then, in one's script, don't forget to add on top
library(magrittr)
For the meaning of the operator %>%
you might want to consider this question: What does %>% function mean in R?
Note that the same operator would also work with the library dplyr
, as it imports from magrittr
.
dplyr
used to have a similar operator (%.%
), which is now deprecated. Here we can read about the differences between %.%
(deprecated operator from the library dplyr
) and %>%
(operator from magrittr
, that is also available in dplyr
)
Create a global variable in and apply the value
<script>
var isPostBack = <%=Convert.ToString(Page.IsPostBack).ToLower()%>;
</script>
Then you can reference it from elsewhere
Best solution is to use the extension we created at CodePath called SmartFragmentStatePagerAdapter. Following that guide, this makes retrieving fragments and the currently selected fragment from a ViewPager significantly easier. It also does a better job of managing the memory of the fragments embedded within the adapter.
The most important thing to know is that ES6 modules are, indeed, an official standard, while CommonJS (Node.js) modules are not.
In 2019, ES6 modules are supported by 84% of browsers. While Node.js puts them behind an --experimental-modules flag, there is also a convenient node package called esm, which makes the integration smooth.
Another issue you're likely to run into between these module systems is code location. Node.js assumes source is kept in a node_modules
directory, while most ES6 modules are deployed in a flat directory structure. These are not easy to reconcile, but it can be done by hacking your package.json
file with pre and post installation scripts. Here is an example isomorphic module and an article explaining how it works.
You don't need function overloading, as you have the *args and **kwargs arguments.
The fact is that function overloading is based on the idea that passing different types you will execute different code. If you have a dynamically typed language like Python, you should not distinguish by type, but you should deal with interfaces and their compliance with the code you write.
For example, if you have code that can handle either an integer, or a list of integers, you can try iterating on it and if you are not able to, then you assume it's an integer and go forward. Of course it could be a float, but as far as the behavior is concerned, if a float and an int appear to be the same, then they can be interchanged.
The simple tilde syntax works only for removing quotation marks around the command line parameters being passed into the batch files
SET xyz=%~1
Above batch file code will set xyz to whatever value is being passed as first paramter stripping away the leading and trailing quotations (if present).
But, This simple tilde syntax will not work for other variables that were not passed in as parameters
For all other variable, you need to use expanded substitution syntax that requires you to specify leading and lagging characters to be removed. Effectively we are instructing to remove strip away the first and the last character without looking at what it actually is.
@SET SomeFileName="Some Quoted file name"
@echo %SomeFileName% %SomeFileName:~1,-1%
If we wanted to check what the first and last character was actually quotation before removing it, we will need some extra code as follows
@SET VAR="Some Very Long Quoted String"
If aa%VAR:~0,1%%VAR:~-1%aa == aa""aa SET UNQUOTEDVAR=%VAR:~1,-1%
Try using a normal Windows shell such as CMD.
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
Try this, It worked for me
SELECT * FROM (
SELECT
[Code],
[Name],
[CategoryCode],
[CreatedDate],
[ModifiedDate],
[CreatedBy],
[ModifiedBy],
[IsActive],
ROW_NUMBER() OVER(PARTITION BY [Code],[Name],[CategoryCode] ORDER BY ID DESC) rownumber
FROM MasterTable
) a
WHERE rownumber = 1
In the first case, the data are passed to the script via GET, in the second via POST.
http://docs.jquery.com/Ajax/load#urldatacallback
I don't think there are limits to the data size, but the completition of the remote call will of course take longer with great amount of data.
Simply floating both elements left achieves the same result.
div {
background:yellow;
vertical-align:middle;
margin:10px;
}
a {
background-color:#FFF;
width:20px;
height:20px;
display:inline-block;
border:solid black 1px;
float:left;
}
span {
background:red;
display:inline-block;
float:left;
}
If you, like me, would rather use some library code where they probably have thought of all special cases, such as what happens if you pass in null or dots in the path but not in the filename, you can use the following:
import org.apache.commons.io.FilenameUtils;
String fileNameWithOutExt = FilenameUtils.removeExtension(fileNameWithExt);
sesssionStorage.setObj(1,{date:Date.now(),action:'save firstObject'});
sesssionStorage.setObj(2,{date:Date.now(),action:'save 2nd object'});
//Query first object
sesssionStorage.getObj(1)
//Retrieve date created of 2nd object
new Date(sesssionStorage.getObj(1).date)
Storage.prototype.setObj = function(key, obj) {
return this.setItem(key, JSON.stringify(obj))
};
Storage.prototype.getObj = function(key) {
return JSON.parse(this.getItem(key))
};
RuleBasedNumberFormat
in ICU libraryI appreciated the link to the ICU project's library from @Pierre-Olivier Dybman (http://www.icu-project.org/apiref/icu4j/com/ibm/icu/text/RuleBasedNumberFormat.html), however still had to figure out how to use it, so an example of the RuleBasedNumberFormat
usage is below.
It will only format single number rather than the whole date, so you will need to build a combined string if looking for a date in format: Monday 3rd February, for example.
The below code sets up the RuleBasedNumberFormat
as an Ordinal format for a given Locale, creates a java.time ZonedDateTime
, and then formats the number with its ordinal into a string.
RuleBasedNumberFormat numOrdinalFormat = new RuleBasedNumberFormat(Locale.UK,
RuleBasedNumberFormat.ORDINAL);
ZonedDateTime zdt = ZonedDateTime.now(ZoneId.of("Pacific/Auckland"));
String dayNumAndOrdinal = numOrdinalFormat.format(zdt.toLocalDate().getDayOfMonth());
Example output:
3rd
Or
4th
etc.
You Don't need to close the wrapped reader/writer.
If you've taken a look at the docs (Reader.close()
,Writer.close()
), You'll see that in Reader.close()
it says:
Closes the stream and releases any system resources associated with it.
Which just says that it "releases any system resources associated with it". Even though it doesn't confirm.. it gives you a nudge to start looking deeper. and if you go to Writer.close()
it only states that it closes itself.
In such cases, we refer to OpenJDK to take a look at the source code.
At BufferedWriter Line 265 you'll see out.close()
. So it's not closing itself.. It's something else. If you search the class for occurences of "out
" you'll notice that in the constructor at Line 87 that out
is the writer the class wraps where it calls another constructor and then assigning out
parameter to it's own out
variable..
So.. What about others? You can see similar code at BufferedReader Line 514, BufferedInputStream Line 468 and InputStreamReader Line 199. Others i don't know but this should be enough to assume that they do.
I have the script all.p
set ...
...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file
Here the two last rows are literal, not heuristic. Then i run
$ gnuplot -p all.p
Change *.dat
to the file type you have, or add file types.
Next step: Add to ~/.bashrc this line
alias p='gnuplot -p ~/./all.p'
and put your file all.p
int your home directory and voila. You can plot all files in any directory by typing p and enter.
EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i)
.
A solution with service
and awk
that takes in a comma-delimited list of service names.
First it's probably a good bet you'll need root privileges to do what you want. If you don't need to check then you can remove that part.
#!/usr/bin/env bash
# First parameter is a comma-delimited string of service names i.e. service1,service2,service3
SERVICES=$1
ALL_SERVICES_STARTED=true
if [ $EUID -ne 0 ]; then
if [ "$(id -u)" != "0" ]; then
echo "root privileges are required" 1>&2
exit 1
fi
exit 1
fi
for service in ${SERVICES//,/ }
do
STATUS=$(service ${service} status | awk '{print $2}')
if [ "${STATUS}" != "started" ]; then
echo "${service} not started"
ALL_SERVICES_STARTED=false
fi
done
if ${ALL_SERVICES_STARTED} ; then
echo "All services started"
exit 0
else
echo "Check Failed"
exit 1
fi
Another example:
double d = 0;
for (int i = 1; i <= 10; i++) {
d += 0.1;
}
System.out.println(d); // prints 0.9999999999999999 not 1.0
Use BigDecimal instead.
EDIT:
Also, just to point out this isn't a 'Java' rounding issue. Other languages exhibit similar (though not necessarily consistent) behaviour. Java at least guarantees consistent behaviour in this regard.
You can also do something like this
class Hello {_x000D_
constructor(){_x000D_
}_x000D_
}_x000D_
_x000D_
function isClass (func) {_x000D_
return typeof func === 'function' && /^class\s/.test(Function.prototype.toString.call(func))_x000D_
}_x000D_
_x000D_
console.log(isClass(Hello))
_x000D_
This will tell you if the input is class or not
smalldatetime
has range up to June 6, 2079 so you can use
ORDER BY ISNULL(Next_Contact_Date, '2079-06-05T23:59:00')
If no legitimate records will have that date.
If this is not an assumption you fancy relying on a more robust option is sorting on two columns.
ORDER BY CASE WHEN Next_Contact_Date IS NULL THEN 1 ELSE 0 END, Next_Contact_Date
Both of the above suggestions are not able to use an index to avoid a sort however and give similar looking plans.
One other possibility if such an index exists is
SELECT 1 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NOT NULL
UNION ALL
SELECT 2 AS Grp, Next_Contact_Date
FROM T
WHERE Next_Contact_Date IS NULL
ORDER BY Grp, Next_Contact_Date
Does this work? Untested but should get the point across.
UPDATE FUNCTIONS
SET Func_TaxRef =
(
SELECT Min(TAX.Tax_Code) AS MinOfTax_Code
FROM TAX, FUNCTIONS F1
WHERE F1.Func_Pure <= [Tax_ToPrice]
AND F1.Func_Year=[Tax_Year]
AND F1.Func_ID = FUNCTIONS.Func_ID
GROUP BY F1.Func_ID;
)
Basically for each row in FUNCTIONS, the subquery determines the minimum current tax code and sets FUNCTIONS.Func_TaxRef to that value. This is assuming that FUNCTIONS.Func_ID is a Primary or Unique key.
This is a working example of making ZIPs in PHP:
$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name, ZipArchive::CREATE);
foreach ($files as $file) {
echo $path = "uploadpdf/".$file;
if(file_exists($path)){
$zip->addFromString(basename($path), file_get_contents($path));---This is main function
}
else{
echo"file does not exist";
}
}
$zip->close();
You cannot open new fragments. Fragments need to be always hosted by an activity. If the fragment is in the same activity (eg tabs) then the back key navigation is going to be tricky I am assuming that you want to open a new screen with that fragment.
So you would simply create a new activity and put the new fragment in there. That activity would then react to the intent either explicitly via the activity class or implicitly via intent filter
s.
What I found works great, with plain javascript (ie: no JQuery library required), is to change the innerHTML of the <select>
tag to the desired single remaining value.
Before:
<select name='day' id='day'>
<option>SUN</option>
<option>MON</option>
<option>TUE</option>
<option>WED</option>
<option>THU</option>
<option>FRI</option>
<option>SAT</option>
</select>
Sample Javascript:
document.getElementById('day').innerHTML = '<option>FRI</option>';
After:
<select name='day' id='day'>
<option>FRI</option>
</select>
This way, no visiual effect change, and this will POST/GET within the <FORM>
.
If you are using chart.js in an Angular project with Typescript, the you can try the following;
Import the library:
import { Chart } from 'chart.js';
In your Component Class declare the variable and define a method:
chart: Chart;
drawGraph(): void {
if (this.chart) {
this.chart.destroy();
}
this.chart = new Chart('myChart', {
.........
});
}
In HTML Template:
<canvas id="myChart"></canvas>
set formatoptions-=t
Keeps the visual textwidth but doesn't add new line in insert mode.
Look at the css Float property. http://w3schools.com/css/pr_class_float.asp
It works with block elements like div. Alternatively, what are you trying to display, tables aren't evil if you're really trying to show a table of some information.
Here's what I get.
I'm using Visual Studio Code and its Terminal to execute the 'npm' commands.
Visual Studio Code (not as administrator)
PS g:\labs\myproject> npm install bootstrap@3
Results in scandir and/or permission errors.
Visual Studio Code (as Administrator)
Run this command after I've run something like 'ng serve'
PS g:\labs\myproject> npm install bootstrap@3
Results in scandir and/or permission errors.
Visual Studio Code (as Administrator - closing and opening the IDE)
If I have already executed other commands that would impact node modules I decided to try closing Visual Studio Code first, opening it up as Administrator then running the command:
PS g:\labs\myproject> npm install bootstrap@3
Result I get then is: + [email protected]
added 115 packages and updated 1 package in 24.685s
This is not a permanent solution since I don't want to continue closing down VS Code every time I want to execute an npm command, but it did resolve the issue to a point.
AWK printf-based solution that avoids % problem, and is unique in that it returns nothing (no return character) if there are less than 4 columns to print:
awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
Testing:
$ x='1 2 3 %s 4 5 6'
$ echo "$x" | awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
%s 4 5 6
$ x='1 2 3'
$ echo "$x" | awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
$ x='1 2 3 '
$ echo "$x" | awk 'NF > 3 { for(i=4; i<NF; i++) printf("%s ", $(i)); print $(i) }'
$
groupId and Mojo name change Since version 2.0-beta-1 tomcat mojos has been renamed to tomcat6 and tomcat7 with the same goals.
You must configure your pom to use this new groupId:
<pluginManagement>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat6-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
</plugin>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.3-SNAPSHOT</version>
</plugin>
</plugins>
</pluginManagement>
Or add the groupId in your settings.xml
.... org.apache.tomcat.maven ....
I had the same issue but the problem was that zoom was not defined within the options object given to Google Maps.
Well, its not technically managing conflicts with submodules (ie: keep this but not that), but I found a way to continue working...and all I had to do was pay attention to my git status
output and reset the submodules:
git reset HEAD subby
git commit
That would reset the submodule to the pre-pull commit. Which in this case is exactly what I wanted. And in other cases where I need the changes applied to the submodule, I'll handle those with the standard submodule workflows (checkout master, pull down the desired tag, etc).
Thanks. Helped me a lot. Converted to Swift 3 and worked
To save: let data = UIImagePNGRepresentation(image)
To load: let image = UIImage(data: data)
LocalDate.parse( "2013-09-18" )
… and …
myLocalDate.toString() // Example: 2013-09-18
The Question and other Answers are out-of-date. The troublesome old legacy date-time classes are now supplanted by the java.time classes.
Your input string happens to comply with standard ISO 8601 format, YYYY-MM-DD. The java.time classes use ISO 8601 formats by default when parsing and generating string representations of date-time values. So no need to specify a formatting pattern.
LocalDate
The LocalDate
class represents a date-only value without time-of-day and without time zone.
LocalDate ld = LocalDate.parse( "2013-09-18" );
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
I just imported ClarityModule
and it solved all the problems. Give it a try!
import { ClarityModule } from 'clarity-angular';
Also, include the module in the imports.
imports: [ ClarityModule ],
The uname command (http://developer.apple.com/documentation/Darwin/Reference/ManPages/man1/uname.1.html) with no parameters should tell you the operating system name. I'd use that, then make conditionals based on the return value.
Example
UNAME := $(shell uname)
ifeq ($(UNAME), Linux)
# do something Linux-y
endif
ifeq ($(UNAME), Solaris)
# do something Solaris-y
endif
If it is in inline context, in HTML try this:
onclick="functionCall();event.stopPropagation();
Your use-case isn't clear. However, if you are certain that you need this to be based on the DOM, and not model-data, then this is a way for one directive to have a reference to all elements with another directive specified on them.
The way is that the child directive can require
the parent directive. The parent directive can expose a method that allows direct directive to register their element with the parent directive. Through this, the parent directive can access the child element(s). So if you have a template like:
<div parent-directive>
<div child-directive></div>
<div child-directive></div>
</div>
Then the directives can be coded like:
app.directive('parentDirective', function($window) {
return {
controller: function($scope) {
var registeredElements = [];
this.registerElement = function(childElement) {
registeredElements.push(childElement);
}
}
};
});
app.directive('childDirective', function() {
return {
require: '^parentDirective',
template: '<span>Child directive</span>',
link: function link(scope, iElement, iAttrs, parentController) {
parentController.registerElement(iElement);
}
};
});
You can see this in action at http://plnkr.co/edit/7zUgNp2MV3wMyAUYxlkz?p=preview
Actually I found this more helpful for functions that return IAsyncAction.
var task = asyncFunction();
while (task.Status == AsyncStatus.Completed) ;
Nothing can be more simple than this
#include <stdio.h>
int main()
{
int i;
for( i=0 ; i<=255 ; i++ ) /*ASCII values ranges from 0-255*/
{
printf("ASCII value of character %c = %d\n", i, i);
}
return 0;
}
I've been stumped by this one before only to realize I added a data-only @interface and forgot to add the empty @implementation block.
I researched the same thing several months ago looking at dozens of the most popular Android devices. I found that every Android device had one of the following aspect ratios (from most square to most rectangular):
And if you consider portrait devices separate from landscape devices you'll also find the inverse of those ratios (3:4, 2:3, 5:8, 3:5, and 9:16)
I used this code,
<div style="visibility:hidden">
<audio autoplay loop>
<source src="Aakaasam-Yemaaya Chesave.mp3">
</audio>
</div>
It is working well but i want stop and pause button. So, we can stop if we don't want to listen.
Try this CSS:
body {
margin: 0;
padding: 0;
}
.logo {
float: left;
}
/* ~~ Top Navigation Bar ~~ */
#navigation-container {
width: 1200px;
margin: 0 auto;
height: 70px;
}
.navigation-bar {
background-color: #352d2f;
height: 70px;
width: 100%;
}
#navigation-container img {
float: left;
}
#navigation-container ul {
padding: 0px;
margin: 0px;
text-align: center;
display:inline-block;
}
#navigation-container li {
list-style-type: none;
padding: 0px;
height: 24px;
margin-top: 4px;
margin-bottom: 4px;
display: inline;
}
#navigation-container li a {
color: white;
font-size: 16px;
font-family: "Trebuchet MS", Arial, Helvetica, sans-serif;
text-decoration: none;
line-height: 70px;
padding: 5px 15px;
opacity: 0.7;
}
#menu {
float: right;
}
Try using this:
If you specify
ON DUPLICATE KEY UPDATE
, and a row is inserted that would cause a duplicate value in aUNIQUE index or
PRIMARY KEY, MySQL performs an [
UPDATE`](http://dev.mysql.com/doc/refman/5.7/en/update.html) of the old row...The
ON DUPLICATE KEY UPDATE
clause can contain multiple column assignments, separated by commas.With
ON DUPLICATE KEY UPDATE
, the affected-rows value per row is 1 if the row is inserted as a new row, 2 if an existing row is updated, and 0 if an existing row is set to its current values. If you specify theCLIENT_FOUND_ROWS
flag tomysql_real_connect()
when connecting to mysqld, the affected-rows value is 1 (not 0) if an existing row is set to its current values...
Use a packet analyzer to intercept the packets to/from somewhere.com
. Studying those packets should tell you what is going on.
Time-outs or connections refused could mean that the remote host is too busy.
that is the right behavior.
if you set @item1
to a value the below expression will be true
IF (@item1 IS NOT NULL) OR (LEN(@item1) > 0)
Anyway in SQL Server there is not a such function but you can create your own:
CREATE FUNCTION dbo.IsNullOrEmpty(@x varchar(max)) returns bit as
BEGIN
IF @SomeVarcharParm IS NOT NULL AND LEN(@SomeVarcharParm) > 0
RETURN 0
ELSE
RETURN 1
END
getting following error
It happens: Error:
ngModel cannot be used to register form controls with a parent formGroup directive. Try using
formGroup's partner directive "formControlName" instead. Example:
_x000D_
I would recommend you to give a look to this library:
I really like it, it supports a variety of storage backends (from cookies to HTML5 storage, Gears, Flash, and more...), its usage is really transparent, you don't have to know or care which backend is used the library will choose the right storage backend depending on the browser capabilities.
Xamarin equivalent of ErlVolton's answer:
editText.SetFilters(editText.GetFilters().Append(new InputFilterAllCaps()).ToArray());
Although I've used Eclipse for years, this "answer" is only conjecture (which I'm going to try tonight). If it gets down-voted out of existence, then obviously I'm wrong.
Oracle relies on CMake to generate a Visual Studio "Solution" for their MySQL Connector C source code. Within the Solution are "Projects" that can be compiled individually or collectively (by the Solution). Each Project has its own makefile, compiling its portion of the Solution with settings that are different than the other Projects.
Similarly, I'm hoping an Eclipse Workspace can hold my related makefile Projects (Eclipse), with a master Project whose dependencies compile the various unique-makefile Projects as pre-requesites to building its "Solution". (My folder structure would be as @Rafael describes).
So I'm hoping a good way to use Workspaces is to emulate Visual Studio's ability to combine dissimilar Projects into a Solution.
You can use the below query to identify the values. But please keep in mind that this will not give you the results from encrypted stored procedure.
SELECT DISTINCT OBJECT_NAME(comments.id) OBJECT_NAME
,objects.type_desc
FROM syscomments comments
,sys.objects objects
WHERE comments.id = objects.object_id
AND TEXT LIKE '%CreatedDate%'
ORDER BY 1
For the records: the official documentation, as for Spring Boot v1.2.0.RELEASE and Spring v4.1.3.RELEASE:
If the only change you need to make to logging is to set the levels of various loggers then you can do that in application.properties using the "logging.level" prefix, e.g.
logging.level.org.springframework.web: DEBUG
logging.level.org.hibernate: ERROR
You can also set the location of a file to log to (in addition to the console) using "logging.file".
To configure the more fine-grained settings of a logging system you need to use the native configuration format supported by the LoggingSystem in question. By default Spring Boot picks up the native configuration from its default location for the system (e.g. classpath:logback.xml for Logback), but you can set the location of the config file using the "logging.config" property.
Since you're only dealing with a 3x3 matrix of possible locations, it'd be pretty easy to just write a search through all possibilities without taxing you computing power. For each open space, compute through all the possible outcomes after that marking that space (recursively, I'd say), then use the move with the most possibilities of winning.
Optimizing this would be a waste of effort, really. Though some easy ones might be:
Thank you first
Use overflow:auto
it works for me.
horizontal scroll bar disappears.
I had a situation where this helped: (PHP 5.4.16 on Windows)
curl_setopt($ch, CURLOPT_SSLVERSION, 3);
If you need access to the resources of a library project (as you do with ABS) ensure that you add the library project/module as a "Module Dependency" instead of a "Library".
np.append needs the array as the first argument and the list you want to append as the second:
mean_data = np.append(mean_data, [ur, ua, np.mean(data[samepoints,-1])])
You can indicate the new process should be started with elevated permissions by setting the Verb property of your startInfo object to 'runas', as follows:
startInfo.Verb = "runas";
This will cause Windows to behave as if the process has been started from Explorer with the "Run as Administrator" menu command.
This does mean the UAC prompt will come up and will need to be acknowledged by the user: if this is undesirable (for example because it would happen in the middle of a lengthy process), you'll need to run your entire host process with elevated permissions by Create and Embed an Application Manifest (UAC) to require the 'highestAvailable' execution level: this will cause the UAC prompt to appear as soon as your app is started, and cause all child processes to run with elevated permissions without additional prompting.
Edit: I see you just edited your question to state that "runas" didn't work for you. That's really strange, as it should (and does for me in several production apps). Requiring the parent process to run with elevated rights by embedding the manifest should definitely work, though.
There is no such limit on the string length. To be certain, I just tested to create a string containing 60 megabyte.
The problem is likely that you are sending the data in a GET request, so it's sent in the URL. Different browsers have different limits for the URL, where IE has the lowest limist of about 2 kB. To be safe, you should never send more data than about a kilobyte in a GET request.
To send that much data, you have to send it in a POST request instead. The browser has no hard limit on the size of a post, but the server has a limit on how large a request can be. IIS for example has a default limit of 4 MB, but it's possible to adjust the limit if you would ever need to send more data than that.
Also, you shouldn't use += to concatenate long strings. For each iteration there is more and more data to move, so it gets slower and slower the more items you have. Put the strings in an array and concatenate all the items at once:
var items = $.map(keys, function(item, i) {
var value = $("#value" + (i+1)).val().replace(/"/g, "\\\"");
return
'{"Key":' + '"' + Encoder.htmlEncode($(this).html()) + '"' + ",'+
'" + '"Value"' + ':' + '"' + Encoder.htmlEncode(value) + '"}';
});
var jsonObj =
'{"code":"' + code + '",'+
'"defaultfile":"' + defaultfile + '",'+
'"filename":"' + currentFile + '",'+
'"lstResDef":[' + items.join(',') + ']}';
In my case the solution was quite simple. I added this header and the browsers opened the file in every test. header('Content-Disposition: attachment; filename="filename.pdf"');
I had the same error here MacOSX 10.6.8 - it seems ruby checks to see if any directory (including the parents) in the path are world writable. In my case there wasn't a /usr/local/bin present as nothing had created it.
so I had to do
sudo chmod 775 /usr/local
to get rid of the warning.
A question here is does any non root:wheel process in MacOS need to create anything in /usr/local ?
InetAddress class can be used to store IP addresses in IPv4 as well as IPv6 formats. You can store the IP address to the object using either InetAddress.getByName()
or InetAddress.getByAddress()
methods.
In the following code snippet, I am using InetAddress.getByName()
method to store IPv4 and IPv6 addresses.
InetAddress IPv4 = InetAddress.getByName("127.0.0.1");
InetAddress IPv6 = InetAddress.getByName("2001:db8:3333:4444:5555:6666:1.2.3.4");
You can also use InetAddress.getByAddress()
to create object by providing the byte array.
InetAddress addr = InetAddress.getByAddress(new byte[]{127, 0, 0, 1});
Furthermore, you can use InetAddress.getLoopbackAddress()
to get the local address and InetAddress.getLocalHost()
to get the address registered with the machine name.
InetAddress loopback = InetAddress.getLoopbackAddress(); // output: localhost/127.0.0.1
InetAddress local = InetAddress.getLocalHost(); // output: <machine-name>/<ip address on network>
Note- make sure to surround your code by try/catch because InetAddress
methods return java.net.UnknownHostException
Using regular expressions to check for nested patterns is very easy.
'/(\((?>[^()]+|(?1))*\))/'
If you do a straight git pull
then you will either be 'fast-forwarded' or merge an unknown number of commits from the remote repository. This happens as one action though, so the last commit that you were at immediately before the pull will be the last entry in the reflog and can be accessed as HEAD@{1}
. This means that you can do:
git diff HEAD@{1}
However, I would strongly recommend that if this is something you find yourself doing a lot then you should consider just doing a git fetch
and examining the fetched branch before manually merging or rebasing onto it. E.g. if you're on master and were going to pull in origin/master:
git fetch
git log HEAD..origin/master
# looks good, lets merge
git merge origin/master
If using JavaScript is an option and you want to avoid nesting tables, include jQuery and try the following method.
First, you'll have to give each row a unique id like so:
<table>
<tr id="idrow1"><td> ADD AS MANY COLUMNS AS YOU LIKE </td><td><button onclick="submitRowAsForm('idrow1')">SUBMIT ROW1</button></td></tr>
<tr id="idrow2"><td> PUT INPUT FIELDS IN THE COLUMNS </td><td><button onclick="submitRowAsForm('idrow2')">SUBMIT ROW2</button></td></tr>
<tr id="idrow3"><td>ADD MORE THAN ONE INPUT PER COLUMN</td><td><button onclick="submitRowAsForm('idrow3')">SUBMIT ROW3</button></td></tr>
</table>
Then, include the following function in your JavaScript for your page.
<script>
function submitRowAsForm(idRow) {
form = document.createElement("form"); // CREATE A NEW FORM TO DUMP ELEMENTS INTO FOR SUBMISSION
form.method = "post"; // CHOOSE FORM SUBMISSION METHOD, "GET" OR "POST"
form.action = ""; // TELL THE FORM WHAT PAGE TO SUBMIT TO
$("#"+idRow+" td").children().each(function() { // GRAB ALL CHILD ELEMENTS OF <TD>'S IN THE ROW IDENTIFIED BY idRow, CLONE THEM, AND DUMP THEM IN OUR FORM
if(this.type.substring(0,6) == "select") { // JQUERY DOESN'T CLONE <SELECT> ELEMENTS PROPERLY, SO HANDLE THAT
input = document.createElement("input"); // CREATE AN ELEMENT TO COPY VALUES TO
input.type = "hidden";
input.name = this.name; // GIVE ELEMENT SAME NAME AS THE <SELECT>
input.value = this.value; // ASSIGN THE VALUE FROM THE <SELECT>
form.appendChild(input);
} else { // IF IT'S NOT A SELECT ELEMENT, JUST CLONE IT.
$(this).clone().appendTo(form);
}
});
form.submit(); // NOW SUBMIT THE FORM THAT WE'VE JUST CREATED AND POPULATED
}
</script>
So what have we done here? We've given each row a unique id and included an element in the row that can trigger the submission of that row's unique identifier. When the submission element is activated, a new form is dynamically created and set up. Then using jQuery, we clone all of the elements contained in <td>
's of the row that we were passed and append the clones to our dynamically created form. Finally, we submit said form.
Try this:
git commit --amend
Then copy and paste the Change-Id: I55862204ef71f69bc88c79fe2259f7cb8365699a
at the end of the file.
Save it and push it again!
<select class='form-control'>
<option *ngFor="let option of options"
[selected]="option === nrSelect"
[value]="option">
{{ option }}
</option>
</select>
nrSelect = 47;
options = [41, 42, 47, 48];
There is a better solution than the accepted answer, specifically using data-* attributes. Setting the id to 1 will cause you issues if any other element on the page has id=1. Instead, you can do:
<button class="btn btn-primary" data-toggle="modal" data-target="#yourModalID" data-yourparameter="whateverYouWant">Load</button>
<script>
$('#yourModalID').on('show.bs.modal', function(e) {
var yourparameter = e.relatedTarget.dataset.yourparameter;
// Do some stuff w/ it.
});
</script>
Remember to check firewall settings as well. after checking and double-checking my pg_hba.conf
and postgres.conf
files I finally found out that my firewall was overriding everything and therefore blocking connections
Use like below:
yourFunc(input: any):Observable<string> {
var requestHeader = { headers: new HttpHeaders({ 'Content-Type': 'text/plain', 'No-Auth': 'False' })};
const headers = new HttpHeaders().set('Content-Type', 'text/plain; charset=utf-8');
return this.http.post<string>(this.yourBaseApi+ '/do-api', input, { headers, responseType: 'text' as 'json' });
}
Simple example: Form with textbox and Search button.
If you write "name" into the textbox
and submit form, it will brings you patients with "name" in table.
View:
@using (Ajax.BeginForm("GetPatients", "Patient", new AjaxOptions {//GetPatients is name of method in PatientController
InsertionMode = InsertionMode.Replace, //target element(#patientList) will be replaced
UpdateTargetId = "patientList",
LoadingElementId = "loader" // div with .gif loader - that is shown when data are loading
}))
{
string patient_Name = "";
@Html.EditorFor(x=>patient_Name) //text box with name and id, that it will pass to controller
<input type="submit" value="Search" />
}
@* ... *@
<div id="loader" class=" aletr" style="display:none">
Loading...<img src="~/Images/ajax-loader.gif" />
</div>
@Html.Partial("_patientList") @* this is view with patient table. Same view you will return from controller *@
_patientList.cshtml:
@model IEnumerable<YourApp.Models.Patient>
<table id="patientList" >
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Number)
</th>
</tr>
@foreach (var patient in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => patient.Name)
</td>
<td>
@Html.DisplayFor(modelItem => patient.Number)
</td>
</tr>
}
</table>
Patient.cs
public class Patient
{
public string Name { get; set; }
public int Number{ get; set; }
}
PatientController.cs
public PartialViewResult GetPatients(string patient_Name="")
{
var patients = yourDBcontext.Patients.Where(x=>x.Name.Contains(patient_Name))
return PartialView("_patientList", patients);
}
And also as TSmith said in comments, don´t forget to install jQuery Unobtrusive Ajax library through NuGet.
from cmd run: SVN List URL you will be provided with 3 options (r)eject, (a)ccept, (p)ermanently. enter p. This resolved issue for me
I had a similar problem with gitlab. It turns out I had restricted the users that are allowed to login via ssh. This won't affect github users, but in case people end up here for gitlab (and the like) issues, ensure you add git
to the AllowUsers
setting in /etc/ssh/sshd_config
:
# Authentication:
LoginGraceTime 120
PermitRootLogin no
StrictModes yes
AllowUsers batman git
You can simply typecast, and it will do the conversion for you, e.g.
var with = (double?) jToken[key] ?? 100;
It will automatically return null
if said key is not present in the object, so there's no need to test for it.
From CREATE FUNCTION
:
When a parameter of the function has a default value, the keyword
DEFAULT
must be specified when the function is called to retrieve the default value. This behavior is different from using parameters with default values in stored procedures in which omitting the parameter also implies the default value.
So you need to do:
SELECT dbo.fCalculateEstimateDate(647,DEFAULT)
If you run pub build --mode=debug
the build directory contains the application without symlinks. The Dart code should be retained when --mode=debug
is used.
Here is some discussion going on about this topic too Dart and it's place in Rails Assets Pipeline
This seems much more straight forward to me:
import re
s = 'asdf=5;iwantthis123jasd'
x= re.search('iwantthis',s)
print(s[x.start():x.end()])
C# introduces properties which do most of the heavy lifting for you...
ie
public string Name { get; set; }
is a C# shortcut to writing...
private string _name;
public string getName { return _name; }
public void setName(string value) { _name = value; }
Basically getters and setters are just means of helping encapsulation. When you make a class you have several class variables that perhaps you want to expose to other classes to allow them to get a glimpse of some of the data you store. While just making the variables public to begin with may seem like an acceptable alternative, in the long run you will regret letting other classes manipulate your classes member variables directly. If you force them to do it through a setter, you can add logic to ensure no strange values ever occur, and you can always change that logic in the future without effecting things already manipulating this class.
ie
private string _name;
public string getName { return _name; }
public void setName(string value)
{
//Don't want things setting my Name to null
if (value == null)
{
throw new InvalidInputException();
}
_name = value;
}
There is another way to archive it.
In the BaseController
class create a method that returns a Model class like for instance.
public MenuPageModel GetTopMenu() { var m = new MenuPageModel(); // populate your model here return m; }
Layout
page you can call that method GetTopMenu()
@using GJob.Controllers <header class="header-wrapper border-bottom border-secondary"> <div class="sticky-header" id="appTopMenu"> @{ var menuPageModel = ((BaseController)this.ViewContext.Controller).GetTopMenu(); } @Html.Partial("_TopMainMenu", menuPageModel) </div> </header>
As a shorthand you can run:
docker tag d58 myname/server:latest
Where d58
represents the first 3 characters of the IMAGE ID,in this case, that's all you need.
Finally, you can remove the old image as follows:
docker rmi server
You could do the following:
Of course this isn't actually live.
What would be more sensible is that you could generate preview images for certain URLs e.g. every day or every week and use them. I image that you don't want to do this manually and you don't want to show the users of your service a preview that looks completely different than what the site currently looks like.
tail -f /path/to/glassfish/domains/YOURDOMAIN/logs/server.log
You can also upload log from admin console : http://yoururl:4848
You can simply do this with a bool:
if int(number) == float(number):
number = int(number)
else:
number = float(number)
The NSDictionary and NSMutableDictionary docs are probably your best bet. They even have some great examples on how to do various things, like...
...create an NSDictionary
NSArray *keys = [NSArray arrayWithObjects:@"key1", @"key2", nil];
NSArray *objects = [NSArray arrayWithObjects:@"value1", @"value2", nil];
NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:objects
forKeys:keys];
...iterate over it
for (id key in dictionary) {
NSLog(@"key: %@, value: %@", key, [dictionary objectForKey:key]);
}
...make it mutable
NSMutableDictionary *mutableDict = [dictionary mutableCopy];
Note: historic version before 2010: [[dictionary mutableCopy] autorelease]
...and alter it
[mutableDict setObject:@"value3" forKey:@"key3"];
...then store it to a file
[mutableDict writeToFile:@"path/to/file" atomically:YES];
...and read it back again
NSMutableDictionary *anotherDict = [NSMutableDictionary dictionaryWithContentsOfFile:@"path/to/file"];
...read a value
NSString *x = [anotherDict objectForKey:@"key1"];
...check if a key exists
if ( [anotherDict objectForKey:@"key999"] == nil ) NSLog(@"that key is not there");
...use scary futuristic syntax
From 2014 you can actually just type dict[@"key"] rather than [dict objectForKey:@"key"]
This three function are the same.
$(document).ready(function(){
})
and
$(function(){
});
and
jQuery(document).ready(function(){
});
here $
is used for define jQuery
like $
= jQuery
.
Now difference is that
$(document).ready
is jQuery event that is fired when DOM
is loaded, so it’s fired when the document structure is ready.
$(window).load
event is fired after whole content is loaded like page contain images,css etc.
Flat and simple config without rewrite, can work in some cases:
location / {
fastcgi_pass unix:/var/run/php5-fpm.sock;
include fastcgi_params;
fastcgi_param SCRIPT_FILENAME /home/webuser/site/index.php;
}
git reset --hard <old-commit-id>
git push -f <remote-name> <branch-name>
Note: As written in comments below, Using this is dangerous in a collaborative environment: you're rewriting history
the easiest thing to do is this:
$str = 'TRUE';
$boolean = strtolower($str) == 'true' ? true : false;
var_dump($boolean);
Doing it this way, you can loop through a series of 'true', 'TRUE', 'false' or 'FALSE' and get the string value to a boolean.
Maybe it helps, but Bazaar and Mercurial are both using dulwich for their Git interoperability.
Dulwich is probably different than the other in the sense that's it's a reimplementation of git in python. The other might just be a wrapper around Git's commands (so it could be simpler to use from a high level point of view: commit/add/delete), it probably means their API is very close to git's command line so you'll need to gain experience with Git.
Use %in%
as follows
A$C %in% B$C
Which will tell you which values of column C of A are in B.
What is returned is a logical vector. In the specific case of your example, you get:
A$C %in% B$C
# [1] TRUE FALSE TRUE TRUE
Which you can use as an index to the rows of A
or as an index to A$C
to get the actual values:
# as a row index
A[A$C %in% B$C, ] # note the comma to indicate we are indexing rows
# as an index to A$C
A$C[A$C %in% B$C]
[1] 1 3 4 # returns all values of A$C that are in B$C
We can negate it too:
A$C[!A$C %in% B$C]
[1] 2 # returns all values of A$C that are NOT in B$C
2 %in% B$C # "is the value 2 in B$C ?"
# FALSE
A$C[2] %in% B$C # "is the 2nd element of A$C in B$C ?"
# FALSE
I found the following to be useful to see who had the most lines that were currently in the code base:
git ls-files -z | xargs -0n1 git blame -w | ruby -n -e '$_ =~ /^.*\((.*?)\s[\d]{4}/; puts $1.strip' | sort -f | uniq -c | sort -n
The other answers have mostly focused on lines changed in commits, but if commits don't survive and are overwritten, they may just have been churn. The above incantation also gets you all committers sorted by lines instead of just one at a time. You can add some options to git blame (-C -M) to get some better numbers that take file movement and line movement between files into account, but the command might run a lot longer if you do.
Also, if you're looking for lines changed in all commits for all committers, the follow little script is helpful:
The reason you get a ConcurrentModificationException
is because an entry is removed via Set.remove() as opposed to Iterator.remove(). If an entry is removed via Set.remove() while an iteration is being done, you will get a ConcurrentModificationException. On the other hand, removal of entries via Iterator.remove() while iteration is supported in this case.
The new for loop is nice, but unfortunately it does not work in this case, because you can't use the Iterator reference.
If you need to remove an entry while iteration, you need to use the long form that uses the Iterator directly.
for (Iterator<Integer> it = set.iterator(); it.hasNext();) {
Integer element = it.next();
if (element % 2 == 0) {
it.remove();
}
}
angular2:
<img src="{{foo.url}}" onerror="this.src='path/to/altimg.png'">
final..It is a keyword which is used for make the string constant. You can not change the value of that string. Look at the example below:
public class StringTest {
static final String str = "Hello";
public static void main(String args[]) {
// str = "world"; // gives error
System.out.println(str); // called without the help of an object
System.out.println(StringTest.str);// called with class name
}
}
Thanks
You can throw an unchecked exception from the method which you wish to roll back. This will be detected by spring and your transaction will be marked as rollback only.
I'm assuming you're using Spring here. And I assume the annotations you refer to in your tests are the spring test based annotations.
The recommended way to indicate to the Spring Framework's transaction infrastructure that a transaction's work is to be rolled back is to throw an Exception from code that is currently executing in the context of a transaction.
and note that:
please note that the Spring Framework's transaction infrastructure code will, by default, only mark a transaction for rollback in the case of runtime, unchecked exceptions; that is, when the thrown exception is an instance or subclass of RuntimeException.
I had the same problem and my solution was the following:
Instead of deleting the main applicationhost.config
(in your "Documents/IIS Express" folder), check your solution folder for a hidden ".vs" folder with a "config" sub-folder. If that folder exists and it has it's own applicationhost.config
file you need to either rename (or delete) that file or edit it and make sure the website(s) configured inside match the ASP.NET web app(s) in your solution that you are trying to debug. Hope this helps.
You can use Collections.list()
to convert an Enumeration
to a List
in one line:
List<T> list = Collections.list(enumeration);
There's no similar method to get a Set
, however you can still do it one line:
Set<T> set = new HashSet<T>(Collections.list(enumeration));
Instead of use img src="", try to create a div and set background-image as the image you want.
Right now it's working for me.
example:
App.js
import React, { Component } from 'react';
import './App.css';
class App extends Component {
render() {
return (
<div>
<div className="myImage"> </div>
</div>
);
}
}
export default App;
App.css
.myImage {
width: 60px;
height: 60px;
background-image: url("./icons/add-circle.png");
background-repeat: no-repeat;
background-size: 100%;
}
I came across this post and found that none of the answers fully captured what I was trying to do. I have a laptop that has a 3840x2160 resolution and two monitors with 1920x1080 resolution. In order to get the correct monitor size in my WPF application I had to make the application DPI aware. Then I used the Win32 API to get the monitor size.
I did this by first moving the window to the monitor that I wanted to get the size from. Then by getting the hwnd of the application's MainWindow (doesn't have to be the main window but my application only has one window) and an IntPtr to the monitor. Then I created a new instance of the MONITORINFOEX struct and called the GetMonitorInfo method.
The MONITORINFOEX struct has both the working area and the full resolution of the screen so you can return whichever one you need. This will also allow you to leave out a reference to System.Windows.Forms (assuming you don't need it something else in your application). I used the .NET Framework Reference Source for System.Windows.Forms.Screen to come up with this solution.
public System.Drawing.Size GetMonitorSize()
{
var window = System.Windows.Application.Current.MainWindow;
var hwnd = new WindowInteropHelper(window).EnsureHandle();
var monitor = NativeMethods.MonitorFromWindow(hwnd, NativeMethods.MONITOR_DEFAULTTONEAREST);
NativeMethods.MONITORINFO info = new NativeMethods.MONITORINFO();
NativeMethods.GetMonitorInfo(new HandleRef(null, monitor), info);
return info.rcMonitor.Size;
}
internal static class NativeMethods
{
public const Int32 MONITOR_DEFAULTTONEAREST = 0x00000002;
[DllImport("user32.dll")]
public static extern IntPtr MonitorFromWindow(IntPtr handle, Int32 flags);
[DllImport("user32.dll", CharSet = CharSet.Auto)]
public static extern bool GetMonitorInfo(HandleRef hmonitor, MONITORINFO info);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto, Pack = 4)]
public class MONITORINFO
{
internal int cbSize = Marshal.SizeOf(typeof(MONITORINFO));
internal RECT rcMonitor = new RECT();
internal RECT rcWork = new RECT();
internal int dwFlags = 0;
}
[StructLayout(LayoutKind.Sequential)]
public struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
public RECT(int left, int top, int right, int bottom)
{
this.left = left;
this.top = top;
this.right = right;
this.bottom = bottom;
}
public RECT(System.Drawing.Rectangle r)
{
left = r.Left;
top = r.Top;
right = r.Right;
bottom = r.Bottom;
}
public static RECT FromXYWH(int x, int y, int width, int height) => new RECT(x, y, x + width, y + height);
public System.Drawing.Size Size => new System.Drawing.Size(right - left, bottom - top);
}
}
Assume the name of the branch where you made multiple commits is called bugfix/123, and you want to squash these commits.
First, create a new branch from develop (or whatever the name of your repo is). Assume the name of the new branch is called bugfix/123_up. Checkout this branch in git bash -
Now this branch will have only one commit with all your changes in it.
Using ScrollView
is not very difficult. You can just add one to your layout and put whatever you want to scroll inside. ScrollView
only takes one child so if you want to put a few things inside then you should make the first thing be something like a LinearLayout
.
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<!-- things to scroll -->
</LinearLayout>
</ScrollView>
If you want to scroll things horizontally, then use a HorizontalScrollView
.
As is talked about in this post, sometimes you want the ScrollView
content to fill the screen. For example, if you had some buttons at the end of a readme. You want the buttons to always be at the end of the text and at bottom of the screen, even if the text doesn't scroll.
If the content scrolls, everything is fine. However, if the content is smaller than the size of the screen, the buttons are not at the bottom.
This can be solved with a combination of using fillViewPort
on the ScrollView
and using a layout weight on the content. Using fillViewPort
makes the ScrollView
fill the parent area. Setting the layout_weight
on one of the views in the LinearLayout
makes that view expand to fill any extra space.
Here is the XML
<?xml version="1.0" encoding="utf-8"?>
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:fillViewport="true"> <--- fillViewport
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<TextView
android:id="@+id/textview"
android:layout_height="0dp" <---
android:layout_weight="1" <--- set layout_weight
android:layout_width="match_parent"
android:padding="6dp"
android:text="hello"/>
<LinearLayout
android:layout_height="wrap_content" <--- wrap_content
android:layout_width="match_parent"
android:background="@android:drawable/bottom_bar"
android:gravity="center_vertical">
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Accept" />
<Button
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Refuse" />
</LinearLayout>
</LinearLayout>
</ScrollView>
The idea for this answer came from a previous answer that is now deleted (link for 10K users). The content of this answer is an update and adaptation of this post.
I use redbot, a great tool to see php version, but also many other useful infos like headers, encoding, keepalive and many more, try it on
I loveit !
I also upvote Neil answer : curl -I http://websitename.com
There simply is no console listening by default. Running in debug mode there is a console attached, but in a production environment it is as you suspected, the message just doesn't go anywhere because nothing is listening.
Tests
On the Tests
class we will add an @XmlRootElement
annotation. Doing this will let your JAXB implementation know that when a document starts with this element that it should instantiate this class. JAXB is configuration by exception, this means you only need to add annotations where your mapping differs from the default. Since the testData
property differs from the default mapping we will use the @XmlElement
annotation. You may find the following tutorial helpful: http://wiki.eclipse.org/EclipseLink/Examples/MOXy/GettingStarted
package forum11221136;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Tests {
TestData testData;
@XmlElement(name="test-data")
public TestData getTestData() {
return testData;
}
public void setTestData(TestData testData) {
this.testData = testData;
}
}
TestData
On this class I used the @XmlType
annotation to specify the order in which the elements should be ordered in. I added a testData
property that appeared to be missing. I also used an @XmlElement
annotation for the same reason as in the Tests
class.
package forum11221136;
import java.util.List;
import javax.xml.bind.annotation.*;
@XmlType(propOrder={"title", "book", "count", "testData"})
public class TestData {
String title;
String book;
String count;
List<TestData> testData;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getBook() {
return book;
}
public void setBook(String book) {
this.book = book;
}
public String getCount() {
return count;
}
public void setCount(String count) {
this.count = count;
}
@XmlElement(name="test-data")
public List<TestData> getTestData() {
return testData;
}
public void setTestData(List<TestData> testData) {
this.testData = testData;
}
}
Demo
Below is an example of how to use the JAXB APIs to read (unmarshal) the XML and populate your domain model and then write (marshal) the result back to XML.
package forum11221136;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Tests.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11221136/input.xml");
Tests tests = (Tests) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(tests, System.out);
}
}
Just type in the following command: taskkill /f /im (program name) To find out the im of your program open task manager and look at the process while your program is running. After the program has run a process will disappear from the task manager; that is your program.
Hehe, curious. I think this is an "intentianal bug", so to speak.
The underlying reason is how the Integer class is written. Basically, parseInt is "optimized" for positive numbers. When it parses the string, it builds the result cumulatively, but negated. Then it flips the sign of the end-result.
Example:
66 = 0x42
parsed like:
4*(-1) = -4
-4 * 16 = -64 (hex 4 parsed)
-64 - 2 = -66 (hex 2 parsed)
return -66 * (-1) = 66
Now, let's look at your example FFFF8000
16*(-1) = -16 (first F parsed)
-16*16 = -256
-256 - 16 = -272 (second F parsed)
-272 * 16 = -4352
-4352 - 16 = -4368 (third F parsed)
-4352 * 16 = -69888
-69888 - 16 = -69904 (forth F parsed)
-69904 * 16 = -1118464
-1118464 - 8 = -1118472 (8 parsed)
-1118464 * 16 = -17895552
-17895552 - 0 = -17895552 (first 0 parsed)
Here it blows up since -17895552 < -Integer.MAX_VALUE / 16 (-134217728).
Attempting to execute the next logical step in the chain (-17895552 * 16)
would cause an integer overflow error.
Edit (addition): in order for the parseInt() to work "consistently" for -Integer.MAX_VALUE <= n <= Integer.MAX_VALUE, they would have had to implement logic to "rotate" when reaching -Integer.MAX_VALUE in the cumulative result, starting over at the max-end of the integer range and continuing downwards from there. Why they did not do this, one would have to ask Josh Bloch or whoever implemented it in the first place. It might just be an optimization.
However,
Hex=Integer.toHexString(Integer.MAX_VALUE);
System.out.println(Hex);
System.out.println(Integer.parseInt(Hex.toUpperCase(), 16));
works just fine, for just this reason. In the sourcee for Integer you can find this comment.
// Accumulating negatively avoids surprises near MAX_VALUE
A lot of good responses here; I especially like the lambda expressions...very clean. I was remiss, however, in not specifying the type of Collection. This is a SPRoleAssignmentCollection (from MOSS) that only has Remove(int) and Remove(SPPrincipal), not the handy RemoveAll(). So, I have settled on this, unless there is a better suggestion.
foreach (SPRoleAssignment spAssignment in workspace.RoleAssignments)
{
if (spAssignment.Member.Name != shortName) continue;
workspace.RoleAssignments.Remove((SPPrincipal)spAssignment.Member);
break;
}
To phyzome's answer (most highly voted one), it seems to me that if you put "identified by" at the end of the grant statement, the user will be created automatically. But if you don't, the user is not created. The following code works for me,
GRANT USAGE ON *.* TO 'username'@'localhost' IDENTIFIED BY 'password';
DROP USER 'username'@'localhost';
Hope this helps.
input()
by default takes the input in form of strings.
if (0<= vote <=24):
vote takes a string input (suppose 4
,5
,etc) and becomes uncomparable.
The correct way is: vote = int(input("Enter your message")
will convert the input to integer (4
to 4 or 5
to 5 depending on the input)
With reference to @ClarkeyBoy answer, below code works fine, if using latest version of Font-Awesome
icons or if you using fa
classes
.fa.icon-white {
color: white;
}
And, then add icon-white
to existing class
The easiest way to use a non-static method/field within a a static method or vice versa is...
(To work this there must be at least one instance of this class)
This type of situation is very common in android app development eg:- An Activity has at-least one instance.
public class ParentClass{
private static ParentClass mParentInstance = null;
ParentClass(){
mParentInstance = ParentClass.this;
}
void instanceMethod1(){
}
static void staticMethod1(){
mParentInstance.instanceMethod1();
}
public static class InnerClass{
void innerClassMethod1(){
mParentInstance.staticMethod1();
mParentInstance.instanceMethod1();
}
}
}
Note:- This cannot be used as a builder method like this one.....
String.valueOf(100);
Note: You shouldn't use async: false
due to this warning messages:
Starting with Gecko 30.0 (Firefox 30.0 / Thunderbird 30.0 / SeaMonkey 2.27), synchronous requests on the main thread have been deprecated due to the negative effects to the user experience.
Chrome even warns about this in the console:
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check https://xhr.spec.whatwg.org/.
This could break your page if you are doing something like this since it could stop working any day.
If you want to do it a way that still feels like if it's synchronous but still don't block then you should use async/await and probably also some ajax that is based on promises like the new Fetch API
async function foo() {
var res = await fetch(url)
console.log(res.ok)
var json = await res.json()
console.log(json)
}
Edit chrome is working on Disallowing sync XHR in page dismissal when the page is being navigated away or closed by the user. This involves beforeunload, unload, pagehide and visibilitychange.
if this is your use case then you might want to have a look at navigator.sendBeacon instead
It is also possible for the page to disable sync req with either http headers or iframe's allow attribute
I also faced the same issue. I found the solutions like following.
Solution 1: I kept my script tag in the body.
<body>
<form> . . . . </form>
<script type="text/javascript" src="<%= My.Working.Common.Util.GetSiteLocation()%>Scripts/Common.js"></script> </body>
Now conflicts regarding the tags will resolve.
Solution 2:
We can also solve this one of the above solutions like Replace the code block with <%# instead of <%= But the problem is it will give only relative path. If you want really absolute path it won't work.
Solution 1 works for me. Next is your choice.
Messing around with the line-height attribute should do the trick. I haven't tested this, so the exact value may not be right, but start with 1.5em, and tweak it in 0.1 increments until it lines up.
.pdf{ line-height:1.5em; }
select Col.name Columnname,prop.Value Description, tbl.name Tablename, sch.name schemaname
from sys.columns col left outer join sys.extended_properties prop
on prop.major_id = col.object_id and prop.minor_id = col.column_id
inner join sys.tables tbl on col.object_id = tbl.object_id
Left outer join sys.schemas sch on sch.schema_id = tbl.schema_id
Disclaimer: I'm the author of jgeXml.
jgexml has Node.js based utility xsd2json
which does a transformation between an XML schema (XSD) and a JSON schema file.
As with other options, it's not a 1:1 conversion, and you may need to hand-edit the output to improve the JSON schema validation, but it has been used to represent a complex XML schema inside an OpenAPI (swagger) definition.
A sample of the purchaseorder.xsd given in another answer is rendered as:
"PurchaseOrderType": {
"type": "object",
"properties": {
"shipTo": {
"$ref": "#/definitions/USAddress"
},
"billTo": {
"$ref": "#/definitions/USAddress"
},
"comment": {
"$ref": "#/definitions/comment"
},
"items": {
"$ref": "#/definitions/Items"
},
"orderDate": {
"type": "string",
"pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}.*$"
}
},
Just to update these answers, ESRI has included this tool, known as Layer to KML in ArcMap 10.X. Also, a Map to KML tool exists.
Simply import the desired layer (vector or raster) and choose the output location, resolution, etc. Very simple tool.
Does this work?
Workbooks.Open Filename:=filepath, ReadOnly:=True
Or, as pointed out in a comment, to keep a reference to the opened workbook:
Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)
The documentation here encourages listening to the onbeforeunload event and/or adding an event listener on window.
window.addEventListener('beforeunload', function(event) {
//do something here
}, false);
You can also just populate the .onunload or .onbeforeunload properties of window with a function or a function reference.
Though behaviour is not standardized across browsers, the function may return a value that the browser will display when confirming whether to leave the page.
Is it a good practice to use try-except-else in python?
The answer to this is that it is context dependent. If you do this:
d = dict()
try:
item = d['item']
except KeyError:
item = 'default'
It demonstrates that you don't know Python very well. This functionality is encapsulated in the dict.get
method:
item = d.get('item', 'default')
The try
/except
block is a much more visually cluttered and verbose way of writing what can be efficiently executing in a single line with an atomic method. There are other cases where this is true.
However, that does not mean that we should avoid all exception handling. In some cases it is preferred to avoid race conditions. Don't check if a file exists, just attempt to open it, and catch the appropriate IOError. For the sake of simplicity and readability, try to encapsulate this or factor it out as apropos.
Read the Zen of Python, understanding that there are principles that are in tension, and be wary of dogma that relies too heavily on any one of the statements in it.
Or echo 'put {path to file}' | sftp {user}@{host}:{dir}
, which would work in both unix and powershell.
Old question I know, but for the curious:
Believe it or not, this issue was solved ~2 decades ago with HTTP BASIC, which passes the value as base64 encoded username:password. (See http://en.wikipedia.org/wiki/Basic_access_authentication#Client_side)
You could do the same, so that the example above would become:
Authorization: FIRE-TOKEN MFBONUoxN0hCR1pIVDdKSjNYODI6ZnJKSVVOOERZcEtEdE9MQ3dvLy95bGxxRHpnPQ==
That depends on the failure handling. If you just want to skip the error elements, try inside:
for(int i = 0; i < max; i++) {
String myString = ...;
try {
float myNum = Float.parseFloat(myString);
myFloats[i] = myNum;
} catch (NumberFormatException ex) {
--i;
}
}
In any other case i would prefer the try outside. The code is more readable, it is more clean. Maybe it would be better to throw an IllegalArgumentException in the error case instead if returning null.
To get Token Device you can do by some steps:
1) Enable APNS (Apple Push Notification Service) for both Developer Certification and Distribute Certification, then redownload those two file.
2) Redownload both Developer Provisioning and Distribute Provisioning file.
3) In Xcode interface: setting provisioning for PROJECT and TARGETS with two file provisioning have download.
4) Finally, you need to add the code below in AppDelegate file to get Token Device (note: run app in real device).
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
[self.window addSubview:viewController.view];
[self.window makeKeyAndVisible];
NSLog(@"Registering for push notifications...");
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert)];
return YES;
}
- (void)application:(UIApplication *)app didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
NSString *str = [NSString stringWithFormat:@"Device Token=%@",deviceToken];
NSLog(@"%@", str);
}
- (void)application:(UIApplication *)app didFailToRegisterForRemoteNotificationsWithError:(NSError *)err {
NSString *str = [NSString stringWithFormat: @"Error: %@", err];
NSLog(@"%@",str);
}
A call to vector<T>::size()
returns a value of type std::vector<T>::size_type
, not int, unsigned int or otherwise.
Also generally iteration over a container in C++ is done using iterators, like this.
std::vector<T>::iterator i = polygon.begin();
std::vector<T>::iterator end = polygon.end();
for(; i != end; i++){
sum += *i;
}
Where T is the type of data you store in the vector.
Or using the different iteration algorithms (std::transform
, std::copy
, std::fill
, std::for_each
et cetera).
In addition to grants, you can try creating synonyms. It will avoid the need for specifying the table owner schema every time.
From the connecting schema:
CREATE SYNONYM pi_int FOR pct.pi_int;
Then you can query pi_int
as:
SELECT * FROM pi_int;
Its my code
jQuery(document).ready(function(e) {
var WindowHeight = jQuery(window).height();
var load_element = 0;
//position of element
var scroll_position = jQuery('.product-bottom').offset().top;
var screen_height = jQuery(window).height();
var activation_offset = 0;
var max_scroll_height = jQuery('body').height() + screen_height;
var scroll_activation_point = scroll_position - (screen_height * activation_offset);
jQuery(window).on('scroll', function(e) {
var y_scroll_pos = window.pageYOffset;
var element_in_view = y_scroll_pos > scroll_activation_point;
var has_reached_bottom_of_page = max_scroll_height <= y_scroll_pos && !element_in_view;
if (element_in_view || has_reached_bottom_of_page) {
jQuery('.product-bottom').addClass("change");
} else {
jQuery('.product-bottom').removeClass("change");
}
});
});
Its working Fine
getClass().getResource()
uses the class loader to load the resource. This means that the resource must be in the classpath to be loaded.
When doing it with Eclipse, everything you put in the source folder is "compiled" by Eclipse:
When launching the program with Eclipse, the bin directory is thus in the classpath, and since it contains the Test.properties file, this file can be loaded by the class loader, using getResource()
or getResourceAsStream()
.
If it doesn't work from the command line, it's thus because the file is not in the classpath.
Note that you should NOT do
FileInputStream inputStream = new FileInputStream(new File(getClass().getResource(url).toURI()));
to load a resource. Because that can work only if the file is loaded from the file system. If you package your app into a jar file, or if you load the classes over a network, it won't work. To get an InputStream, just use
getClass().getResourceAsStream("Test.properties")
And finally, as the documentation indicates,
Foo.class.getResourceAsStream("Test.properties")
will load a Test.properties file located in the same package as the class Foo.
Foo.class.getResourceAsStream("/com/foo/bar/Test.properties")
will load a Test.properties file located in the package com.foo.bar
.
I had the same problem :) Verify the "Source code" folder on the "Solution Explorer", if it doesn't contain any "source code" file then :
Right click on "Source code" > Add > Existing Item > Choose the file You want to build and run.
Good luck ;)
Just a simple folder drill down.
sub sample()
Dim FileSystem As Object
Dim HostFolder As String
HostFolder = "C:\"
Set FileSystem = CreateObject("Scripting.FileSystemObject")
DoFolder FileSystem.GetFolder(HostFolder)
end sub
Sub DoFolder(Folder)
Dim SubFolder
For Each SubFolder In Folder.SubFolders
DoFolder SubFolder
Next
Dim File
For Each File In Folder.Files
' Operate on each file
Next
End Sub
If you are using django app to deploy on heroku
make sure to put request library in the requirements.txt file.
It depends
It depends on a lot of things - your goals, your experience, your timeframe, etc.
The majority of game programming isn't language specific. 3D math is 3D math in C# as much as it is in C++. While the APIs may be different, and different 'bookkeeping' may be required, the fundamental logic and math will remain the same.
And it's true that most AAA game engines are C++ with a scripting language on top of them. That is undeniable. However, most AAA engines also have a bunch of in-house tools supporting them, and those may be in anything - Java, C#, C++, etc.
If you want to write a game, and are an experienced developer then C++ and C# have a lot going for them. C# has less housekeeping, while C++ has more available libraries and tools. For anything highly complex, however, you'd be best off trying to use an existing engine as a starting point.
If you want to write a game, and are a new developer then don't write an engine. Use an existing engine, and mod it or use its facilities to write your game. Trust me.
If you want to learn how to write an engine, and are an experienced developer you should probably think about C++. C# is possible as well, but the amount of code and ease of integration of C++ probably puts it over the top.
If you want to learn how to write an engine, and are a new developer I'd probably recommend C#/XNA. You'll get to the game 'stuff' faster, with less headache of learning the ins and outs of C++.
If you want a job in the industry then you need to figure out what kind of job you want. A high-level language can help get a foot in the door dealing with tools and/or web development, which can lead to opportunities on actual game work. Even knowledge of scripting languages can help if you want to go for more of the game designer/scripter position. Chances are that you will not get a job working on core engine stuff immediately, as the skills required to do so are pretty high. Strong C++ development skills are always helpful, especially in real-time or networked scenarios.
AAA game engine development involves some serious brain-twisting code.
If you want to start a professional development house then you probably aren't reading this, but already know that C++ is probably the only viable answer.
If you want to do casual game development then you should probably consider Flash or a similar technology.
A faster way to
would be
:x
If you have opened multiple files you may need to do a
:xa
I don't know whether they really skipped it or if my eyes were just glazing over but....
Just in case anybody else is overlooking the same things that I did....
just as when you were developing and testing...
1) You need a DISTRIBUTION << CERTIFICATE >> 2) You need a DISTRIBUTION << PROVISIONING PROFILE >>
That is TWO STEPS on the portal in order to get the thing signed.
There I was, having created the developer CERTIFICATE and copied it to the Mobile Provisions folder, wondering why it didn't work.
As soon as I had the provisioning profile in place
* BINGO *
<div id="cblist">
<input type="checkbox" value="first checkbox" id="cb1" /> <label for="cb1">first checkbox</label>
</div>
<input type="text" id="txtName" />
<input type="button" value="ok" id="btnSave" />
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
addCheckbox($('#txtName').val());
});
});
function addCheckbox(name) {
var container = $('#cblist');
var inputs = container.find('input');
var id = inputs.length+1;
$('<input />', { type: 'checkbox', id: 'cb'+id, value: name }).appendTo(container);
$('<label />', { 'for': 'cb'+id, text: name }).appendTo(container);
}
</script>
Real problem is when you need draw some tile/sprites intersecting/spanning two or more other tiles.
After 2 (hard) months of personal analisys of problem I finally found and implemented a "correct render drawing" for my new cocos2d-js game. Solution consists in mapping, for each tile (susceptible), which sprites are "front, back, top and behind". Once doing that you can draw them following a "recursive logic".
Needed this answer myself and from the link provided by David Moye, decided on this and thought it might be of use to others with the same question:
CREATE PROCEDURE ...
AS
BEGIN
BEGIN TRANSACTION
-- lock table "a" till end of transaction
SELECT ...
FROM a
WITH (TABLOCK, HOLDLOCK)
WHERE ...
-- do some other stuff (including inserting/updating table "a")
-- release lock
COMMIT TRANSACTION
END
I could use the GetBody
from Request package.
Look this comment in source code from request.go in net/http:
GetBody defines an optional func to return a new copy of Body. It is used for client requests when a redirect requires reading the body more than once. Use of GetBody still requires setting Body. For server requests it is unused."
GetBody func() (io.ReadCloser, error)
This way you can get the body request without make it empty.
Sample:
getBody := request.GetBody
copyBody, err := getBody()
if err != nil {
// Do something return err
}
http.DefaultClient.Do(request)
set your property using below code at the time of model creation i think your problem will be solved..and the time are not appear in database.you dont need to add any annotation.
private DateTime? dob;
public DateTime? DOB
{
get
{
if (dob != null)
{
return dob.Value.Date;
}
else
{
return null;
}
}
set { dob = value; }
}
Following are the references that may explain Architecture in more detail and a list of UML diagrams for software architecture. (I could not find listing of UML diagrams for software design )
UML 2 Diagram use for Architectural Models
Classification of UML diagrams
Classification of UML diagrams
Even after posting this answer, i myself is not clear which diagram is for architecture and which one for design :). Grady Booch, in his slide # 58, states that Classes, Interfaces and Collaborations are part of Design View and this Design View is one of the View of Architecture !!!
Get Sum Of particular row value using PHP MYSQL
"SELECT SUM(filed_name) from table_name"
If you are absolutely sure that your Python library path is in your system variables (and you can find that path when you pip install Jupyter, you just have to read a bit) and you still experience "command not found or recognized" errors in Windows, you can try:
python -m notebook
For my Windows at least (Windows 10 Pro), having the python -m
is the only way I can run my Python packages from command line without running into some sort of error
Fatal error in launcher: Unable to create process using ' "
or
Errno 'THIS_PROGRAM' not found
The literal answer is:
return (value == 1 ? Periods.VariablePeriods : Periods.FixedPeriods);
Note that the inline if statement, just like an if statement, only checks for true or false. If (value == 1) evaluates to false, it might not necessarily mean that value == 2. Therefore it would be safer like this:
return (value == 1
? Periods.VariablePeriods
: (value == 2
? Periods.FixedPeriods
: Periods.Unknown));
If you add more values an inline if will become unreadable and a switch would be preferred:
switch (value)
{
case 1:
return Periods.VariablePeriods;
case 2:
return Periods.FixedPeriods;
}
The good thing about enums is that they have a value, so you can use the values for the mapping, as user854301 suggested. This way you can prevent unnecessary branches thus making the code more readable and extensible.
In this part of your code:
if(tmp[j] > 57 && tmp[j] < 48)
isDigit = 0;
else
isDigit = 1;
Your if
condition will always be false, resulting in isDigit
always being set to 1
. You are probably wanting:
if(tmp[j] > '9' || tmp[j] < '0')
isDigit = 0;
else
isDigit = 1;
But. this can be simplified to:
isDigit = isdigit(tmp[j]);
However, the logic of your loop seems kind of misguided:
int isDigit = 0;
int j=0;
while(j<strlen(tmp) && isDigit == 0){
isDigit = isdigit(tmp[j]);
j++;
}
As tmp
is not a constant, it is uncertain whether the compiler will optimize the length calculation out of each iteration.
As @andlrc suggests in a comment, you can instead just check for digits, since the terminating NUL will fail the check anyway.
while (isdigit(tmp[j])) ++j;
This is an answer from 2012, the question if from 2009, but people still look at it and there's only one correct (use WebDriver
) and one almost useful (but not good enough) answer.
If you're using Selenium RC and can actually see an alert dialog, then it can't be done. Selenium should handle it for you. But, as stated in Selenium documentation:
Selenium tries to conceal those dialogs from you (by replacing window.alert, window.confirm and window.prompt) so they won’t stop the execution of your page. If you’re seeing an alert pop-up, it’s probably because it fired during the page load process, which is usually too early for us to protect the page.
It is a known limitation of Selenium RC (and, therefore, Selenium IDE, too) and one of the reasons why Selenium 2 (WebDriver) was developed. If you want to handle onload
JS alerts, you need to use WebDriver alert handling.
That said, you can use Robot
or selenium.keyPressNative()
to fill in any text and press Enter and confirm the dialog blindly. It's not the cleanest way, but it could work. You won't be able to get the alert
message, however.
Robot
has all the useful keys mapped to constants, so that will be easy. With keyPressNative()
, you want to use 10
as value for pressing Enter or 27
for Esc since it works with ASCII codes.
First, a better usage to compute number of elements when the actual array declaration is in scope is:
sizeof array / sizeof array[0]
This way you don't repeat the type name, which of course could change in the declaration and make you end up with an incorrect length computation. This is a typical case of don't repeat yourself.
Second, as a minor point, please note that sizeof
is not a function, so the expression above doesn't need any parenthesis around the argument to sizeof
.
Third, C doesn't have references so your usage of &
in a declaration won't work.
I agree that the proper C solution is to pass the length (using the size_t
type) as a separate argument, and use sizeof
at the place the call is being made if the argument is a "real" array.
Note that often you work with memory returned by e.g. malloc()
, and in those cases you never have a "true" array to compute the size off of, so designing the function to use an element count is more flexible.
Use "$@"
to represent all the arguments:
for var in "$@"
do
echo "$var"
done
This will iterate over each argument and print it out on a separate line. $@ behaves like $* except that when quoted the arguments are broken up properly if there are spaces in them:
sh test.sh 1 2 '3 4'
1
2
3 4
.class {
/* Fallback for web browsers that doesn't support RGBa */
background: rgb(0, 0, 0);
/* RGBa with 0.6 opacity */
background: rgba(0, 0, 0, 0.6);
}
replace now.getTime() with your long value.
//GET UTC time for current date
Date now= new Date();
//LocalDateTime utcDateTimeForCurrentDateTime = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDateTime();
LocalDate localDate = Instant.ofEpochMilli(now.getTime()).atZone(ZoneId.of("UTC")).toLocalDate();
DateTimeFormatter dTF2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm");
System.out.println(" formats as " + dTF2.format(utcDateTimeForCurrentDateTime));
You can try the simple one
select to_date('2020-07-08T15:30:42Z','yyyy-mm-dd"T"hh24:mi:ss"Z"') from dual;
Try this out: sudo cron reload
It works for me on ubuntu 12.10
At this point method
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
this.mWakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, "My Tag");
this.mWakeLock.acquire();
is deprecated.
You should use
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
and getWindow().clearFlags(android.view.WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
You can fake it like this:
-- with column headings
select column1, column2 from some_table;
-- without column headings
select column1 as '', column2 as '' from some_table;
is only the matter of finding the dom where you want to insert the the text.
DEMO jsfiddle
$().text();
This would be a good place to use a closure:
(function() {
var toggled = false;
$(".list-toggle").click(function() {
toggled = !toggled;
$(".list-sort").attr("colspan", toggled ? 6 : null);
});
})();
The toggled
variable will only exist inside of the scope defined, and can be used to store the state of the toggle from one click event to the next.
If you want to execute a function when something is done. One of a good solution is to listen to events.
For example, I'll implement a Dispatcher
, a DispatcherEvent
class with ES6,then:
let Notification = new Dispatcher()
Notification.on('Load data success', loadSuccessCallback)
const loadSuccessCallback = (data) =>{
...
}
//trigger a event whenever you got data by
Notification.dispatch('Load data success')
Dispatcher:
class Dispatcher{
constructor(){
this.events = {}
}
dispatch(eventName, data){
const event = this.events[eventName]
if(event){
event.fire(data)
}
}
//start listen event
on(eventName, callback){
let event = this.events[eventName]
if(!event){
event = new DispatcherEvent(eventName)
this.events[eventName] = event
}
event.registerCallback(callback)
}
//stop listen event
off(eventName, callback){
const event = this.events[eventName]
if(event){
delete this.events[eventName]
}
}
}
DispatcherEvent:
class DispatcherEvent{
constructor(eventName){
this.eventName = eventName
this.callbacks = []
}
registerCallback(callback){
this.callbacks.push(callback)
}
fire(data){
this.callbacks.forEach((callback=>{
callback(data)
}))
}
}
Happy coding!
p/s: My code is missing handle some error exceptions
Also, make sure you have no files that accidentally try to inherit or define the same (partial) class as other files. Note that these files can seem unrelated to the files where the error actually appeared!
it's very simple how to replace with Fragment.
DataFromDb changeActivity = new DataFromDb();
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
transaction.replace(R.id.changeFrg, changeActivity);
transaction.commit();
Just put .htaccess into the folder you want to restrict
## no access to this folder
# Apache 2.4
<IfModule mod_authz_core.c>
Require all denied
</IfModule>
# Apache 2.2
<IfModule !mod_authz_core.c>
Order Allow,Deny
Deny from all
</IfModule>
Source: MantisBT sources.
Stephen Canon answered it very well!
But
This is 3 times as fast as testing all m up to vn.
int IsPrime(unsigned int number) {
if (number <= 3 && number > 1)
return 1; // as 2 and 3 are prime
else if (number%2==0 || number%3==0)
return 0; // check if number is divisible by 2 or 3
else {
unsigned int i;
for (i=5; i*i<=number; i+=6) {
if (number % i == 0 || number%(i + 2) == 0)
return 0;
}
return 1;
}
}
Generally speaking, this is the pattern I use:
You can add virtual columns as
SELECT '1' as temp
But if you tries to put where condition to additionally generated column, it wont work and will show an error message as the column doesn't exist.
We can solve this issue by returning sql result as a table.ie,
SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1
This one works for me
<li ng-style="{'background-image':'url(/static/'+imgURL+')'}">...</li>
Wouldn't unlinking it and creating the new one do the same thing in the end anyway?
Here's a complete example of how it can be done. However you need flashback query privileges on the child table.
Here's the setup.
create table parent_tab
(parent_id number primary key,
val varchar2(20));
create table child_tab
(child_id number primary key,
parent_id number,
child_val number,
constraint child_par_fk foreign key (parent_id) references parent_tab);
insert into parent_tab values (1,'Red');
insert into parent_tab values (2,'Green');
insert into parent_tab values (3,'Blue');
insert into parent_tab values (4,'Black');
insert into parent_tab values (5,'White');
insert into child_tab values (10,1,100);
insert into child_tab values (20,3,100);
insert into child_tab values (30,3,100);
insert into child_tab values (40,4,100);
insert into child_tab values (50,5,200);
commit;
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
Now delete a subset of the children (ones with parents 1,3 and 4 - but not 5).
delete from child_tab where child_val = 100;
Then get the parent_ids from the current COMMITTED state of the child_tab (ie as they were prior to your deletes) and remove those that your session has NOT deleted. That gives you the subset that have been deleted. You can then delete those out of the parent_tab
delete from parent_tab
where parent_id in
(select parent_id from child_tab as of scn dbms_flashback.get_system_change_number
minus
select parent_id from child_tab);
'Green' is still there (as it didn't have an entry in the child table anyway) and 'Red' is still there (as it still has an entry in the child table)
select * from parent_tab
where parent_id not in (select parent_id from child_tab);
select * from parent_tab;
It is an exotic/unusual operation, so if i was doing it I'd probably be a bit cautious and lock both child and parent tables in exclusive mode at the start of the transaction. Also, if the child table was big it wouldn't be particularly performant so I'd opt for a PL/SQL solution like Rajesh's.
Well you can do it but may catch more exceptions.
So if the your script should runs as another user such as www U should make sure the PATH and other environment is ok.
sudo -u www -i /the/path/of/your/script
Please prefer the sudo manual~ -i [command] The -i (simulate initial login) option runs the shell specified by the password database entry of the target user as a loginshell...
The tarlog plugin, combined with removing -Dorg.eclipse.swt.internal.carbon.smallFonts from eclipse.ini, helps my tired eyes on MacOS Yosemite with Eclipse Luna (4.4).
Problem: Didn't work for me for a PyDev foo.py Python file. Workaround: Open a file named foo.java - change the font size. Go back to foo.py and voila!! - the python font size matches the java font size.
You just need to specify which columns you're inserting directly into:
INSERT INTO [dbo].[rLicenses] ([Name]) VALUES ('test')
Views can be picky like that.
This is working for me,
# cat checking.sh
#!/bin/bash
echo "You have provided the following arguments $arg1 $arg2 $arg3"
if [ "$arg1" = "$arg2" ] && [ "$arg1" != "$arg3" ]
then
echo "Two of the provided args are equal."
exit 3
elif [ $arg1 == $arg2 ] && [ $arg1 = $arg3 ]
then
echo "All of the specified args are equal"
exit 0
else
echo "All of the specified args are different"
exit 4
fi
# ./checking.sh
You have provided the following arguments
All of the specified args are equal
You can add set -x
in script to troubleshoot the errors.
Use the grepl
function
grepl( needle, haystack, fixed = TRUE)
like so:
grepl(value, chars, fixed = TRUE)
# TRUE
Use ?grepl
to find out more.
attr_accessor
is a Ruby method that gives you setter and getter methods to an instance variable of the same name. So it is equivalent to
class MyModel
def my_variable
@my_variable
end
def my_variable=(value)
@my_variable = value
end
end
attr_accessible
is a Rails method that determines what variables can be set in a mass assignment.
When you submit a form, and you have something like MyModel.new params[:my_model]
then you want to have a little bit more control, so that people can't submit things that you don't want them to.
You might do attr_accessible :email
so that when someone updates their account, they can change their email address. But you wouldn't do attr_accessible :email, :salary
because then a person could set their salary through a form submission. In other words, they could hack their way to a raise.
That kind of information needs to be explicitly handled. Just removing it from the form isn't enough. Someone could go in with firebug and add the element into the form to submit a salary field. They could use the built in curl to submit a new salary to the controller update method, they could create a script that submits a post with that information.
So attr_accessor
is about creating methods to store variables, and attr_accessible
is about the security of mass assignments.
Use the __contains__()
method of Pythons string class.:
a = ['abc-123', 'def-456', 'ghi-789', 'abc-456']
for i in a:
if i.__contains__("abc") :
print(i, " is containing")
This should remove the first element, and then you can return the remaining:
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
_x000D_
myarray.shift();_x000D_
alert(myarray);
_x000D_
As others have suggested, you could also use slice(1);
var myarray = ["item 1", "item 2", "item 3", "item 4"];_x000D_
_x000D_
alert(myarray.slice(1));
_x000D_
UPDATE
Microsoft now provide this artifact in maven central. See @nirmal's answer for further details: https://stackoverflow.com/a/41149866/1570834
ORIGINAL ANSWER
The issue is that Maven can't find this artifact in any of the configured maven repositories.
Unfortunately Microsoft doesn't make this artifact available via any maven repository. You need to download the jar from the Microsoft website, and then manually install it into your local maven repository.
You can do this with the following maven command:
mvn install:install-file -Dfile=sqljdbc4.jar -DgroupId=com.microsoft.sqlserver -DartifactId=sqljdbc4 -Dversion=4.0 -Dpackaging=jar
Then next time you run maven on your POM it will find the artifact.
I found that using cast()
was the best solution for me:
cast(Format(amount, "Standard") AS CHAR CHARACTER SET utf8) AS Amount
There is also a convert()
function. More details on it here
Another resource here
I wasn't happy with any of these answers, and the one that's right has no explanation and negative votes so I searched around, found some stuff and edited it so that it is easy to understand. Have a play with it, not as straight forward as one would hope.
//move your variable into an Object type
Object obj=whatYouAreChecking;
System.out.println(obj);
// moving the class type into a Class variable
Class cls=obj.getClass();
System.out.println(cls);
// convert that Class Variable to a neat String
String answer = cls.getSimpleName();
System.out.println(answer);
Here is a method:
public static void checkClass (Object obj) {
Class cls = obj.getClass();
System.out.println("The type of the object is: " + cls.getSimpleName());
}
DATE(readingstamp) BETWEEN '2016-07-21' AND '2016-07-31' AND TIME(readingstamp) BETWEEN '08:00:00' AND '17:59:59'
simply separate the casting of date and time
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
If you're using Rails 3+, remove the gem from the Gemfile and run bundle install
.
If you're using Rails 2, hopefully you've put the declaration in config/environment.rb. If so, removing it from there and running rake gems:install
should do the trick.
You can use:
set content=
for /f "delims=" %%i in ('type text.txt') do set content=!content! %%i
Just in case you don't want to use stored proc, here's a simple query version
select *
from information_schema.columns
where table_name = 'aspnet_Membership'
order by ordinal_position
function count(){
var c= 0;
for(var p in this) if(this.hasOwnProperty(p))++c;
return c;
}
var O={a: 1, b: 2, c: 3};
count.call(O);
All the answers that include creating an new object from Form
class are absolutely creating new form
. But you can use Text
property of ActiveForm
subclass in Form
class. For example:
public Form1()
{
InitializeComponent();
Form1.ActiveForm.Text = "Your Title";
}
This Blog article explains the internals of ODEX files:
WHAT IS AN ODEX FILE?
In Android file system, applications come in packages with the extension .apk. These application packages, or APKs contain certain .odex files whose supposed function is to save space. These ‘odex’ files are actually collections of parts of an application that are optimized before booting. Doing so speeds up the boot process, as it preloads part of an application. On the other hand, it also makes hacking those applications difficult because a part of the coding has already been extracted to another location before execution.
Here's a stdlib solution that supports a variable utc offset in the input time string:
>>> from email.utils import parsedate_tz, mktime_tz
>>> from datetime import datetime, timedelta
>>> timestamp = mktime_tz(parsedate_tz('Tue May 08 15:14:45 +0800 2012'))
>>> utc_time = datetime(1970, 1, 1) + timedelta(seconds=timestamp)
>>> utc_time
datetime.datetime(2012, 5, 8, 7, 14, 45)
There are 3 ways to pass data from Parent to Children
Through Children Router Resolver if you have to receive different data
this.data = this.route.snaphsot.data['dataFromResolver'];
Through Parent Router Resolver if your have to receive the same data from parent
this.data = this.route.parent.snaphsot.data['dataFromResolver'];
Note1: You can read about resolver here. There is also an example of resolver and how to register the resolver into the module and then retrieve data from resolver into the component. The resolver registration is the same on the parent and child.
Note2: You can read about ActivatedRoute here to be able to get data from router
edit: this answer has been written in 2013. Please check Cristian Traìna's comment below about requestAnimationFrame
I made it. The code below doesn't depend on any framework.
Limitation : The anchor active is not written in the url.
Version of the code : 1.0 | Github : https://github.com/Yappli/smooth-scroll
(function() // Code in a function to create an isolate scope
{
var speed = 500;
var moving_frequency = 15; // Affects performance !
var links = document.getElementsByTagName('a');
var href;
for(var i=0; i<links.length; i++)
{
href = (links[i].attributes.href === undefined) ? null : links[i].attributes.href.nodeValue.toString();
if(href !== null && href.length > 1 && href.substr(0, 1) == '#')
{
links[i].onclick = function()
{
var element;
var href = this.attributes.href.nodeValue.toString();
if(element = document.getElementById(href.substr(1)))
{
var hop_count = speed/moving_frequency
var getScrollTopDocumentAtBegin = getScrollTopDocument();
var gap = (getScrollTopElement(element) - getScrollTopDocumentAtBegin) / hop_count;
for(var i = 1; i <= hop_count; i++)
{
(function()
{
var hop_top_position = gap*i;
setTimeout(function(){ window.scrollTo(0, hop_top_position + getScrollTopDocumentAtBegin); }, moving_frequency*i);
})();
}
}
return false;
};
}
}
var getScrollTopElement = function (e)
{
var top = 0;
while (e.offsetParent != undefined && e.offsetParent != null)
{
top += e.offsetTop + (e.clientTop != null ? e.clientTop : 0);
e = e.offsetParent;
}
return top;
};
var getScrollTopDocument = function()
{
return document.documentElement.scrollTop + document.body.scrollTop;
};
})();
you can do something like this
$collection = collect(['name' => 'Desk', 'price' => 200]);
$collection->toArray();
Reference is https://laravel.com/docs/5.1/collections#method-toarray
Originally from Laracasts website https://laracasts.com/discuss/channels/laravel/how-to-convert-this-collection-to-an-array
Those commands use different output streams. By default both messages will be printed on console but it's possible for example to redirect one or both of these to a file.
java MyApp 2>errors.txt
This will redirect System.err
to errors.txt
file.
I found that these CSS styles force the page to always scroll to top on reload/refresh:
html {
height: 100%;
overflow: hidden;
width: 100%;
}
body {
height: 100%;
overflow-x: hidden;
overflow-y: auto;
width: 100%;
}
This solved my similar problem. I used it to revert the changes, then I added everything and commited changes in the terminal with
svn add folder_path/*
svn commit -m "message"
This should work, I just tested it out and it worked as expected: no expansion, substitution, or what-have-you took place.
cat <<< '
#!/bin/bash
curr=`cat /sys/class/backlight/intel_backlight/actual_brightness`
if [ $curr -lt 4477 ]; then
curr=$((curr+406));
echo $curr > /sys/class/backlight/intel_backlight/brightness;
fi' > file # use overwrite mode so that you don't keep on appending the same script to that file over and over again, unless that's what you want.
Using the following also works.
cat <<< ' > file
... code ...'
Also, it's worth noting that when using heredocs, such as << EOF
, substitution and variable expansion and the like takes place. So doing something like this:
cat << EOF > file
cd "$HOME"
echo "$PWD" # echo the current path
EOF
will always result in the expansion of the variables $HOME
and $PWD
. So if your home directory is /home/foobar
and the current path is /home/foobar/bin
, file
will look like this:
cd "/home/foobar"
echo "/home/foobar/bin"
instead of the expected:
cd "$HOME"
echo "$PWD"
the plus works just fine, i personally prefer using the concat function.
var s = string.Concat(string 1, string 2, string, 3, etc)