This works in all browsers:
window.location.href = '...';
If you wanted to change the page without it reflecting in the browser back history, you can do:
window.location.replace('...');
None of the answers above, at least to me, show how to actually handle determining whether you have 1 item or multiple, and how to actually get the values out of your items in a generic way that doesn't depend on there actually only being one item, or multiple, so I'm throwing my hat in the ring.
This is quite easily and generically done by checking your count to see that you have at least one item, then doing a foreach
loop on the .SelectedItems
, casting each item as a DataRowView
:
if (listView1.SelectedItems.Count > 0)
{
foreach (DataRowView drv in listView1.SelectedItems)
{
string firstColumn = drv.Row[0] != null ? drv.Row[0].ToString() : String.Empty;
string secondColumn = drv.Row[1] != null ? drv.Row[1].ToString() : String.Empty;
// ... do something with these values before they are replaced
// by the next run of the loop that will get the next row
}
}
This will work, whether you have 1 item or many. It's funny that MSDN says to use ListView.SelectedListViewItemCollection
to capture listView1.SelectedItems
and iterate through that, but I found that this gave an error in my WPF app: The type name 'SelectedListViewItemCollection' does not exist in type 'ListView'
.
select sequence_owner, sequence_name from dba_sequences;
DBA_SEQUENCES -- all sequences that exist
ALL_SEQUENCES -- all sequences that you have permission to see
USER_SEQUENCES -- all sequences that you own
Note that since you are, by definition, the owner of all the sequences returned from USER_SEQUENCES
, there is no SEQUENCE_OWNER
column in USER_SEQUENCES
.
Most easiest way is to use ViewTreeObserver, if you directly use .height or .width you get values as 0, due to views are not have size until they draw on our screen. Following example will show how to use ViewTreeObserver
ViewTreeObserver viewTreeObserver = YOUR_VIEW_TO_MEASURE.getViewTreeObserver();
if (viewTreeObserver.isAlive()) {
viewTreeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
YOUR_VIEW_TO_MEASURE.getViewTreeObserver().removeOnGlobalLayoutListener(this);
int viewHeight = YOUR_VIEW_TO_MEASURE.getHeight();
int viewWeight = YOUR_VIEW_TO_MEASURE.getWidth();
}
});
}
if you need to use this on method, use like this and to save the values you can use globle variables.
I found an easy way, which has a few restrictions, but worked for me:
Here a working example:
<svg width="240" height="240" viewBox="0 0 1024 1024">_x000D_
<defs>_x000D_
<path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>_x000D_
<clipPath id="clip">_x000D_
<use xlink:href="#ld"/>_x000D_
</clipPath>_x000D_
</defs>_x000D_
<g>_x000D_
<use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="#00D2B8" clip-path="url(#clip)"/>_x000D_
</g>_x000D_
</svg>
_x000D_
redsquare's solution is the right answer.
But as an IN-THEORY solution you can write a function which is selecting the elements classed by .visibilityCheck
(not all visible elements) and check their visibility
property value; if true
then do something.
Afterward, the function should be performed periodically using the setInterval()
function. You can stop the timer using the clearInterval()
upon successful call-out.
Here's an example:
function foo() {
$('.visibilityCheck').each(function() {
if ($(this).is(':visible')){
// do something
}
});
}
window.setInterval(foo, 100);
You can also perform some performance improvements on it, however, the solution is basically absurd to be used in action. So...
Even shorter and with json-functions:
JSONObject songsObject = json.getJSONObject("songs");
JSONArray songsArray = songsObject.toJSONArray(songsObject.names());
In case that you want to display in your <div>
some kind of popUp message on screen center - then you don't need to read size of <div>
but you can use flex
.box {
width: 50px;
height: 20px;
background: red;
}
.container {
display: flex;
justify-content: center;
align-items: center;
height: 100vh;
width: 100vw;
position: fixed; /* remove this in case there is no content under div (and remember to set body margins to 0)*/
}
_x000D_
<div class="container">
<div class="box">My div</div>
</div>
_x000D_
You can compare the length of the string with one where the commas are removed:
len(value) - len(replace(value,',',''))
Assuming you have already downloaded Jdk 1.8. You have to make sure your eclipse version supports Jdk 1.8. Click on "Help" tab and then select "Check for Updates". Try again.
There is the easy way
HTML:
<input type="checkbox" name="test[]" />x
<input type="checkbox" name="test[]" />y
<input type="checkbox" name="test[]" />z
<button type="button" id="submit">Submit</button>
JQUERY:
$("#submit").on("click",function(){
if (($("input[name*='test']:checked").length)<=0) {
alert("You must check at least 1 box");
}
return true;
});
For this you not need any plugin. Enjoy;)
Sending data from formfields back to the server (php) is usualy done by the POST method which can be found back in the superglobal array $_POST inside PHP. There is no need to transform it to JSON before you send it to the server. Little example:
<?php
if($_SERVER['REQUEST_METHOD'] == 'POST')
{
echo '<pre>';
print_r($_POST);
}
?>
<form action="" method="post">
<input type="text" name="email" value="[email protected]" />
<button type="submit">Send!</button>
With AJAX you are able to do exactly the same thing, only without page refresh.
Instant stop =
myUtilDateStart.toInstant()
.plus( Duration.ofMinutes( x ) )
;
Other Answers are correct, especially the Answer by Borgwardt. But those Answers use outmoded legacy classes.
The original date-time classes bundled with Java have been supplanted with java.time classes. Perform your business logic in java.time types. Convert to the old types only where needed to work with old code not yet updated to handle java.time types.
If your Calendar
is actually a GregorianCalendar
you can convert to a ZonedDateTime
. Find new methods added to the old classes to facilitate conversion to/from java.time types.
if( myUtilCalendar instanceof GregorianCalendar ) {
GregorianCalendar gregCal = (GregorianCalendar) myUtilCalendar; // Downcasting from the interface to the concrete class.
ZonedDateTime zdt = gregCal.toZonedDateTime(); // Create `ZonedDateTime` with same time zone info found in the `GregorianCalendar`
end if
If your Calendar
is not a Gregorian
, call toInstant
to get an Instant
object. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds.
Instant instant = myCal.toInstant();
Similarly, if starting with a java.util.Date
object, convert to an Instant
. The Instant
class represents a moment on the timeline in UTC with a resolution of nanoseconds (up to nine (9) digits of a decimal fraction).
Instant instant = myUtilDate.toInstant();
Apply a time zone to get a ZonedDateTime
.
ZoneId z = ZoneId.of( "America/Montreal" );
ZonedDateTime zdt = instant.atZone( z );
To get a java.util.Date
object, go through the Instant
.
java.util.Date utilDate = java.util.Date.from( zdt.toInstant() );
For more discussion of converting between the legacy date-time types and java.time, and a nifty diagram, see my Answer to another Question.
Duration
Represent the span of time as a Duration
object. Your input for the duration is a number of minutes as mentioned in the Question.
Duration d = Duration.ofMinutes( yourMinutesGoHere );
You can add that to the start to determine the stop.
Instant stop = startInstant.plus( d );
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 java.time.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
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.
Several of the answers mention that you can use JNI or JNA to access cpython but I would not recommend starting from scratch because there are already open source libraries for accessing cpython from java. For example:
Open your PDF in Google Chrome. Edit the PDF as you want. Hit ctrl + p. Save as PDF to your desktop.
You can use Android Material Components.
build.gradle:
implementation 'com.google.android.material:material:1.0.0'
layout.xml:
<com.google.android.material.button.MaterialButtonToggleGroup
android:id="@+id/toggleGroup"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:checkedButton="@id/btn_one_way"
app:singleSelection="true">
<Button
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:id="@+id/btn_one_way"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="One way trip" />
<Button
style="@style/Widget.MaterialComponents.Button.OutlinedButton"
android:id="@+id/btn_round"
android:layout_width="0dp"
android:layout_weight="1"
android:layout_height="wrap_content"
android:text="Round trip" />
</com.google.android.material.button.MaterialButtonToggleGroup>
Some others not mentioned here -
Mono Cecil: With Cecil, you can load existing managed assemblies, browse all the contained types, modify them on the fly and save back to the disk the modified assembly.
Kaliro: This is a tool for exploring the content of applications built using the Microsoft.Net framework.
Dotnet IL Editor (DILE): Dotnet IL Editor (DILE) allows disassembling and debugging .NET 1.0/1.1/2.0/3.0/3.5 applications without source code or .pdb files. It can debug even itself or the assemblies of the .NET Framework on IL level.
Common Compiler Infrastructure: Microsoft Research Common Compiler Infrastructure (CCI) is a set of libraries and an application programming interface (API) that supports some of the functionality that is common to compilers and related programming tools. CCI is used primarily by applications that create, modify or analyze .NET portable executable (PE) and debug (PDB) files.
There is also a property resourceRef
of JndiObjectFactoryBean
that is, when set to true
, used to automatically prepend the string java:comp/env/
if it is not already present.
<bean id="someId" class="org.springframework.jndi.JndiObjectFactoryBean">
<property name="jndiName" value="jdbc/loc"/>
<property name="resourceRef" value="true"/>
</bean>
Duration in seconds using Python 2.7 and the YouTube API v3:
try:
dur = entry['contentDetails']['duration']
try:
minutes = int(dur[2:4]) * 60
except:
minutes = 0
try:
hours = int(dur[:2]) * 60 * 60
except:
hours = 0
secs = int(dur[5:7])
print hours, minutes, secs
video.duration = hours + minutes + secs
print video.duration
except Exception as e:
print "Couldnt extract time: %s" % e
pass
I'm not sure precisely what you're looking for, but this program:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public StatusType Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = Building.StatusType.open },
new Building () { Name = "two", Status = Building.StatusType.closed },
new Building () { Name = "three", Status = Building.StatusType.weird },
new Building () { Name = "four", Status = Building.StatusType.open },
new Building () { Name = "five", Status = Building.StatusType.closed },
new Building () { Name = "six", Status = Building.StatusType.weird },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var q = from building in buildingList
where statusList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
}
produces the expected output:
one: open
two: closed
four: open
five: closed
This program compares a string representation of the enum and produces the same output:
public class Building
{
public enum StatusType
{
open,
closed,
weird,
};
public string Name { get; set; }
public string Status { get; set; }
}
public static List <Building> buildingList = new List<Building> ()
{
new Building () { Name = "one", Status = "open" },
new Building () { Name = "two", Status = "closed" },
new Building () { Name = "three", Status = "weird" },
new Building () { Name = "four", Status = "open" },
new Building () { Name = "five", Status = "closed" },
new Building () { Name = "six", Status = "weird" },
};
static void Main (string [] args)
{
var statusList = new List<Building.StatusType> () { Building.StatusType.open, Building.StatusType.closed };
var statusStringList = statusList.ConvertAll <string> (st => st.ToString ());
var q = from building in buildingList
where statusStringList.Contains (building.Status)
select building;
foreach ( var b in q )
Console.WriteLine ("{0}: {1}", b.Name, b.Status);
Console.ReadKey ();
}
I created this extension method to convert one IEnumerable to another, but I'm not sure how efficient it is; it may just create a list behind the scenes.
public static IEnumerable <TResult> ConvertEach (IEnumerable <TSource> sources, Func <TSource,TResult> convert)
{
foreach ( TSource source in sources )
yield return convert (source);
}
Then you can change the where clause to:
where statusList.ConvertEach <string> (status => status.GetCharValue()).
Contains (v.Status)
and skip creating the List<string>
with ConvertAll ()
at the beginning.
I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.
It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.
To improve upon @arnorhs answer I've added in the ability to have a more precise result so if you wanted years, months, days & hours for instance since the user joined.
I've added a new parameter to allow you to specify the number of points of precision you wish to have returned.
function get_friendly_time_ago($distant_timestamp, $max_units = 3) {
$i = 0;
$time = time() - $distant_timestamp; // to get the time since that moment
$tokens = [
31536000 => 'year',
2592000 => 'month',
604800 => 'week',
86400 => 'day',
3600 => 'hour',
60 => 'minute',
1 => 'second'
];
$responses = [];
while ($i < $max_units && $time > 0) {
foreach ($tokens as $unit => $text) {
if ($time < $unit) {
continue;
}
$i++;
$numberOfUnits = floor($time / $unit);
$responses[] = $numberOfUnits . ' ' . $text . (($numberOfUnits > 1) ? 's' : '');
$time -= ($unit * $numberOfUnits);
break;
}
}
if (!empty($responses)) {
return implode(', ', $responses) . ' ago';
}
return 'Just now';
}
Simply add the eventhandler to the button when creating it.
button.Click += new EventHandler(this.button_Click);
void button_Click(object sender, System.EventArgs e)
{
//your stuff...
}
You can also use debug(function)
, to break when function
is called.
Light red fill with dark red text.
{'bg_color': '#FFC7CE', 'font_color': '#9C0006'})
Light yellow fill with dark yellow text.
{'bg_color': '#FFEB9C', 'font_color': '#9C6500'})
Green fill with dark green text.
{'bg_color': '#C6EFCE', 'font_color': '#006100'})
Use the Date.prototype.setFullYear method to set the year to what you want it to be.
For example:
var aYearFromNow = new Date();
aYearFromNow.setFullYear(aYearFromNow.getFullYear() + 1);
There really isn't another way to work with dates in JavaScript if these methods aren't present in the environment you are working with.
The question is how to call a C function from Python, if I understood correctly. Then the best bet are Ctypes (BTW portable across all variants of Python).
>>> from ctypes import *
>>> libc = cdll.msvcrt
>>> print libc.time(None)
1438069008
>>> printf = libc.printf
>>> printf("Hello, %s\n", "World!")
Hello, World!
14
>>> printf("%d bottles of beer\n", 42)
42 bottles of beer
19
For a detailed guide you may want to refer to my blog article.
The @Transactional
annotation takes a timeout parameter where you can specify timeout in seconds for a specific method in the @RestController
@RequestMapping(value = "/method",
method = RequestMethod.POST,
produces = MediaType.APPLICATION_JSON_VALUE)
@Timed
@Transactional(timeout = 120)
time.time()
may only give resolution to the second, the preferred approach for milliseconds is datetime
.
from datetime import datetime
dt = datetime.now()
dt.microsecond
SELECT
o.name
FROM
sys.sql_modules sm
INNER JOIN sys.objects o ON
o.object_id = sm.object_id
WHERE
sm.definition LIKE '%<table name>%'
Just keep in mind that this will also turn up SPs where the table name is in the comments or where the table name is a substring of another table name that is being used. For example, if you have tables named "test" and "test_2" and you try to search for SPs with "test" then you'll get results for both.
This is important information that I found on fragments:
Historically each screen in an Android app was implemented as a separate Activity. This creates a challenge in passing information between screens because the Android Intent mechanism does not allow passing a reference type (i.e. object) directly between Activities. Instead the object must be serialized or a globally accessible reference made available.
By making each screen a separate Fragment, this data passing headache is completely avoided. Fragments always exist within the context of a given Activity and can always access that Activity. By storing the information of interest within the Activity, the Fragment for each screen can simply access the object reference through the Activity.
Source: https://www.pluralsight.com/blog/software-development/android-fragments
To accessing member functions or variables from one scope to another scope (In your case one method to another method we need to refer method or variable with class object. and you can do it by referring with self keyword which refer as class object.
class YourClass():
def your_function(self, *args):
self.callable_function(param) # if you need to pass any parameter
def callable_function(self, *params):
print('Your param:', param)
I think some concepts from "Advanced Unix Programming" by Marc Rochkind were helpful in understanding the different roles of fork()
/exec()
, especially for someone used to the Windows CreateProcess()
model:
A program is a collection of instructions and data that is kept in a regular file on disk. (from 1.1.2 Programs, Processes, and Threads)
.
In order to run a program, the kernel is first asked to create a new process, which is an environment in which a program executes. (also from 1.1.2 Programs, Processes, and Threads)
.
It’s impossible to understand the exec or fork system calls without fully understanding the distinction between a process and a program. If these terms are new to you, you may want to go back and review Section 1.1.2. If you’re ready to proceed now, we’ll summarize the distinction in one sentence: A process is an execution environment that consists of instruction, user-data, and system-data segments, as well as lots of other resources acquired at runtime, whereas a program is a file containing instructions and data that are used to initialize the instruction and user-data segments of a process. (from 5.3
exec
System Calls)
Once you understand the distinction between a program and a process, the behavior of fork()
and exec()
function can be summarized as:
fork()
creates a duplicate of the current processexec()
replaces the program in the current process with another program(this is essentially a simplified 'for dummies' version of paxdiablo's much more detailed answer)
One thing json
cannot do is dict
indexed with numerals. The following snippet
import json
dictionary = dict({0:0, 1:5, 2:10})
serialized = json.dumps(dictionary)
unpacked = json.loads(serialized)
print(unpacked[0])
will throw
KeyError: 0
Because keys are converted to strings. cPickle
preserves the numeric type and the unpacked dict
can be used right away.
Make your size a factor in your dataframe by:
temp$size_f = factor(temp$size, levels=c('50%','100%','150%','200%'))
Then change the facet_grid(.~size)
to facet_grid(.~size_f)
Then plot:
The graphs are now in the correct order.
UPDATE 2017:
In C++17 there is now an official way to list files of your file system: std::filesystem
. There is an excellent answer from Shreevardhan below with this source code:
#include <string>
#include <iostream>
#include <filesystem>
namespace fs = std::filesystem;
int main()
{
std::string path = "/path/to/directory";
for (const auto & entry : fs::directory_iterator(path))
std::cout << entry.path() << std::endl;
}
Old Answer:
In small and simple tasks I do not use boost, I use dirent.h which is also available for windows:
DIR *dir;
struct dirent *ent;
if ((dir = opendir ("c:\\src\\")) != NULL) {
/* print all the files and directories within directory */
while ((ent = readdir (dir)) != NULL) {
printf ("%s\n", ent->d_name);
}
closedir (dir);
} else {
/* could not open directory */
perror ("");
return EXIT_FAILURE;
}
It is just a small header file and does most of the simple stuff you need without using a big template-based approach like boost(no offence, I like boost!).
The author of the windows compatibility layer is Toni Ronkko. In Unix, it is a standard header.
You should set the src
attribute after the onload
event, f.ex:
el.onload = function() { //...
el.src = script;
You should also append the script to the DOM before attaching the onload
event:
$body.append(el);
el.onload = function() { //...
el.src = script;
Remember that you need to check readystate
for IE support. If you are using jQuery, you can also try the getScript()
method: http://api.jquery.com/jQuery.getScript/
IMPORTANT: Just to make something clear. I assume that the commands are inside a .py
script and the script is called using e.g. python script.py
from the console.
A simple way that works for me is:
Example of script.py
file:
plt.imshow(*something*)
plt.colorbar()
plt.xlabel("true ")
plt.ylabel("predicted ")
plt.title(" the matrix")
# Add block = False
plt.show(block = False)
################################
# OTHER CALCULATIONS AND CODE HERE ! ! !
################################
# the next command is the last line of my script
plt.show()
Expanding on some other answers, this is what I do:
Setup the repo: git clone --mirror user@server:/url-to-repo.git
Then when you want to refresh the backup: git remote update
from the clone location.
This backs up all branches and tags, including new ones that get added later, although it's worth noting that branches that get deleted do not get deleted from the clone (which for a backup may be a good thing).
This is atomic so doesn't have the problems that a simple copy would.
You can use MutationObserver to track attribute changes including data-*
changes. For example:
var foo = document.getElementById('foo');_x000D_
_x000D_
var observer = new MutationObserver(function(mutations) {_x000D_
console.log('data-select-content-val changed');_x000D_
});_x000D_
observer.observe(foo, { _x000D_
attributes: true, _x000D_
attributeFilter: ['data-select-content-val'] });_x000D_
_x000D_
foo.dataset.selectContentVal = 1;
_x000D_
<div id='foo'></div>_x000D_
_x000D_
What you really want to do is use an XML parser and append the new elements with the API provided.
Then simply overwrite the file.
The easiest to use would probably be a DOM parser like the one below:
Same as answers by user5542464 and Piyush S. Wanare but split in two steps:
pg_dump -U Username -h DatabaseEndPoint -a -t TableToCopy SourceDatabase > dump
cat dump | psql -h DatabaseEndPoint -p portNumber -U Username -W TargetDatabase
otherwise the pipe asks the two passwords in the same time.
Well, .html()
uses .innerHTML
which is faster than DOM creation.
To convert a datetime object that represents time in UTC to POSIX timestamp:
from datetime import timezone
seconds_since_epoch = utc_time.replace(tzinfo=timezone.utc).timestamp()
To convert a datetime object that represents time in the local timezone to POSIX timestamp:
import tzlocal # $ pip install tzlocal
local_timezone = tzlocal.get_localzone()
seconds_since_epoch = local_timezone.localize(local_time, is_dst=None).timestamp()
See How do I convert local time to UTC in Python? If the tz database is available on a given platform; a stdlib-only solution may work.
Follow the links if you need solutions for <3.3
Python versions.
I'd like to expand on Obertklep's answer. In his example it is an NPM module called body-parser
which is doing most of the work. Where he puts req.body.name
, I believe he/she is using body-parser
to get the contents of the name attribute(s) received when the form is submitted.
If you do not want to use Express, use querystring
which is a built-in Node module. See the answers in the link below for an example of how to use querystring
.
It might help to look at this answer, which is very similar to your quest.
Many recommend that increasing recursion limit is a good solution however it is not because there will be always limit. Instead use an iterative solution.
def fib(n):
a,b = 1,1
for i in range(n-1):
a,b = b,a+b
return a
print fib(5)
This one worked in my python script:
print "\t%-5s %-10s %-10s %-10s %-10s %-10s %-20s" % (thread[0],thread[1],thread[2],thread[3],thread[4],thread[5],thread[6])
Here's a quick overview:
One last thing: If you declare Foo foo;
without assigning it you don't have to worry - nothing is leaked. If Foo is a reference type, nothing was created. If Foo is a value type, it is allocated on the stack and thus will automatically be cleaned up.
Add height & width properties to your .css file.
Using SPEL and P-NAMESPACE:
<beans...
xmlns:p="http://www.springframework.org/schema/p" ...>
..
<bean name="someName" class="my.pkg.classes"
p:type="#{T(my.pkg.types.MyEnumType).TYPE1}"/>
create layout dynamically and set its parameter as setmargin() will not work directly on an imageView
ImageView im;
im = (ImageView) findViewById(R.id.your_image_in_XML_by_id);
RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(im.getLayoutParams());
layout.setMargins(counter*27, 0, 0, 0);//left,right,top,bottom
im.setLayoutParams(layout);
im.setImageResource(R.drawable.yourimage)
Please note that since Spring Boot 1.3.0.M1, you are able to build fully executable jars using Maven and Gradle.
For Maven, just include the following in your pom.xml
:
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
<configuration>
<executable>true</executable>
</configuration>
</plugin>
For Gradle add the following snippet to your build.gradle
:
springBoot {
executable = true
}
The fully executable jar contains an extra script at the front of the file, which allows you to just symlink your Spring Boot jar to init.d
or use a systemd
script.
init.d
example:
$ln -s /var/yourapp/yourapp.jar /etc/init.d/yourapp
This allows you to start, stop and restart your application like:
$/etc/init.d/yourapp start|stop|restart
Or use a systemd
script:
[Unit]
Description=yourapp
After=syslog.target
[Service]
ExecStart=/var/yourapp/yourapp.jar
User=yourapp
WorkingDirectory=/var/yourapp
SuccessExitStatus=143
[Install]
WantedBy=multi-user.target
More information at the following links:
On .Net Core 3.1 we just need to do these:
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
}
Using SeriLog will look like:
using Microsoft.Extensions.Configuration;
using Serilog;
using System;
namespace yournamespace
{
class Program
{
static void Main(string[] args)
{
var configuration = new ConfigurationBuilder().AddJsonFile("appsettings.json").Build();
Log.Logger = new LoggerConfiguration().ReadFrom.Configuration(configuration).CreateLogger();
try
{
Log.Information("Starting Program.");
}
catch (Exception ex)
{
Log.Fatal(ex, "Program terminated unexpectedly.");
return;
}
finally
{
Log.CloseAndFlush();
}
}
}
}
And the Serilog appsetings.json section for generating one file daily will look like:
"Serilog": {
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"System": "Warning"
}
},
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"WriteTo": [
{
"Name": "File",
"Args": {
"path": "C:\\Logs\\Program.json",
"rollingInterval": "Day",
"formatter": "Serilog.Formatting.Compact.CompactJsonFormatter, Serilog.Formatting.Compact"
}
}
]
}
If you want to use the MAX(id) instead of the count, after reading the comments from Pax then the following SQL will give you what you want
SELECT COALESCE(MAX(id)+1, 0) FROM words
char **orderIds;
orderIds = malloc(variableNumberOfElements * sizeof(char*));
for(int i = 0; i < variableNumberOfElements; i++) {
orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
strcpy(orderIds[i], your_string[i]);
}
As quoted above, "If you don't test your private methods, how do you know they won't break?"
This is a major issue. One of the big points of unit tests is to know where, when, and how something broke ASAP. Thus decreasing a significant amount of development & QA effort. If all that is tested is the public, then you don't have honest coverage and delineation of the internals of the class.
I've found one of the best ways to do this is simply add the test reference to the project and put the tests in a class parallel to the private methods. Put in the appropriate build logic so that the tests don't build into the final project.
Then you have all the benefits of having these methods tested and you can find problems in seconds versus minutes or hours.
So in summary, yes, unit test your private methods.
Try selecting the default mode as Internet connection.
Go to Settings -> Connectivity -> Default Mode -> Internet Connection.
Now enable the USB Debugging mode under Applications -> Development -> USB Debugging.
It worked for me.
To get the value from the servlet from POST
command, you can follow the approach as explained on this post by using request.getParameter(key)
format which will return the value you want.
Just for completeness (and this is not at all recommended):
int length;
try
{
length = str.getBytes("UTF-16BE").length / 2
}
catch (UnsupportedEncodingException e)
{
throw new AssertionError("Cannot happen: UTF-16BE is always a supported encoding");
}
This works because a char
is a UTF-16 code unit, and str.length()
returns the number of such code units. Each UTF-16 code unit takes up 2 bytes, so we divide by 2. Additionally, there is no byte order mark written with UTF-16BE.
Have you tried logging in as the jenkins user?
Try this:
sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git
Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.
If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?
What really makes me feel bad about mocking abstract classes is the fact, that neither the default constructor YourAbstractClass()
gets called (missing super()
in mock) nor seems there to be any way in Mockito to default initialize mock properties (e.g List
properties with empty ArrayList
or LinkedList
).
My abstract class (basically the class source code gets generated) does NOT provide a dependency setter injection for list elements, nor a constructor where it initializes the list elements (which I tried to add manually).
Only the class attributes use default initialization:
private List<MyGenType> dep1 = new ArrayList<MyGenType>();
private List<MyGenType> dep2 = new ArrayList<MyGenType>();
So there is NO way to mock an abstract class without using a real object implementation (e.g inner class definition in unit test class, overriding abstract methods) and spying the real object (which does proper field initialization).
Too bad that only PowerMock would help here further.
Live example of Curl command to send OPTIONS requests: https://reqbin.com/req/c-d8nxa0fl
BLOB is for binary data (videos, images, documents, other)
CLOB is for large text data (text)
Maximum size on MySQL 2GB
Maximum size on Oracle 128TB
Inside the component, create a computed function
computed:{
myState:function(){
return this.$store.state.my_state; // return the state value in `my_state`
}
}
Now the computed function name can be watched, like
watch:{
myState:function(newVal,oldVal){
// this function will trigger when ever the value of `my_state` changes
}
}
The changes made in the vuex
state my_state
will reflect in the computed function myState
and trigger the watch function.
If the state my_state
is having nested data, then the handler
option will help more
watch:{
myState:{
handler:function(newVal,oldVal){
// this function will trigger when ever the value of `my_state` changes
},
deep:true
}
}
This will watch all the nested values in the store my_state
.
This is the unsorted list and we want is 1234567
list = [3,1,2,5,4,7,6]
def sort(list):
for i in range(len(list)-1):
if list[i] > list[i+1]:
a = list[i]
list[i] = list[i+1]
list[i+1] = a
print(list)
sort(list)
simplest in simplest method to sort a array. Im using currently bubble sorting that is: it checks first 2 location and moves the smallest number to left so on. "-n"in loop is to avoid the indentation error you will understand it by doing it so.
string stringToDecrypt = CypherText.Replace(" ", "+");
int len = stringToDecrypt.Length;
byte[] inputByteArray = Convert.FromBase64String(stringToDecrypt);
You need to parse your time format using strptime.
>>> import time
>>> from datetime import datetime
>>> ts, ms = '20.12.2016 09:38:42,76'.split(',')
>>> ts
'20.12.2016 09:38:42'
>>> ms
'76'
>>> dt = datetime.strptime(ts, '%d.%m.%Y %H:%M:%S')
>>> time.mktime(dt.timetuple())*1000 + int(ms)*10
1482223122760.0
Iterating over a dictionary object itself actually gives you an iterator over its keys. Python is trying to unpack keys, which you get from m.type + m.purity
into (m, k)
.
My crystal ball says m.type
and m.purity
are both strings, so your keys are also strings. Strings are iterable, so they can be unpacked; but iterating over the string gives you an iterator over its characters. So whenever m.type + m.purity
is more than two characters long, you have too many values to unpack. (And whenever it's shorter, you have too few values to unpack.)
To fix this, you can iterate explicitly over the items
of the dict, which are the (key, value) pairs that you seem to be expecting. But if you only want the values, then just use the values.
(In 2.x, itervalues
, iterkeys
, and iteritems
are typically a better idea; the non-iter
versions create a new list object containing the values/keys/items. For large dictionaries and trivial tasks within the iteration, this can be a lot slower than the iter
versions which just set up an iterator.)
For Bootstrap:
<div class="navbar-fixed-bottom row-fluid">
<div class="navbar-inner">
<div class="container">
Text
</div>
</div>
</div>
confirmed only that method work now:
newVersion = Jsoup.connect("https://play.google.com/store/apps/details?id=" + AcMainPage.this.getPackageName() + "&hl=it")
.timeout(30000)
.userAgent("Mozilla/5.0 (Windows; U; WindowsNT 5.1; en-US; rv1.8.1.6) Gecko/20070725 Firefox/2.0.0.6")
.referrer("http://www.google.com")
.get()
.select(".hAyfc .htlgb")
.get(5)
.ownText();
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
Use ng-show
and toggle the value of a show
scope variable in the ng-click
handler.
Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/
<ul class="procedures">
<li ng-repeat="procedure in procedures">
<h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
<div class="procedure-details" ng-show="show">
<p>Number of patient discharges: {{procedure.discharges}}</p>
<p>Average amount covered by Medicare: {{procedure.covered}}</p>
<p>Average total payments: {{procedure.payments}}</p>
</div>
</li>
</ul>
How I update my deviceToken
First when I login I send the first device token under the user collection and the current logged in user.
After that, I just override onNewToken(token:String)
in my FirebaseMessagingService()
and just update that value if a new token is generated for that user
class MyFirebaseMessagingService: FirebaseMessagingService() {
override fun onMessageReceived(p0: RemoteMessage) {
super.onMessageReceived(p0)
}
override fun onNewToken(token: String) {
super.onNewToken(token)
val currentUser= FirebaseAuth.getInstance().currentUser?.uid
if(currentUser != null){
FirebaseFirestore.getInstance().collection("user").document(currentUser).update("deviceToken",token)
}
}
}
Each time your app opens it will check for a new token, if the user is not yet signed in it will not update the token, if the user is already logged in you can check for a newToken
Paths specified with a .
are relative to the current working directory, not relative to the script file. So the file might be found if you run node app.js
but not if you run node folder/app.js
. The only exception to this is require('./file')
and that is only possible because require
exists per-module and thus knows what module it is being called from.
To make a path relative to the script, you must use the __dirname
variable.
var path = require('path');
path.join(__dirname, 'path/to/file')
or potentially
path.join(__dirname, 'path', 'to', 'file')
In Windows debug.keystore
file is localtes at C:\Users\%Username%\.android
folder. This file is created when you install your android SDK and is valid only for a year. After this perod you will start getting this error Error getting final archive: Debug certificate expired on xx/xx/xxxx
.
To remove this error simply delete the file and run the program again. In my Eclipse I have enabled Project->Build Automatically
so it directly worked but in case you have disabled it you will need to clean the project Project->Clean
.. select your project and press ok. Then you will need to build it manually. 3rd click on your project and select Build project
.(Note - You will only see this option if you have diabled Build Automatically feature in your Projects Menu)
QuerySelectorAll will get all the matching elements with defined selector. Here on the example I've used element's name(li
tag) to get all of the li
present inside the div with navbar
element.
let navbar = document_x000D_
.getElementById("navbar")_x000D_
.querySelectorAll('li');_x000D_
_x000D_
navbar.forEach((item, index) => {_x000D_
console.log({ index, item })_x000D_
});
_x000D_
_x000D_
<div id="navbar">_x000D_
<ul>_x000D_
<li id="navbar-One">One</li>_x000D_
<li id="navbar-Two">Two</li>_x000D_
<li id="navbar-Three">Three</li>_x000D_
<li id="navbar-Four">Four</li>_x000D_
<li id="navbar-Five">Five</li>_x000D_
</ul>_x000D_
</div>
_x000D_
When you run the Windows Command Prompt, and type in python
, it starts the Python interpreter.
Typing it again tries to interpret python
as a variable, which doesn't exist and thus won't work:
Microsoft Windows [Version 6.1.7601]
Copyright (c) 2009 Microsoft Corporation. All rights reserved.
C:\Users\USER>python
Python 2.7.5 (default, May 15 2013, 22:43:36) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> python
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'python' is not defined
>>> print("interpreter has started")
interpreter has started
>>> quit() # leave the interpreter, and go back to the command line
C:\Users\USER>
If you're not doing this from the command line, and instead running the Python interpreter (python.exe or IDLE's shell) directly, you are not in the Windows Command Line, and python
is interpreted as a variable, which you have not defined.
The 2nd parameter in the get
call is a config object. You want something like this:
$http
.get('accept.php', {
params: {
source: link,
category_id: category
}
})
.success(function (data,status) {
$scope.info_show = data
});
See the Arguments section of http://docs.angularjs.org/api/ng.$http for more detail
Not all phones and versions of android have things mounted the same.
Limiting options when remounting would be best.
Simply remount as rw (Read/Write):
# mount -o rw,remount /system
Once you are done making changes, remount to ro (read-only):
# mount -o ro,remount /system
if you use mvvm and your itemssource is located in your vm. just call INotifyPropertyChanged for your collection property when you want to refresh.
OnPropertyChanged("YourCollectionProperty");
i entered in Mysql Workbench and i changed the password. It seem the password was expired. it works!
I'm guessing that you're referring to the fact that you often have to put a 'return false;' statement in your event handlers, i.e.
<a href="#" onclick="doSomeFunction(); return false;">...
The 'return false;' in this case stops the browser from jumping to the current location, as indicated by the href="#" - instead, only doSomeFunction() is executed. It's useful for when you want to add events to anchor tags, but don't want the browser jumping up and down to each anchor on each click
There are already lots of good answers but I have come up with a function called get similar to lodash get in JavaScript land that also supports reaching into lists by index:
def get(value, keys, default_value = None):
'''
Useful for reaching into nested JSON like data
Inspired by JavaScript lodash get and Clojure get-in etc.
'''
if value is None or keys is None:
return None
path = keys.split('.') if isinstance(keys, str) else keys
result = value
def valid_index(key):
return re.match('^([1-9][0-9]*|[0-9])$', key) and int(key) >= 0
def is_dict_like(v):
return hasattr(v, '__getitem__') and hasattr(v, '__contains__')
for key in path:
if isinstance(result, list) and valid_index(key) and int(key) < len(result):
result = result[int(key)] if int(key) < len(result) else None
elif is_dict_like(result) and key in result:
result = result[key]
else:
result = default_value
break
return result
def test_get():
assert get(None, ['foo']) == None
assert get({'foo': 1}, None) == None
assert get(None, None) == None
assert get({'foo': 1}, []) == {'foo': 1}
assert get({'foo': 1}, ['foo']) == 1
assert get({'foo': 1}, ['bar']) == None
assert get({'foo': 1}, ['bar'], 'the default') == 'the default'
assert get({'foo': {'bar': 'hello'}}, ['foo', 'bar']) == 'hello'
assert get({'foo': {'bar': 'hello'}}, 'foo.bar') == 'hello'
assert get({'foo': [{'bar': 'hello'}]}, 'foo.0.bar') == 'hello'
assert get({'foo': [{'bar': 'hello'}]}, 'foo.1') == None
assert get({'foo': [{'bar': 'hello'}]}, 'foo.1.bar') == None
assert get(['foo', 'bar'], '1') == 'bar'
assert get(['foo', 'bar'], '2') == None
How about overriding the onDraw method and then painting lines to the canvas?
for(int i = 0; i < rows; i++)
{
canvas.drawLine(0, i * m_cellHeight, m_totalWidth, i * m_cellHeight, paint);
}
for(int i = 0; i < m_columns; i++){
canvas.drawLine(i* m_cellWidth, 0, i * m_cellWidth, m_cellHeight * rows, paint);
}
The best solution for this is to create a simple parent pom file project (with packaging 'pom') generically for all projects from your organization.
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0-SNAPSHOT</version>
<packaging>pom</packaging>
<distributionManagement>
<repository>
<id>nexus-site</id>
<url>http://central_nexus/server</url>
</repository>
</distributionManagement>
</project>
This can be built, released, and deployed to your local nexus so everyone has access to its artifact.
Now for all projects which you wish to use it, simply include this section:
<parent>
<groupId>your.company</groupId>
<artifactId>company-parent</artifactId>
<version>1.0.0</version>
</parent>
This solution will allow you to easily add other common things to all your company's projects. For instance if you wanted to standardize your JUnit usage to a specific version, this would be the perfect place for that.
If you have projects that use multi-module structures that have their own parent, Maven also supports chaining inheritance so it is perfectly acceptable to make your project's parent pom file refer to your company's parent pom and have the project's child modules not even aware of your company's parent.
I see from your example project structure that you are attempting to put your parent project at the same level as your aggregator pom. If your project needs its own parent, the best approach I have found is to include the parent at the same level as the rest of the modules and have your aggregator pom.xml file at the root of where all your modules' directories exist.
- pom.xml (aggregator)
- project-parent
- project-module1
- project-module2
What you do with this structure is include your parent module in the aggregator and build everything with a mvn install
from the root directory.
We use this exact solution at my organization and it has stood the test of time and worked quite well for us.
You seem to be doing file name comparisons, so I would just add that OrdinalIgnoreCase
is closest to what NTFS does (it's not exactly the same, but it's closer than InvariantCultureIgnoreCase
)
I've made a jQuery plugin for the purpose of blinking notification messages in the browser title bar. You can specify different options like blinking interval, duration, if the blinking should stop when the window/tab gets focused, etc. The plugin works in Firefox, Chrome, Safari, IE6, IE7 and IE8.
Here is an example on how to use it:
$.titleAlert("New mail!", {
requireBlur:true,
stopOnFocus:true,
interval:600
});
If you're not using jQuery, you might still want to look at the source code (there are a few quirky bugs and edge cases that you need to work around when doing title blinking if you want to fully support all major browsers).
You forgot to include the stored procedure or function script for sp_ppinCamposIndice
From C++ Primer:
The istringstream type reads a string, ostringstream writes a string, and stringstream reads and writes the string.
I come across some cases where it is both convenient and concise to use stringstream.
It is from one of the solutions for this leetcode problem. It demonstrates a very suitable case where the use of stringstream is efficient and concise.
Suppose a
and b
are complex numbers expressed in string format, we want to get the result of multiplication of a
and b
also in string format. The code is as follows:
string a = "1+2i", b = "1+3i";
istringstream sa(a), sb(b);
ostringstream out;
int ra, ia, rb, ib;
char buff;
// only read integer values to get the real and imaginary part of
// of the original complex number
sa >> ra >> buff >> ia >> buff;
sb >> rb >> buff >> ib >> buff;
out << ra*rb-ia*ib << '+' << ra*ib+ia*rb << 'i';
// final result in string format
string result = out.str()
It is also from a leetcode problem that requires you to simplify the given path string, one of the solutions using stringstream is the most elegant that I have seen:
string simplifyPath(string path) {
string res, tmp;
vector<string> stk;
stringstream ss(path);
while(getline(ss,tmp,'/')) {
if (tmp == "" or tmp == ".") continue;
if (tmp == ".." and !stk.empty()) stk.pop_back();
else if (tmp != "..") stk.push_back(tmp);
}
for(auto str : stk) res += "/"+str;
return res.empty() ? "/" : res;
}
Without the use of stringstream, it would be difficult to write such concise code.
byte[] iso88591Data = theString.getBytes("ISO-8859-1");
Will do the trick. From your description it seems as if you're trying to "store an ISO-8859-1 String". String objects in Java are always implicitly encoded in UTF-16. There's no way to change that encoding.
What you can do, 'though is to get the bytes that constitute some other encoding of it (using the .getBytes()
method as shown above).
If anyone comes to this page looking to do this in a React-based client, you can do something like the below, which was an answer original provided by Sophia Alpert of the React team here
getInitialState: function(event) {
return {image: "http://example.com/primary_image.jpg"};
},
handleError: function(event) {
this.setState({image: "http://example.com/failover_image.jpg"});
},
render: function() {
return (
<img onError={this.handleError} src={src} />;
);
}
Maybe a little late, but using different drivers altogether is overkill for a case of user error:
db.dbConnect("jdbc:sqlserver://localhost:1433/muff", "user", "pw" );
should be either one of these:
db.dbConnect("jdbc:sqlserver://localhost\muff", "user", "pw" );
(using named pipe) or:
db.dbConnect("jdbc:sqlserver://localhost:1433", "user", "pw" );
using port number directly; you can leave out 1433 because it's the default port, leaving:
db.dbConnect("jdbc:sqlserver://localhost", "user", "pw" );
I have tried this and it is working fine for me:
sqlcmd -S servername -E -s~ -W -k1 -Q "sql query here" > "\\file_path\file_name.csv"
After hours of trying, the function is born :) I had a scenario where I had to display loader in time while the file is preparing for download:
Working in Chrome, Safari and Firefox
function ajaxDownload(url, filename = 'file', method = 'get', data = {}, callbackSuccess = () => {}, callbackFail = () => {}) {
$.ajax({
url: url,
method: 'GET',
xhrFields: {
responseType: 'blob'
},
success: function (data) {
// create link element
let a = document.createElement('a'),
url = window.URL.createObjectURL(data);
// initialize
a.href = url;
a.download = filename;
// append element to the body,
// a must, due to Firefox
document.body.appendChild(a);
// trigger download
a.click();
// delay a bit deletion of the element
setTimeout(function(){
window.URL.revokeObjectURL(url);
document.body.removeChild(a);
}, 100);
// invoke callback if any
callbackSuccess(data);
},
error: function (err) {
// invoke fail callback if any
callbackFail(err)
}
});
iOS 9 forces connections that are using HTTPS to be TLS 1.2 to avoid recent vulnerabilities. In iOS 8 even unencrypted HTTP connections were supported, so that older versions of TLS didn't make any problems either. As a workaround, you can add this code snippet to your Info.plist:
<key>NSAppTransportSecurity</key>
<dict>
<key>NSAllowsArbitraryLoads</key>
<true/>
</dict>
*referenced to App Transport Security (ATS)
Sometimes the value needs to be trimmed of whitespace or it won't be matched, in such case this additional step can be used (source):
if(((DropDownList) myControl1).Items.Cast<ListItem>().Select(i => i.Value.Trim() == ctrl.value.Trim()).FirstOrDefault() != null){}
You can use the GNLauncher, which is part of a utility library I wrote in cases where a lot of interaction with the Activity is required. With the library, it is almost as simple as calling a function on the Activity object with the required parameters. https://github.com/noxiouswinter/gnlib_android/wiki#gnlauncher
In my case, the file C:\Users\xxx\AppData\Local\PreEmptive Solutions\Dotfuscator Professional Edition\4.0\dfusrprf.xml
was full of NULL.
I deleted it; it was recreated on the first launch of Dotfuscator, and after that, normality was restored.
Get highlighted text this way:
window.getSelection().toString()
and of course a special treatment for ie:
document.selection.createRange().htmlText
you can easily resolve this problem by changing the port number of glassfish.
Go to glassfich configuration File domain.xml
which is located under GlassFish_Server\glassfish\domains\domain1\config
.
Open this file, then change the following line:
<network-listener port="8080" protocol="http-listener-1" transport="tcp"
name="http-listener-1" thread-pool="http-thread-pool"></network-listener>
replace 8080
by 9090
for example, then save file and run glassfish again.
it should nicely work.
In my case, I was referencing a library that was being built to the wrong Platform/Configuration (I had just created the referenced library).
Furthermore, I was unable to fix the problem in Visual Studio Configuration Manager -- unable to switch and create new Platforms and Configurations for this library. I fixed it by correcting the entries in the ProjectConfigurationPlatforms
section of the .sln
file for that project. All its permutations were set to Debug|Any CPU
(I'm not sure how I did that). I overwrote the entries for the broken project with the ones for a working project and changed the GUID for each entry.
Entries for functioning project
{9E93345C-7A51-4E9A-ACB0-DAAB8F1A1267}.Release|x64.ActiveCfg = Release|x64
{9E93345C-7A51-4E9A-ACB0-DAAB8F1A1267}.Release|x64.Build.0 = Release|x64
Entries for corrupted project
{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.ActiveCfg = Debug|Any CPU
{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.Build.0 = Debug|Any CPU
Corrupted entries now fixed
{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.ActiveCfg = Release|x64
{94562215-903C-47F3-BF64-8B90EF43FD27}.Release|x64.Build.0 = Release|x64
I hope this helps someone.
This answer is late, but I was having the same issue. I found something that works.
In eclipse Project Explorer, right click the project name -> select "Run As" -> "Maven Build..."
In the goals, enter spring-boot:run
then click Run button.
I have the STS plug-in (i.e. SpringSource Tool Suite), so on some projects I will get a "Spring Boot App" option under Run As. But, it doesn't always show up for some reason. I use the above workaround for those.
Here is a reference that explains how to run Spring boot apps:
Spring boot tutorial
I had trouble getting selectable to work with ASP.NET. It turns out I wasn't properly including everything, but this gentleman made it foolproof: Three steps to use jQuery UI in ASP.NET MVC 5.
When you want to loop into a multiple dimensions array, you can use foreach like this:
foreach($data as $users){
foreach($users as $user){
echo $user['id'].' '.$user['c_name'].' '.$user['seat_no'].'<br/>';
}
}
Generally if the installation went smoothly, it will create the desktop icons/folders. Maybe check the installation summary log to see if there's any underlying errors.
It should be located C:\Program Files\Microsoft SQL Server\100\Setup Bootstrap\Log(date stamp)\
I have made a very useful method to add a string in a certain position in Python:
def insertChar(mystring, position, chartoinsert ):
longi = len(mystring)
mystring = mystring[:position] + chartoinsert + mystring[position:]
return mystring
for example:
a = "Jorgesys was here!"
def insertChar(mystring, position, chartoinsert ):
longi = len(mystring)
mystring = mystring[:position] + chartoinsert + mystring[position:]
return mystring
#Inserting some characters with a defined position:
print(insertChar(a,0, '-'))
print(insertChar(a,9, '@'))
print(insertChar(a,14, '%'))
we will have as an output:
-Jorgesys was here!
Jorgesys @was here!
Jorgesys was h%ere!
Try using System.getProperty("line.separator")
to get a new line.
You can use Maven Version Manager through which you can use multiple version of Maven per directory base.
Installation
Using Homebrew brew install mvnvm
Without Homebrew mkdir -p ~/bin && curl -s https://bitbucket.org/mjensen/mvnvm/raw/master/mvn > ~/bin/mvn && chmod 0755 ~/bin/mvn
and add ~/bin
to path.
Usage
Default Version
To set default maven version set the environment variable DEFAULT_MVN_VERSION
to the maven version to be used by default.
Maven version for the folder
Create a file named mvnvm.properties
in the folder and configure the maven version as follows
mvn_version=<maven version>
It's because you're missing position:relative;
on #contentframe
<div id="contentframe" style="position:relative; top: 160px; left: 0px;">
position:absolute;
positions itself against the closest ancestor that has a position
that is not static
. Since the default is static
that is what was causing your issue.
same happened with me..
Problem was that Actually i deleted my Database table MoviesCast
and made new table and problem was that my last migration was trying to induce the deleted table MoviesCast
in the database.
I Solved it by simply removing all the content of last migration and simply ran Up() & down() method
public override void Up()
{
}
public override void Down()
{
}
then updated the database and simply add new migration
You can parse the pom file with JDOM (http://www.jdom.org/).
Try  
as per the docs :
The character entities
 
and 
denote an en space and an em space respectively, where an en space is half the point size and an em space is equal to the point size of the current font. For fixed pitch fonts, the user agent can treat the en space as being equivalent to A space character, and the em space as being equuivalent to two space characters.
Docs link : https://www.w3.org/MarkUp/html3/specialchars.html
You're checking the wrong method. Moq requires that you Setup (and then optionally Verify) the method in the dependency class.
You should be doing something more like this:
class MyClassTest
{
[TestMethod]
public void MyMethodTest()
{
string action = "test";
Mock<SomeClass> mockSomeClass = new Mock<SomeClass>();
mockSomeClass.Setup(mock => mock.DoSomething());
MyClass myClass = new MyClass(mockSomeClass.Object);
myClass.MyMethod(action);
// Explicitly verify each expectation...
mockSomeClass.Verify(mock => mock.DoSomething(), Times.Once());
// ...or verify everything.
// mockSomeClass.VerifyAll();
}
}
In other words, you are verifying that calling MyClass#MyMethod
, your class will definitely call SomeClass#DoSomething
once in that process. Note that you don't need the Times
argument; I was just demonstrating its value.
In Windows Forms:
this.StartPosition = FormStartPosition.CenterScreen;
In WPF:
this.WindowStartupLocation = WindowStartupLocation.CenterScreen;
That's all you have to do...
In PostgreSQL 9.1 there is an easier way
http://www.postgresql.org/message-id/[email protected]
CREATE TABLE foog(a varchar(10));
ALTER TABLE foog ALTER COLUMN a TYPE varchar(30);
postgres=# \d foog
Table "public.foog"
Column | Type | Modifiers
--------+-----------------------+-----------
a | character varying(30) |
As pointed out by Hawker65 in the comment of chepner answer, the most voted solution does neither take care of multiple extensions (such as filename.tar.gz), nor of dots in the rest of the path (such as this.path/with.dots/in.path.name). A possible solution is:
a=this.path/with.dots/in.path.name/filename.tar.gz
echo $(dirname $a)/$(basename $a | cut -d. -f1)
CAST(timestamp_expression AS DATE)
For example, The query is : SELECT CAST(SYSTIMESTAMP AS DATE) FROM dual;
First question:
Use the Intent to call another Activity. In the Manifest, you should add
<activity android:name="ListViewImage"></activity>
<activity android:name="com.company.listview.ListViewImage">
</activity>
And in your current activity,
btListe = (ImageButton)findViewById(R.id.Button_Liste);
btListe.setOnClickListener(new OnClickListener()
{ public void onClick(View v)
{
intent = new Intent(main.this, ListViewImage.class);
startActivity(intent);
finish();
}
});
Second question:
sendButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
String valueString = editValue.getText().toString();
long value;
if (valueString != null) {
value = Long.parseLong(valueString);
}
else {
value = 0;
}
Bundle sendBundle = new Bundle();
sendBundle.putLong("value", value);
Intent i = new Intent(Activity1.this, Activity2.class);
i.putExtras(sendBundle);
startActivity(i);
finish();
}
});
and in Activity2:
Bundle receiveBundle = this.getIntent().getExtras();
final long receiveValue = receiveBundle.getLong("value");
receiveValueEdit.setText(String.valueOf(receiveValue));
callReceiverButton.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent i = new Intent(Activity2.this, Receiver.class);
i.putExtra("new value", receiveValue - 10);
}
});
see my answer here:
How can I get the current date and time in UTC or GMT in Java?
I've fully tested it by changing the timezones on the emulator
By using itemStateChanged(ItemListener)
you can track selecting and deselecting checkbox (and do whatever you want based on it):
myCheckBox.addItemListener(new ItemListener() {
@Override
public void itemStateChanged(ItemEvent e) {
if(e.getStateChange() == ItemEvent.SELECTED) {//checkbox has been selected
//do something...
} else {//checkbox has been deselected
//do something...
};
}
});
Java Swing itemStateChanged docu should help too. By using isSelected()
method you can just test if actual is checkbox selected:
if(myCheckBox.isSelected()){_do_something_if_selected_}
Sleep() causes the currently executing thread to sleep (temporarily cease execution).
Yield() causes the currently executing thread object to temporarily pause and allow other threads to execute.
Read [this] (Link Removed) for a good explanation of the topic.
git show-ref --tags
For example, git show-ref --abbrev=7 --tags
will show you something like the following:
f727215 refs/tags/v2.16.0
56072ac refs/tags/v2.17.0
b670805 refs/tags/v2.17.1
250ed01 refs/tags/v2.17.2
My own tests conclusively show that br
tags do not like to be targeted for css.
But if you can add style then you can probably also add a scrip tag to the header of the page?
Link to an external .js
that does something like this:
function replaceLineBreaksWithHorizontalRulesInElement( element )
{
elems = element.getElementsByTagName( 'br' );
for ( var i = 0; i < elems.length; i ++ )
{
br = elems.item( i );
hr = document.createElement( 'hr' );
br.parentNode.replaceChild( hr, br );
}
}
So in short, it's not optimal, but here is my solution.
There is no 4.5 application pool. You can use any 4.5 application in 4.0 app pool. The .NET 4.5 is "just" an in-place-update not a major new version.
Updated for Swift 3
Create two View Controllers with a button on each. For the second view controller, set the class name to SecondViewController
and the storyboard ID to secondVC
.
ViewController.swift
import UIKit
class ViewController: UIViewController {
@IBAction func presentButtonTapped(_ sender: UIButton) {
let storyboard = UIStoryboard(name: "Main", bundle: nil)
let myModalViewController = storyboard.instantiateViewController(withIdentifier: "secondVC")
myModalViewController.modalPresentationStyle = UIModalPresentationStyle.fullScreen
myModalViewController.modalTransitionStyle = UIModalTransitionStyle.coverVertical
self.present(myModalViewController, animated: true, completion: nil)
}
}
SecondViewController.swift
import UIKit
class SecondViewController: UIViewController {
@IBAction func dismissButtonTapped(_ sender: UIButton) {
self.dismiss(animated: true, completion: nil)
}
}
Source:
Use "
That should work.
First of all - that selector is pretty slow. It will scan every DOM element looking for the ids. It will be less of a performance hit if you can assign a class to the element.
$(".myselect")
To answer your question though, there are a few ways to change the select elements value in jQuery
// sets selected index of a select box to the option with the value "0"
$("select#elem").val('0');
// sets selected index of a select box to the option with the value ""
$("select#elem").val('');
// sets selected index to first item using the DOM
$("select#elem")[0].selectedIndex = 0;
// sets selected index to first item using jQuery (can work on multiple elements)
$("select#elem").prop('selectedIndex', 0);
This would work as well:
df = pd.DataFrame()
new_line = pd.Series({'A2M': 4.059, 'A2ML1': 4.28}, name='HCC1419')
df = df.append(new_line, ignore_index=False)
The name
in the Series will be the index in the dataframe. ignore_index=False
is the important flag in this case.
String source = "liril";
StringBuffer sb = new StringBuffer(source);
String r = sb.reverse().toString();
if (source.equals(r)) {
System.out.println("Palindrome ...");
} else {
System.out.println("Not a palindrome...");
}
This selector should work but will be more efficient if you replace it with your suited markup:
//*[contains(@class, 'Test')]
Or, since we know the sought element is a div
:
//div[contains(@class, 'Test')]
But since this will also match cases like class="Testvalue"
or class="newTest"
, @Tomalak's version provided in the comments is better:
//div[contains(concat(' ', @class, ' '), ' Test ')]
If you wished to be really certain that it will match correctly, you could also use the normalize-space function to clean up stray whitespace characters around the class name (as mentioned by @Terry):
//div[contains(concat(' ', normalize-space(@class), ' '), ' Test ')]
Note that in all these versions, the * should best be replaced by whatever element name you actually wish to match, unless you wish to search each and every element in the document for the given condition.
Best way to solve this until a fix is available (if a fix comes) is to force IE compatibility mode on the user.
Use <META http-equiv="X-UA-Compatible" content="IE=9">
ideally in the masterpage so all pages in your site get the workaround.
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
Use any. They are almost the same.
As usual, there are pros and cons.
Use std::reverse_iterator
:
operator>()
std::greater<int>()
Use std::greater
when:
As for performance, both methods are equally efficient. I tried the following benchmark:
#include <algorithm>
#include <chrono>
#include <iostream>
#include <fstream>
#include <vector>
using namespace std::chrono;
/* 64 Megabytes. */
#define VECTOR_SIZE (((1 << 20) * 64) / sizeof(int))
/* Number of elements to sort. */
#define SORT_SIZE 100000
int main(int argc, char **argv) {
std::vector<int> vec;
vec.resize(VECTOR_SIZE);
/* We generate more data here, so the first SORT_SIZE elements are evicted
from the cache. */
std::ifstream urandom("/dev/urandom", std::ios::in | std::ifstream::binary);
urandom.read((char*)vec.data(), vec.size() * sizeof(int));
urandom.close();
auto start = steady_clock::now();
#if USE_REVERSE_ITER
auto it_rbegin = vec.rend() - SORT_SIZE;
std::sort(it_rbegin, vec.rend());
#else
auto it_end = vec.begin() + SORT_SIZE;
std::sort(vec.begin(), it_end, std::greater<int>());
#endif
auto stop = steady_clock::now();
std::cout << "Sorting time: "
<< duration_cast<microseconds>(stop - start).count()
<< "us" << std::endl;
return 0;
}
With this command line:
g++ -g -DUSE_REVERSE_ITER=0 -std=c++11 -O3 main.cpp \
&& valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
&& cg_annotate cachegrind.out
g++ -g -DUSE_REVERSE_ITER=1 -std=c++11 -O3 main.cpp \
&& valgrind --cachegrind-out-file=cachegrind.out --tool=cachegrind ./a.out \
&& cg_annotate cachegrind.out
std::greater
demo
std::reverse_iterator
demo
Timings are same. Valgrind reports the same number of cache misses.
Finally found out what to do. Added the -std=c++0x compiler argument under Project Properties -> C/C++ Build -> Settings -> GCC C++ Compiler -> Miscellaneous. It works now!
But how to add this flag by default for all C++ projects? Anybody?
I'm not sure if you can alter the original element but how about switch from using the id attr to something else like data-id? Then just read the value of data-id for your hash value and it won't jump.
According to this MSDN blog: https://blogs.msdn.microsoft.com/manishagarwal/2005/09/28/resolving-file-references-in-team-build-part-2/
There is a search order for assemblies when building. The search order is as follows:
So, if the desired assembly is found by HintPath, but an alternate assembly can be found using ReferencePath, it will prefer the ReferencePath'd assembly to the HintPath'd one.
It is just not a valid Java syntax. You can do
names = new String[] {"Ankit","Bohra","Xyz"};
What are you doing: (I am using bytes instead of in for better reading)
You start with int *ap
and so on, so your (your computers) memory looks like this:
-------------- memory used by some one else --------
000: ?
001: ?
...
098: ?
099: ?
-------------- your memory --------
100: something <- here is *ap
101: 41 <- here starts a[]
102: 42
103: 43
104: 44
105: 45
106: something <- here waits x
lets take a look waht happens when (print short cut for ...print("$d", ...)
print a[0] -> 41 //no surprise
print a -> 101 // because a points to the start of the array
print *a -> 41 // again the first element of array
print a+1 -> guess? 102
print *(a+1) -> whats behind 102? 42 (we all love this number)
and so on, so a[0] is the same as *a, a[1] = *(a+1), ....
a[n] just reads easier.
now, what happens at line 9?
ap=a[4] // we know a[4]=*(a+4) somehow *105 ==> 45
// warning! converting int to pointer!
-------------- your memory --------
100: 45 <- here is *ap now 45
x = *ap; // wow ap is 45 -> where is 45 pointing to?
-------------- memory used by some one else --------
bang! // dont touch neighbours garden
So the "warning" is not just a warning it's a severe error.
I do not believe there is a "per query" way to do this. (You can use the use
keyword to specify the database - not the schema - but that's technically a separate query as you have to issue the go
command afterward.)
Remember, in SQL server fully qualified table names are in the format:
[database].[schema].[table]
In SQL Server Management Studio you can configure all the defaults you're asking about.
You can set up the default database
on a per-user basis (or in your connection string):
Security > Logins > (right click) user > Properties > General
You can set up the default schema
on a per-user basis (but I do not believe you can configure it in your connection string, although if you use dbo
that is always the default):
Security > Logins > (right click) user > Properties > User Mapping > Default Schema
In short, if you use dbo
for your schema, you'll likely have the least amount of headaches.
This is an old question, but since I spent the last few weeks trying to figure it out on my own:
Now, finally, after 3-4 weeks of trying to figure out OpenCL, etc, I found this tutorial to help you get started quickly. It is a step-by-step for getting hipCaffe up and running. Unlike nVidia though, please ensure you have supported hardware!!!! https://rocm.github.io/hardware.html. Think you can get it working without their supported hardware? Good luck. You've been warned. Once you have ROCM up and running (AND RUN THE VERIFICATION TESTS), here is the hipCaffe tutorial--if you got ROCM up you'll be doing an MNIST validation test within 10 minutes--sweet! https://rocm.github.io/ROCmHipCaffeQuickstart.html
Here's a concrete example:
Suppose you have a function that calculates the gravitational force acting on an object. If you don't know the formula, you can find it here. This function takes in the three necessary parameters as arguments.
Now, being on the earth, you only want to calculate forces for objects on this planet. In a functional language, you could pass in the mass of the earth to the function and then partially evaluate it. What you'd get back is another function that takes only two arguments and calculates the gravitational force of objects on earth. This is called currying.
I received this exception when trying to run a bulk UPDATE query in a non-JTA (i.e. resource-local) entity manager in Java SE. I had simply forgotten to wrap my JPQL code in
em.getTransaction().begin();
and
em.getTransaction().commit();
This one works well on Red Hat Linux (RHEL), macOS, BSD and some AIXes:
ps -T $$ | awk 'NR==2{print $NF}'
alternatively, the following one should also work if pstree is available,
pstree | egrep $$ | awk 'NR==2{print $NF}'
You can install this plugin in Firefox: https://addons.mozilla.org/en-US/firefox/addon/cliget/?src=cb-dl-toprated Start downloading what you want and click on the plugin. It gives you the whole command either for wget or curl to download the file on the serer. Very easy!
I've had the most success with python-dateutil:
from dateutil import tz
def datetime_to_utc(date):
"""Returns date in UTC w/o tzinfo"""
return date.astimezone(tz.gettz('UTC')).replace(tzinfo=None) if date.tzinfo else date
For those finding this via Google;
I was getting this error because, as suggested by the error, I failed to close a SqlDataReader prior to creating another on the same SqlCommand, mistakenly assuming that it would be garbage collected when leaving the method it was created in.
I solved the issue by calling sqlDataReader.Close();
before creating the second reader.
This will end the function, and you can even customize the "Error" message:
import sys
def end():
if condition:
# the player wants to play again:
main()
elif not condition:
sys.exit("The player doesn't want to play again") #Right here
body.addEventListener("load", init(), false);
That init() is saying run this function now and assign whatever it returns to the load event.
What you want is to assign the reference to the function, not the result. So you need to drop the ().
body.addEventListener("load", init, false);
Also you should be using window.onload and not body.onload
addEventListener
is supported in most browsers except IE 8.
Psuedo code ahead (updated with actual code):
Do While ComboBox1.ListCount > 0
ComboBox1.RemoveItem (0)
Loop
Basically, while you have items, remove the first item from the combobox. Once all the items have been removed (count = 0), your box is blank.
Method 2: Even better
ComboBox1.Clear
char *charPtr = "test string";
cout << charPtr << endl;
string str = charPtr;
cout << str << endl;
More of a comment link for suggested further reading...A really good blog article which benchmarks various ways of accomplishing this task can be found here.
They use a few techniques: "Insert Where Not Exists", "Merge" statement, "Insert Except", and your typical "left join" to see which way is the fastest to accomplish this task.
The example code used for each technique is as follows (straight copy/paste from their page) :
INSERT INTO #table1 (Id, guidd, TimeAdded, ExtraData)
SELECT Id, guidd, TimeAdded, ExtraData
FROM #table2
WHERE NOT EXISTS (Select Id, guidd From #table1 WHERE #table1.id = #table2.id)
-----------------------------------
MERGE #table1 as [Target]
USING (select Id, guidd, TimeAdded, ExtraData from #table2) as [Source]
(id, guidd, TimeAdded, ExtraData)
on [Target].id =[Source].id
WHEN NOT MATCHED THEN
INSERT (id, guidd, TimeAdded, ExtraData)
VALUES ([Source].id, [Source].guidd, [Source].TimeAdded, [Source].ExtraData);
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT id, guidd, TimeAdded, ExtraData from #table2
EXCEPT
SELECT id, guidd, TimeAdded, ExtraData from #table1
------------------------------
INSERT INTO #table1 (id, guidd, TimeAdded, ExtraData)
SELECT #table2.id, #table2.guidd, #table2.TimeAdded, #table2.ExtraData
FROM #table2
LEFT JOIN #table1 on #table1.id = #table2.id
WHERE #table1.id is null
It's a good read for those who are looking for speed! On SQL 2014, the Insert-Except method turned out to be the fastest for 50 million or more records.
You can use .querySelectorAll()
to select all td
elements, then loop over these with .forEach()
. Their values can be retrieved with .innerHTML
:
const cells = document.querySelectorAll('td');_x000D_
cells.forEach(function(cell) {_x000D_
console.log(cell.innerHTML);_x000D_
})
_x000D_
<table name="mytab" id="mytab1">_x000D_
<tr> _x000D_
<td>col1 Val1</td>_x000D_
<td>col2 Val2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>col1 Val3</td>_x000D_
<td>col2 Val4</td>_x000D_
</tr>_x000D_
</table>
_x000D_
If you want to only select columns from a specific row, you can make use of the pseudo-class :nth-child()
to select a specific tr
, optionally in conjunction with the child combinator (>
) (which can be useful if you have a table within a table):
const cells = document.querySelectorAll('tr:nth-child(2) > td');_x000D_
cells.forEach(function(cell) {_x000D_
console.log(cell.innerHTML);_x000D_
})
_x000D_
<table name="mytab" id="mytab1">_x000D_
<tr> _x000D_
<td>col1 Val1</td>_x000D_
<td>col2 Val2</td>_x000D_
</tr>_x000D_
<tr>_x000D_
<td>col1 Val3</td>_x000D_
<td>col2 Val4</td>_x000D_
</tr>_x000D_
</table>
_x000D_
if you want to remove spaces,-, and another text from string then use following :
suppose you have a mobile number in your Table like '718-378-4957' or ' 7183784957' and you want replace and get the mobile number then use following Text.
select replace(replace(replace(replace(MobileNo,'-',''),'(',''),')',''),' ','') from EmployeeContactNumber
Result :-- 7183784957
You can also simple add the following into the Header or Footer of the Worksheet
Last Saved: &[Date] &[Time]
This is an option:
dbContext.Entry(entity).State = EntityState.Detached;
Have you gone through google's geocoding api. The following link shall help you get started: http://code.google.com/apis/maps/documentation/geocoding/#GeocodingRequests
We can as well start an application by knowing application type and feeding it with data:
adb shell am start -d "file:///sdcard/sample.3gp" -t "video/3gp" -a android.intent.action.VIEW
This command displays available Video Players to play sample.3gp file
Full example:
private static final Pattern p = Pattern.compile("^([a-zA-Z]+)([0-9]+)(.*)");
public static void main(String[] args) {
// create matcher for pattern p and given string
Matcher m = p.matcher("Testing123Testing");
// if an occurrence if a pattern was found in a given string...
if (m.find()) {
// ...then you can use group() methods.
System.out.println(m.group(0)); // whole matched expression
System.out.println(m.group(1)); // first expression from round brackets (Testing)
System.out.println(m.group(2)); // second one (123)
System.out.println(m.group(3)); // third one (Testing)
}
}
Since you're looking for the first number, you can use such regexp:
^\D+(\d+).*
and m.group(1)
will return you the first number. Note that signed numbers can contain a minus sign:
^\D+(-?\d+).*
i found this way worked nice:
{
char [] a;
String temp;
Scanner keyboard = new Scanner(System.in);
System.out.println("please give the first integer :");
temp=keyboard.next();
a=temp.toCharArray();
}
you can also get individual one with String.charAt()
Looking at your other question I assume you are trying to run a php or asp file or something on your webserver and this is your first attempt in webdesign.
Once you have installed php correctly (which you probably did when you got XAMPP) just place whatever file you want under your localhost (/www/var/html perhaps?) and it should run. You can check this of course at localhost/file.php in your browser.
To me the best way is -
Hope this will help .
SlickGrid has this functionality, see the tree demo.
If you want to build your own, here is an example (jsFiddle demo): Build your table with a data-depth
attribute to indicate the depth of the item in the tree (the levelX
CSS classes are just for styling indentation):
<table id="mytable">
<tr data-depth="0" class="collapse level0">
<td><span class="toggle collapse"></span>Item 1</td>
<td>123</td>
</tr>
<tr data-depth="1" class="collapse level1">
<td><span class="toggle"></span>Item 2</td>
<td>123</td>
</tr>
</table>
Then when a toggle link is clicked, use Javascript to hide all <tr>
elements until a <tr>
of equal or less depth is found (excluding those already collapsed):
$(function() {
$('#mytable').on('click', '.toggle', function () {
//Gets all <tr>'s of greater depth below element in the table
var findChildren = function (tr) {
var depth = tr.data('depth');
return tr.nextUntil($('tr').filter(function () {
return $(this).data('depth') <= depth;
}));
};
var el = $(this);
var tr = el.closest('tr'); //Get <tr> parent of toggle button
var children = findChildren(tr);
//Remove already collapsed nodes from children so that we don't
//make them visible.
//(Confused? Remove this code and close Item 2, close Item 1
//then open Item 1 again, then you will understand)
var subnodes = children.filter('.expand');
subnodes.each(function () {
var subnode = $(this);
var subnodeChildren = findChildren(subnode);
children = children.not(subnodeChildren);
});
//Change icon and hide/show children
if (tr.hasClass('collapse')) {
tr.removeClass('collapse').addClass('expand');
children.hide();
} else {
tr.removeClass('expand').addClass('collapse');
children.show();
}
return children;
});
});
You can text-align: center the body to center the container. Then text-align: left the container to get all the text, etc. to align left.
Leland's answer worked for me, but I had to change steps 4 and 6 to:
4) git checkout -B icu4c-62.1 575eb4b
6) brew reinstall Formula/icu4c.rb
You can use implode to return your array with a string separator.
$withComma = implode(",", $array);
echo $withComma;
// Will display apple,banana,orange
Just pass it as an argument of findAll
:
>>> from BeautifulSoup import BeautifulSoup
>>> soup = BeautifulSoup("""
... <html>
... <head><title>My Title!</title></head>
... <body><table>
... <tr><td>First!</td>
... <td valign="top">Second!</td></tr>
... </table></body><html>
... """)
>>>
>>> soup.findAll('td')
[<td>First!</td>, <td valign="top">Second!</td>]
>>>
>>> soup.findAll('td', valign='top')
[<td valign="top">Second!</td>]
NULL Cannot be compared to any value using the comparison operators. NULL = NULL is false. Null is not a value. The IS operator is specially designed to handle NULL comparisons.
I realize there is an accepted answer, and apparently it was either the size of memory chosen or the infinite loop suggestion that solved the issue for the OP.
For me, I added an array to the config file earlier and made some other changes prior to running artisan and getting the out of memory error and no amount of increasing memory helped. What it turned out to be was a missing comma after the array I added to the config file.
I am adding this answer in hopes that it helps someone else figure out what might be causing out of memory error. I am using laravel 5.4 under MAMP.
Along with the already suggested methods of using a foreach
loop, I thought I'd also mention that any object that implements IEnumerable
also provides an IEnumerator
interface via the GetEnumerator
method. Although this method is usually not necessary, this can be used for manually iterating over collections, and is particularly useful when writing your own extension methods for collections.
IEnumerable<T> mySequence;
using (var sequenceEnum = mySequence.GetEnumerator())
{
while (sequenceEnum.MoveNext())
{
// Do something with sequenceEnum.Current.
}
}
A prime example is when you want to iterate over two sequences concurrently, which is not possible with a foreach
loop.
I found a short comparison from MSDN
The .NET Framework Class Library includes four classes named Timer, each of which offers different functionality:
System.Timers.Timer
, which fires an event and executes the code in one or more event sinks at regular intervals. The class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Threading.Timer
, which executes a single callback method on a thread pool thread at regular intervals. The callback method is defined when the timer is instantiated and cannot be changed. Like the System.Timers.Timer class, this class is intended for use as a server-based or service component in a multithreaded environment; it has no user interface and is not visible at runtime.
System.Windows.Forms.Timer
, a Windows Forms component that fires an event and executes the code in one or more event sinks at regular intervals. The component has no user interface and is designed for use in a single-threaded environment.
System.Web.UI.Timer
, an ASP.NET component that performs asynchronous or synchronous web page postbacks at a regular interval.
An additional option is to go to your build folder and use the command ccmake .
This is like the GUI but terminal based. This obviously won't help with an installation script but at least it can be run without a UI.
The one warning I have is it won't let you generate sometimes when you have warnings. if that is the case, exit the interface and call cmake .
You need to create a set of escaped (with \
) parentheses (that match the parentheses) and a group of regular parentheses that create your capturing group:
var regExp = /\(([^)]+)\)/;_x000D_
var matches = regExp.exec("I expect five hundred dollars ($500).");_x000D_
_x000D_
//matches[1] contains the value between the parentheses_x000D_
console.log(matches[1]);
_x000D_
Breakdown:
\(
: match an opening parentheses(
: begin capturing group[^)]+
: match one or more non )
characters)
: end capturing group\)
: match closing parenthesesHere is a visual explanation on RegExplained
Just incase Someone needs an easier way:
The following code gives a view of the whole activity:
View v1 = getWindow().getDecorView().getRootView();
To get a certian view in the activity,for example an imageView inside the activity, simply add the id of that view you want to get:
View v1 = getWindow().getDecorView().getRootView().findViewById(R.id.imageView1);
Hope this helps somebody
As you can see here there is a very simple way to do that.
In your DialogFragment
add an interface listener like:
public interface EditNameDialogListener {
void onFinishEditDialog(String inputText);
}
Then, add a reference to that listener:
private EditNameDialogListener listener;
This will be used to "activate" the listener method(s), and also to check if the parent Activity/Fragment implements this interface (see below).
In the Activity
/FragmentActivity
/Fragment
that "called" the DialogFragment
simply implement this interface.
In your DialogFragment
all you need to add at the point where you'd like to dismiss the DialogFragment
and return the result is this:
listener.onFinishEditDialog(mEditText.getText().toString());
this.dismiss();
Where mEditText.getText().toString()
is what will be passed back to the calling Activity
.
Note that if you want to return something else simply change the arguments the listener takes.
Finally, you should check whether the interface was actually implemented by the parent activity/fragment:
@Override
public void onAttach(Context context) {
super.onAttach(context);
// Verify that the host activity implements the callback interface
try {
// Instantiate the EditNameDialogListener so we can send events to the host
listener = (EditNameDialogListener) context;
} catch (ClassCastException e) {
// The activity doesn't implement the interface, throw exception
throw new ClassCastException(context.toString()
+ " must implement EditNameDialogListener");
}
}
This technique is very flexible and allow calling back with the result even if your don;t want to dismiss the dialog just yet.
You could skip the use of buttord, and instead just pick an order for the filter and see if it meets your filtering criterion. To generate the filter coefficients for a bandpass filter, give butter() the filter order, the cutoff frequencies Wn=[low, high]
(expressed as the fraction of the Nyquist frequency, which is half the sampling frequency) and the band type btype="band"
.
Here's a script that defines a couple convenience functions for working with a Butterworth bandpass filter. When run as a script, it makes two plots. One shows the frequency response at several filter orders for the same sampling rate and cutoff frequencies. The other plot demonstrates the effect of the filter (with order=6) on a sample time series.
from scipy.signal import butter, lfilter
def butter_bandpass(lowcut, highcut, fs, order=5):
nyq = 0.5 * fs
low = lowcut / nyq
high = highcut / nyq
b, a = butter(order, [low, high], btype='band')
return b, a
def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
y = lfilter(b, a, data)
return y
if __name__ == "__main__":
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import freqz
# Sample rate and desired cutoff frequencies (in Hz).
fs = 5000.0
lowcut = 500.0
highcut = 1250.0
# Plot the frequency response for a few different orders.
plt.figure(1)
plt.clf()
for order in [3, 6, 9]:
b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)
plt.plot((fs * 0.5 / np.pi) * w, abs(h), label="order = %d" % order)
plt.plot([0, 0.5 * fs], [np.sqrt(0.5), np.sqrt(0.5)],
'--', label='sqrt(0.5)')
plt.xlabel('Frequency (Hz)')
plt.ylabel('Gain')
plt.grid(True)
plt.legend(loc='best')
# Filter a noisy signal.
T = 0.05
nsamples = T * fs
t = np.linspace(0, T, nsamples, endpoint=False)
a = 0.02
f0 = 600.0
x = 0.1 * np.sin(2 * np.pi * 1.2 * np.sqrt(t))
x += 0.01 * np.cos(2 * np.pi * 312 * t + 0.1)
x += a * np.cos(2 * np.pi * f0 * t + .11)
x += 0.03 * np.cos(2 * np.pi * 2000 * t)
plt.figure(2)
plt.clf()
plt.plot(t, x, label='Noisy signal')
y = butter_bandpass_filter(x, lowcut, highcut, fs, order=6)
plt.plot(t, y, label='Filtered signal (%g Hz)' % f0)
plt.xlabel('time (seconds)')
plt.hlines([-a, a], 0, T, linestyles='--')
plt.grid(True)
plt.axis('tight')
plt.legend(loc='upper left')
plt.show()
Here are the plots that are generated by this script:
If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).
The way to use mysplit.bat
below is
mysplit.bat <mysize> 'myfile'
Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.
Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.
Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.
Script mysplit.bat
:
@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell ^
$upperBound = 100MB; ^
$rootName = %2; ^
$from = $rootName; ^
$fromFile = [io.file]::OpenRead($from); ^
$buff = new-object byte[] $upperBound; ^
$count = $idx = 0; ^
try { ^
do { ^
'Reading ' + $upperBound; ^
$count = $fromFile.Read($buff, 0, $buff.Length); ^
if ($count -gt 0) { ^
$to = '{0}.{1}' -f ($rootName, $idx); ^
$toFile = [io.file]::OpenWrite($to); ^
try { ^
'Writing ' + $count + ' to ' + $to; ^
$tofile.Write($buff, 0, $count); ^
} finally { ^
$tofile.Close(); ^
} ^
} ^
$idx ++; ^
} while ($count -gt 0); ^
} ^
finally { ^
$fromFile.Close(); ^
} ^
%End PowerShell%
It is a security issue, so to fix it simply do the following:
Some things to clarify:
therefore the correct answer would be
$timestamp = '1299762201428';
$date = date('Y-m-d H:i:s', substr($timestamp, 0, -3));
From ScottGu's blog:
Starting with the ASP.NET MVC 3 Beta release, you can now add a file called _ViewStart.cshtml (or _ViewStart.vbhtml for VB) underneath the \Views folder of your project:
The _ViewStart file can be used to define common view code that you want to execute at the start of each View’s rendering. For example, we could write code within our _ViewStart.cshtml file to programmatically set the Layout property for each View to be the SiteLayout.cshtml file by default:
Because this code executes at the start of each View, we no longer need to explicitly set the Layout in any of our individual view files (except if we wanted to override the default value above).
Important: Because the _ViewStart.cshtml allows us to write code, we can optionally make our Layout selection logic richer than just a basic property set. For example: we could vary the Layout template that we use depending on what type of device is accessing the site – and have a phone or tablet optimized layout for those devices, and a desktop optimized layout for PCs/Laptops. Or if we were building a CMS system or common shared app that is used across multiple customers we could select different layouts to use depending on the customer (or their role) when accessing the site.
This enables a lot of UI flexibility. It also allows you to more easily write view logic once, and avoid repeating it in multiple places.
Also see this.
In a more general sense this ability of MVC framework to "know" about _Viewstart.cshtml is called "Coding by convention".
Convention over configuration (also known as coding by convention) is a software design paradigm which seeks to decrease the number of decisions that developers need to make, gaining simplicity, but not necessarily losing flexibility. The phrase essentially means a developer only needs to specify unconventional aspects of the application. For example, if there's a class Sale in the model, the corresponding table in the database is called “sales” by default. It is only if one deviates from this convention, such as calling the table “products_sold”, that one needs to write code regarding these names.
Wikipedia
There's no magic to it. Its just been written into the core codebase of the MVC framework and is therefore something that MVC "knows" about. That why you don't find it in the .config files or elsewhere; it's actually in the MVC code. You can however override to alter or null out these conventions.
I had the same problem in win10 64bit, too. After a lot of searching, I found this solution.(If you're using an intel system(CPU, GPU, Motherboard, etc.)) Hope it work for you, too.
step 1: Make sure virtualization is enabled on your device:
Reboot your computer and then press F2 for BIOS setup. You should find Virtualization tag and make sure it is marked as enabled. If it's not enabled, no virtual devices can run on your device.
step 2: Install/Update Intel Hardware Accelerated Execution Manager(Intel HAXM) on your device:
This software should be installed or updated for any AVDs to run. You can download the latest version by googling "HAXM". After download, install .exe file and reboot your computer.
The scroll speed CAN be changed, adjusted, reversed, all of the above - via javascript (or a js library such as jQuery).
WHY would you want to do this? Parallax is just one of the reasons. I have no idea why anyone would argue against doing so -- the same negative arguments can be made against hiding DIVs, sliding elements up/down, etc. Websites are always a combination of technical functionality and UX design -- a good designer can use almost any technical capability to improve UX. That is what makes him/her good.
Toni Almeida of Portugal created a brilliant demo, reproduced below:
HTML:
<div id="myDiv">
Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. <span class="boldit">Use the mouse wheel (not the scroll bar) to scroll this DIV. You will see that the scroll eventually slows down, and then stops. </span>
</div>
javascript/jQuery:
function wheel(event) {
var delta = 0;
if (event.wheelDelta) {(delta = event.wheelDelta / 120);}
else if (event.detail) {(delta = -event.detail / 3);}
handle(delta);
if (event.preventDefault) {(event.preventDefault());}
event.returnValue = false;
}
function handle(delta) {
var time = 1000;
var distance = 300;
$('html, body').stop().animate({
scrollTop: $(window).scrollTop() - (distance * delta)
}, time );
}
if (window.addEventListener) {window.addEventListener('DOMMouseScroll', wheel, false);}
window.onmousewheel = document.onmousewheel = wheel;
Source:
How to change default scrollspeed,scrollamount,scrollinertia of a webpage
When use CMS GC in jdk1.8 will appeare this error, i change the G1 Gc solve this problem.
-Xss512k -Xms6g -Xmx6g -XX:+UseG1GC -XX:MaxGCPauseMillis=200 -XX:InitiatingHeapOccupancyPercent=70 -XX:NewRatio=1 -XX:SurvivorRatio=6 -XX:G1ReservePercent=10 -XX:G1HeapRegionSize=32m -XX:ConcGCThreads=6 -Xloggc:gc.log -XX:+HeapDumpOnOutOfMemoryError -XX:+PrintGC -XX:+PrintGCDetails -XX:+PrintGCTimeStamps
For all users on a specific database, do the following:
# psql
\c your_database
select grantee, table_catalog, privilege_type, table_schema, table_name from information_schema.table_privileges order by grantee, table_schema, table_name;
It could also be something as simple as Apache not being configured to start automatically on boot. Assuming you are on a Red Hat-like system such as CentOS or Fedora, the chkconfig –list command will show you which services are set to start for each runlevel. You should see a line like
httpd 0:off 1:off 2:on 3:on 4:on 5:on 6:off
If instead it says "off" all the way across, you can activate it with chkconfig httpd on. OR you can start apache manually from your panel.
You can also use this
let str = "hello single ' double \" and slash \\ yippie";
let escapeStr = escape(str);
document.write("<b>str : </b>"+str);
document.write("<br/><b>escapeStr : </b>"+escapeStr);
document.write("<br/><b>unEscapeStr : </b> "+unescape(escapeStr));
_x000D_
There are two ways to do what you are trying
One is a Multi-column Correlated Update
UPDATE PRODUCTION a
SET (name, count) = (
SELECT name, count
FROM STAGING b
WHERE a.ID = b.ID);
You can use merge
MERGE INTO PRODUCTION a
USING ( select id, name, count
from STAGING ) b
ON ( a.id = b.id )
WHEN MATCHED THEN
UPDATE SET a.name = b.name,
a.count = b.count
use #undef UNICODE
at the top of your main file.
After many days trying, I found this solution that worked for me:
touch-action: none;
-ms-touch-action: none;
I think you'll get what you want with the -maxdepth 1
option, based on your current command structure. If not, you can try looking at the man page for find
.
Relevant entry (for convenience's sake):
-maxdepth levels
Descend at most levels (a non-negative integer) levels of direc-
tories below the command line arguments. `-maxdepth 0' means
only apply the tests and actions to the command line arguments.
Your options basically are:
# Do NOT show hidden files (beginning with ".", i.e., .*):
find DirsRoot/* -maxdepth 0 -type f
Or:
# DO show hidden files:
find DirsRoot/ -maxdepth 1 -type f
The following example validates an XML file and generates the appropriate error or warning.
using System;
using System.IO;
using System.Xml;
using System.Xml.Schema;
public class Sample
{
public static void Main()
{
//Load the XmlSchemaSet.
XmlSchemaSet schemaSet = new XmlSchemaSet();
schemaSet.Add("urn:bookstore-schema", "books.xsd");
//Validate the file using the schema stored in the schema set.
//Any elements belonging to the namespace "urn:cd-schema" generate
//a warning because there is no schema matching that namespace.
Validate("store.xml", schemaSet);
Console.ReadLine();
}
private static void Validate(String filename, XmlSchemaSet schemaSet)
{
Console.WriteLine();
Console.WriteLine("\r\nValidating XML file {0}...", filename.ToString());
XmlSchema compiledSchema = null;
foreach (XmlSchema schema in schemaSet.Schemas())
{
compiledSchema = schema;
}
XmlReaderSettings settings = new XmlReaderSettings();
settings.Schemas.Add(compiledSchema);
settings.ValidationEventHandler += new ValidationEventHandler(ValidationCallBack);
settings.ValidationType = ValidationType.Schema;
//Create the schema validating reader.
XmlReader vreader = XmlReader.Create(filename, settings);
while (vreader.Read()) { }
//Close the reader.
vreader.Close();
}
//Display any warnings or errors.
private static void ValidationCallBack(object sender, ValidationEventArgs args)
{
if (args.Severity == XmlSeverityType.Warning)
Console.WriteLine("\tWarning: Matching schema not found. No validation occurred." + args.Message);
else
Console.WriteLine("\tValidation error: " + args.Message);
}
}
The preceding example uses the following input files.
<?xml version='1.0'?>
<bookstore xmlns="urn:bookstore-schema" xmlns:cd="urn:cd-schema">
<book genre="novel">
<title>The Confidence Man</title>
<price>11.99</price>
</book>
<cd:cd>
<title>Americana</title>
<cd:artist>Offspring</cd:artist>
<price>16.95</price>
</cd:cd>
</bookstore>
books.xsd
<xsd:schema xmlns:xsd="http://www.w3.org/2001/XMLSchema"
xmlns="urn:bookstore-schema"
elementFormDefault="qualified"
targetNamespace="urn:bookstore-schema">
<xsd:element name="bookstore" type="bookstoreType"/>
<xsd:complexType name="bookstoreType">
<xsd:sequence maxOccurs="unbounded">
<xsd:element name="book" type="bookType"/>
</xsd:sequence>
</xsd:complexType>
<xsd:complexType name="bookType">
<xsd:sequence>
<xsd:element name="title" type="xsd:string"/>
<xsd:element name="author" type="authorName"/>
<xsd:element name="price" type="xsd:decimal"/>
</xsd:sequence>
<xsd:attribute name="genre" type="xsd:string"/>
</xsd:complexType>
<xsd:complexType name="authorName">
<xsd:sequence>
<xsd:element name="first-name" type="xsd:string"/>
<xsd:element name="last-name" type="xsd:string"/>
</xsd:sequence>
</xsd:complexType>
</xsd:schema>
The quick one-liner, inline way
await new Promise(resolve => setTimeout(resolve, 1000));
Here is another approach.
class orbisius_custom_string {
/**
* The reverse of nl2br. Handles <br/> <br/> <br />
* usage: orbisius_custom_string::br2nl('Your buffer goes here ...');
* @param str $buff
* @return str
* @author Slavi Marinov | http://orbisius.com
*/
public static function br2nl($buff = '') {
$buff = preg_replace('#<br[/\s]*>#si', "\n", $buff);
$buff = trim($buff);
return $buff;
}
}
I was facing same issue so I have reinstall MySQL 8 with different Authentication Method "Use Legacy Authentication Method (Retain MySQL 5.x compatibility)" then work properly.
Choose Second Method of Authentication while installing.
For VB.net
vbcrlf = environment.newline...
Dim MyString As String = "This is a Test" & Environment.NewLine & " This is the second line!"
Dim MyNewString As String = MyString.Replace(Environment.NewLine,String.Empty)
Solution:
>>> s = []
>>> p = ['This', 'That', 'There', 'is', 'apple']
>>> [s.append(i.lower()) if not i.islower() else s.append(i) for i in p]
>>> s
>>> ['this', 'that', 'there', 'is','apple']
This solution will create a separate list containing the lowercase items, regardless of their original case. If the original case is upper then the list s
will contain lowercase of the respective item in list p
. If the original case of the list item is already lowercase in list p
then the list s
will retain the item's case and keep it in lowercase. Now you can use list s
instead of list p
.
Use content=
"IE=edge,chrome=1"
Skip other X-UA-Compatible
modes
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
--------------------------
No compatibility icon
The IE9 Address bar does not show up the Compatibility View button
and the page does not also show up a jumble of out-of-place menus, images, and text boxes.
Features
This meta tag is required to enable javascript::JSON.parse()
on IE8
(even when <!DOCTYPE html>
is present)
Correctness
Rendering/Execution of modern HTML/CSS/JavaScript is more valid (nicer).
Performance
The Trident rendering engine should run faster in its edge mode.
In your HTML
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
IE=edge
means IE should use the latest (edge) version of its rendering enginechrome=1
means IE should use the Chrome rendering engine if installedOr better in the configuration of your web server:
(see also the RiaD's answer)
Apache as proposed by pixeline
<IfModule mod_setenvif.c>
<IfModule mod_headers.c>
BrowserMatch MSIE ie
Header set X-UA-Compatible "IE=Edge,chrome=1" env=ie
</IfModule>
</IfModule>
<IfModule mod_headers.c>
Header append Vary User-Agent
</IfModule>
Nginx as proposed by Stef Pause
server {
#...
add_header X-UA-Compatible "IE=Edge,chrome=1";
}
Varnish proxy as proposed by Lucas Riutzel
sub vcl_deliver {
if( resp.http.Content-Type ~ "text/html" ) {
set resp.http.X-UA-Compatible = "IE=edge,chrome=1";
}
}
IIS (since v7)
<configuration>
<system.webServer>
<httpProtocol>
<customHeaders>
<add name="X-UA-Compatible" value="IE=edge,chrome=1" />
</customHeaders>
</httpProtocol>
</system.webServer>
</configuration>
As noticed by Lynda (see comments), the Compatibility changes in IE11 recommends Edge mode:
Starting with IE11, edge mode is the preferred document mode; it represents the highest support for modern standards available to the browser.
But the position of Microsoft was not clear. Another MSDN page did not recommend Edge mode:
Because Edge mode forces all pages to be opened in standards mode, regardless of the version of Internet Explorer, you might be tempted to use this for all pages viewed with Internet Explorer. Don't do this, as the
X-UA-Compatible
header is only supported starting with Windows Internet Explorer 8.
Instead, Microsoft recommended using <!DOCTYPE html>
:
If you want all supported versions of Internet Explorer to open your pages in standards mode, use the HTML5 document type declaration [...]
As Ricardo explains (in the comments below) any DOCTYPE (HTML4, XHTML1...) can be used to trigger Standards Mode, not only HTML5's DOCTYPE. The important thing is to always have a DOCTYPE in the page.
Clara Onager has even noticed in an older version of Specifying legacy document modes:
Edge mode is intended for testing purposes only; do not use it in a production environment.
It is so confusing that Usman Y thought Clara Onager was speaking about:
The [...] example is provided for illustrative purposes only; don't use it in a production environment.
<meta http-equiv="X-UA-Compatible" content="IE=7,9,10" >
Well... In the rest of this answer I give more explanations why using content="IE=edge,chrome=1"
is a good practice in production.
For many years (2000 to 2008), IE market share was more than 80%. And IE v6 was considered as a de facto standard (80% to 97% market share in 2003, 2004, 2005 and 2006 for IE6 only, more market share with all IE versions).
As IE6 was not respecting Web standards, developers had to test their website using IE6. That situation was great for Microsoft (MS) as web developers had to buy MS products (e.g. IE cannot be used without buying Windows), and it was more profit-making to stay non-compliant (i.e. Microsoft wanted to become the standard excluding other companies).
Therefore many many sites were IE6 compliant only, and as IE was not compliant with web standard, all these web sites was not well rendered on standards compliant browsers. Even worse, many sites required only IE.
However, at this time, Mozilla started Firefox development respecting as much as possible all the web standards (other browser were implemented to render pages as done by IE6). As more and more web developers wanted to use the new web standards features, more and more websites were more supported by Firefox than IE.
When IE market sharing was decreasing, MS realized staying standard incompatible was not a good idea. Therefore MS started to release new IE version (IE8/IE9/IE10) respecting more and more the web standards.
But the issue is all the websites designed for IE6: Microsoft could not release new IE versions incompatible with these old IE6-designed websites. Instead of deducing the IE version a website has been designed, MS requested developers to add extra data (X-UA-Compatible
) in their pages.
Nowadays, IE6 is still used (0.7% in 2016) (4.5% in January 2014), and some internet websites are still IE6-only-compliant. Some intranet website/applications are tested using IE6. Some intranet website are 100% functional only on IE6. These companies/departments prefer to postpone the migration cost: other priorities, nobody no longer knows how the website/application has been implemented, the owner of the legacy website/application went bankrupt...
China represents 50% of IE6 usage in 2013, but it may change in the next years as Chinese Linux distribution is being broadcast.
If you (try to) respect web standard, you can simply always use http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"
. To keep compatibility with old browsers, just avoid using latest web features: use the subset supported by the oldest browser you want to support. Or If you want to go further, you may adopt concepts as Graceful degradation, Progressive enhancement and Unobtrusive JavaScript. (You may also be pleased to read What should a web developer consider?.)
Do do not care about the best IE version rendering: this is not your job as browsers have to be compliant with web standards. If your site is standard compliant and use moderately latest features, therefore browsers have to be compliant with your website.
Moreover, as there are many campaigns to kill IE6 (IE6 no more, MS campaign), nowadays you may avoid wasting time with IE testing!
In 2009-2012, I worked for a company using IE6 as the official single browser allowed. I had to implement an intranet website for IE6 only. I decided to respect web standard but using the IE6-capable subset (HTML/CSS/JS).
It was hard, but when the company switched to IE8, the website was still well rendered because I had used Firefox and firebug to check the web-standard compatibility ;)