In my case I had wrong package imported:
import org.testng.annotations.Test;
instead of
import org.junit.Test;
Beware of your ide autocomplete.
I have this problem from time to time. The thing that resolves the issue most for me is to run the JUnit test from Run configurations... ensuring that JUnit 4 is set as the test runner.
Generally, I see this issue when attempting to Run As... Junit test from the context menu on the Package Explorer. If you right click the code for the test you are trying to run and instead of selecting Run As... Junit Test you select Run configurations... ensure the Project, Test Class and test runner are set correctly, clicking apply, then run works all the time for me.
By default , maven looks at these folders for java and test classes respectively - src/main/java and src/test/java
When the src is specified with the test classes under source and the scope for junit dependency in pom.xml is mentioned as test - org.unit will not be found by maven.
Please check out this one: https://github.com/TransparentMarket/junit. It runs the test in the order they are specified (defined within the compiled class file). Also it features a AllTests suite to run tests defined by sub package first. Using the AllTests implementation one can extend the solution in also filtering for properties (we used to use @Fast annotations but those were not published yet).
Ok, you've declared junit
dependency for test
classes only (those that are in src/test/java
but you're trying to use it in main
classes (those that are in src/main/java
).
Either do not use it in main classes, or remove <scope>test</scope>
.
In Selenium Python it is:
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support.ui import Select
def get_selected_value_from_drop_down(self):
try:
select = Select(WebDriverWait(self.driver, 20).until(EC.element_to_be_clickable((By.ID, 'data_configuration_edit_data_object_tab_details_lb_use_for_match'))))
return select.first_selected_option.get_attribute("value")
except NoSuchElementException, e:
print "Element not found "
print e
As mentioned in duscusion: WEB-INF is not really a part of class path. If you use a common template such as maven, use src/main/resources or src/test/resources to place the app-context.xml into. Then you can use 'classpath:'.
Place your config file into src/main/resources/app-context.xml and use code
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:app-context.xml")
public class PersonControllerTest {
...
}
or you can make yout test context with different configuration of beans.
Place your config file into src/test/resources/test-app-context.xml and use code
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:test-app-context.xml")
public class PersonControllerTest {
...
}
In Spring 2.1.5 at least, the XML file can be conveniently replaced by annotations. Piggy backing on @Sembrano's answer, I have this. "Look ma, no XML".
It appears I to had list all the classes I need @Autowired in the @ComponentScan
@RunWith(SpringJUnit4ClassRunner.class)
@ComponentScan(
basePackageClasses = {
OwnerService.class
})
@EnableAutoConfiguration
public class OwnerIntegrationTest {
@Autowired
OwnerService ownerService;
@Test
public void testOwnerService() {
Assert.assertNotNull(ownerService);
}
}
I would prefer AssertJ for this.
assertThatExceptionOfType(ExpectedException.class)
.isThrownBy(() -> {
// method call
}).withMessage("My message");
public class StringEqualityTest extends TestCase {
public void testEquality() throws Exception {
String a = "abcde";
String b = new String(a);
assertTrue(a.equals(b));
assertFalse(a == b);
assertEquals(a, b);
}
}
The basic difference between all these annotations is as follows -
All these annotations along with the usage is defined on Codingeek - Junit5 Test Lifecycle
testCompile is deprecated. Gradle 7 compatible:
dependencies {
...
testImplementation 'junit:junit:4.13'
}
and if you use the default folder structure (src/test/java/...) the test section is simply:
test {
useJUnit()
}
Finally:
gradlew clean test
Alos see: https://docs.gradle.org/current/userguide/java_testing.html
I had the similar problem with my Eclipse Helios which debugging Junits. My problem was little different as i was able to run Junits successfully but when i was getting ClassNotFoundException while debugging the same JUNITs.
I have tried all sort of different solutions available in Stackoverflow.com and forums elsewhere, but nothing seem to work. After banging my head with these issue for close to two days, finally i figured out the solution to it.
If none of the solutions seem to work, just delete the .metadata folder created in your workspace. This would create an additional overhead of importing the projects and all sorts of configuration you have done, but these will surely solve these issue.
Hope these helps.
This problem also arises when you have mockito-all on your class path, which is already deprecated.
If possible just include mockito-core.
Maven config for mixing junit, mockito and hamcrest:
<dependencies>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-core</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.hamcrest</groupId>
<artifactId>hamcrest-library</artifactId>
<version>1.3</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-all</artifactId>
<version>1.9.5</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
</dependencies>
Rules are used to add additional functionality which applies to all tests within a test class, but in a more generic way.
For instance, ExternalResource executes code before and after a test method, without having to use @Before
and @After
. Using an ExternalResource
rather than @Before
and @After
gives opportunities for better code reuse; the same rule can be used from two different test classes.
The design was based upon: Interceptors in JUnit
For more information see JUnit wiki : Rules.
In case you use Spring Test try org.springframework.test.util.ReflectionTestUtils
ReflectionTestUtils.setField(testObject, "person", mockedPerson);
I think the usual use case is to call it when no exception was thrown in a negative test.
Something like the following pseudo-code:
test_addNilThrowsNullPointerException()
{
try {
foo.add(NIL); // we expect a NullPointerException here
fail("No NullPointerException"); // cause the test to fail if we reach this
} catch (NullNullPointerException e) {
// OK got the expected exception
}
}
import static com.googlecode.catchexception.apis.BDDCatchException.*;
@Test
public void testFooThrowsIndexOutOfBoundsException() {
when(() -> foo.doStuff());
then(caughtException()).isInstanceOf(IndexOutOfBoundsException.class);
}
eu.codearte.catch-exception:catch-exception:2.0
assertTrue
will fail if the checked value is false, and assertFalse
will do the opposite: fail if the checked value is true.
Another thing, your last assertEquals will very likely fail, as it will compare the "Book was already checked out" string with the output of m1.checkOut(b1,p2). It needs a third parameter (the second value to check for equality).
I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.
You can try doing:
String myResource = IOUtils.toString(this.getClass().getResourceAsStream("yourfile.xml")).replace("\n","");
If you are unlucky enough to catch all errors in your code. You can stupidly do
class DumpTest {
Exception ex;
@Test
public void testWhatEver() {
try {
thisShouldThrowError();
} catch (Exception e) {
ex = e;
}
assertEquals(null,ex);
}
}
Alternatively to hasProperty
you can try hamcrest-more-matchers where
matcher with extracting function. In your case it will look like:
import static com.github.seregamorph.hamcrest.MoreMatchers.where;
assertThat(myClass.getMyItems(), contains(
where(MyItem::getName, is("foo")),
where(MyItem::getName, is("bar"))
));
The advantages of this approach are:
Expected: iterable containing [Object that matches is "foo" after call
MyItem.getName, Object that matches is "bar" after call MyItem.getName]
but: item 0: was "wrong-name"
print didn't transition from statement to function until Python 3.0. If you're using older Python then you can suppress the newline with a trailing comma like so:
print "Foo %10s bar" % baz,
Take a look at this for more detail. It refers to how Apache handles multiple requests. Preforking, which is the default, starts a number of Apache processes (2 by default here, though I believe one can configure this through httpd.conf). Worker MPM will start a new thread per request, which I would guess, is more memory efficient. Historically, Apache has used prefork, so it's a better-tested model. Threading was only added in 2.0.
Latest revision based on comment from BinaryZebra's comment
and tested here. The addition of command eval
allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.
Use $IFS that has no spaces\tabs, just newlines/CR
$ IFS=$'\r\n' GLOBIGNORE='*' command eval 'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync
Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes ""
and braces {}
as in the example above
Edit:
Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around
With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)
Other notes:
Can also follow drizzt's suggestion below and replace a forked subshell+cat with
$(</etc/passwd)
The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this
A clean and flexible solution in MS SQL Server 2005/2008 is to create a CLR Agregate function.
You'll find quite a few articles (with code) on google.
It looks like this article walks you through the whole process using C#.
As your intuition correctly guessed, the naive solution with a pair of exists / writeFile
calls is wrong. Asynchronous code runs in unpredictable ways. And in given case it is
a.txt
? — No.a.txt
gets created by another program)a.txt
if it's possible. — Okay.But yes, we can do that in a single call. We're working with file system so it's a good idea to read developer manual on fs
. And hey, here's an interesting part.
'w' - Open file for writing. The file is created (if it does not exist) or truncated (if it exists).
'wx' - Like 'w' but fails if path exists.
So all we have to do is just add wx
to the fs.open
call. But hey, we don't like fopen
-like IO. Let's read on fs.writeFile
a bit more.
fs.readFile(filename[, options], callback)#
filename String
options Object
encoding String | Null default = null
flag String default = 'r'
callback Function
That options.flag
looks promising. So we try
fs.writeFile(path, data, { flag: 'wx' }, function (err) {
if (err) throw err;
console.log("It's saved!");
});
And it works perfectly for a single write. I guess this code will fail in some more bizarre ways yet if you try to solve your task with it. You have an atomary "check for a_#.jpg
existence, and write there if it's empty" operation, but all the other fs
state is not locked, and a_1.jpg
file may spontaneously disappear while you're already checking a_5.jpg
. Most* file systems are no ACID databases, and the fact that you're able to do at least some atomic operations is miraculous. It's very likely that wx
code won't work on some platform. So for the sake of your sanity, use database, finally.
Imagine we're writing something like memoize-fs
that caches results of function calls to the file system to save us some network/cpu time. Could we open the file for reading if it exists, and for writing if it doesn't, all in the single call? Let's take a funny look on those flags. After a while of mental exercises we can see that a+
does what we want: if the file doesn't exist, it creates one and opens it both for reading and writing, and if the file exists it does so without clearing the file (as w+
would). But now we cannot use it neither in (smth)File
, nor in create(Smth)Stream
functions. And that seems like a missing feature.
So feel free to file it as a feature request (or even a bug) to Node.js github, as lack of atomic asynchronous file system API is a drawback of Node. Though don't expect changes any time soon.
Edit. I would like to link to articles by Linus and by Dan Luu on why exactly you don't want to do anything smart with your fs
calls, because the claim was left mostly not based on anything.
Reference the System.Web
dll in your model and use System.Web.Caching.Cache
public string[] GetNames()
{
string[] names = Cache["names"] as string[];
if(names == null) //not in cache
{
names = DB.GetNames();
Cache["names"] = names;
}
return names;
}
A bit simplified but I guess that would work. This is not MVC specific and I have always used this method for caching data.
I had the same problem and following worked good, you should navigate main folder in your project than type:
source bin/activate
As others have mentioned, this is an old thread and even with this thread there tends to be different solutions that worked for different people. The solution that worked for is as follows:
Right Click Project Name > Properties
Linker > General
Output File > $(OutDir)$(TargetName)$(TargetExt) as indicated by @ReturnVoid
Click Apply
For whatever reason this initial correction didn't fix my problem (I'm using VS2015 Community to build c++ program). If you still get the error message try the following additional steps:
Back in Project > Properties > Linker > General > Output File >
You'll see the previously entered text in bold
Select Drop Down > Select "inherit from parent or project defaults"
Select Apply
Previously bold font is no longer bold
Build > Rebuild > Debug
It doesn't make since to me to require these additional steps in addition to what @ReturnVoid posted but...what works is what works...hope it helps someone else out too. Thanks @ReturnVoid
You can integrate both tidy and html-beautify automatically by installing the plugin vim-autoformat. After that, you can execute whichever formatter is installed with a single keystroke.
In case you want to be lazier:
#syntax lambda x : (false,true)[Condition]
In your case:
rate = lambda(T) : (400*exp(-T),200*exp(-T))[T>200]
Warning: The following answer is using Vue 1.x. The twoWay
data mutation is removed from Vue 2.x (fortunately!).
In case of "global" variables—that are attached to the global object, which is the window object in web browsers—the most reliable way to declare the variable is to set it on the global object explicitly:
window.hostname = 'foo';
However form Vue's hierarchy perspective (the root view Model and nested components) the data can be passed downwards (and can be mutated upwards if twoWay binding is specified).
For instance if the root viewModel has a hostname
data, the value can be bound to a nested component with v-bind
directive as v-bind:hostname="hostname"
or in short :hostname="hostname"
.
And within the component the bound value can be accessed through component's props
property.
Eventually the data will be proxied to this.hostname
and can be used inside the current Vue instance if needed.
var theGrandChild = Vue.extend({_x000D_
template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3>',_x000D_
props: ['foo', 'bar']_x000D_
});_x000D_
_x000D_
var theChild = Vue.extend({_x000D_
template: '<h2>My awesome component has a "{{foo}}"</h2> \_x000D_
<the-grandchild :foo="foo" :bar="bar"></the-grandchild>',_x000D_
props: ['foo'],_x000D_
data: function() {_x000D_
return {_x000D_
bar: 'bar'_x000D_
};_x000D_
},_x000D_
components: {_x000D_
'the-grandchild': theGrandChild_x000D_
}_x000D_
});_x000D_
_x000D_
_x000D_
// the root view model_x000D_
new Vue({_x000D_
el: 'body',_x000D_
data: {_x000D_
foo: 'foo'_x000D_
},_x000D_
components: {_x000D_
'the-child': theChild_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>_x000D_
<h1>The root view model has a "{{foo}}"</h1>_x000D_
<the-child :foo="foo"></the-child>
_x000D_
In cases that we need to mutate the parent's data upwards, we can add a .sync
modifier to our binding declaration like :foo.sync="foo"
and specify that the given 'props' is supposed to be a twoWay
bound data.
Hence by mutating the data in a component, the parent's data would be changed respectively.
For instance:
var theGrandChild = Vue.extend({_x000D_
template: '<h3>The nested component has also a "{{foo}}" and a "{{bar}}"</h3> \_x000D_
<input v-model="foo" type="text">',_x000D_
props: {_x000D_
'foo': {_x000D_
twoWay: true_x000D_
}, _x000D_
'bar': {}_x000D_
}_x000D_
});_x000D_
_x000D_
var theChild = Vue.extend({_x000D_
template: '<h2>My awesome component has a "{{foo}}"</h2> \_x000D_
<the-grandchild :foo.sync="foo" :bar="bar"></the-grandchild>',_x000D_
props: {_x000D_
'foo': {_x000D_
twoWay: true_x000D_
}_x000D_
},_x000D_
data: function() {_x000D_
return { bar: 'bar' };_x000D_
}, _x000D_
components: {_x000D_
'the-grandchild': theGrandChild_x000D_
}_x000D_
});_x000D_
_x000D_
// the root view model_x000D_
new Vue({_x000D_
el: 'body',_x000D_
data: {_x000D_
foo: 'foo'_x000D_
},_x000D_
components: {_x000D_
'the-child': theChild_x000D_
}_x000D_
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/1.0.16/vue.js"></script>_x000D_
<h1>The root view model has a "{{foo}}"</h1>_x000D_
<the-child :foo.sync="foo"></the-child>
_x000D_
I would like to add this, I used this in laravel to just index my table:
My Code:
@foreach($resultsPerCountry->first()->studies as $result)
<tr>
<td>{{ ++$loop->index}}</td>
</tr>
@endforeach
Have you tried using the ConflictResolution:=xlLocalSessionChanges parameter in the SaveAs method?
As so:
Public Sub example()
Application.DisplayAlerts = False
Application.EnableEvents = False
For Each element In sArray
XLSMToXLSX(element)
Next element
Application.DisplayAlerts = False
Application.EnableEvents = False
End Sub
Sub XLSMToXLSX(ByVal file As String)
Do While WorkFile <> ""
If Right(WorkFile, 4) <> "xlsx" Then
Workbooks.Open Filename:=myPath & WorkFile
Application.DisplayAlerts = False
Application.EnableEvents = False
ActiveWorkbook.SaveAs Filename:= _
modifiedFileName, FileFormat:= _
xlOpenXMLWorkbook, CreateBackup:=False, _
ConflictResolution:=xlLocalSessionChanges
Application.DisplayAlerts = True
Application.EnableEvents = True
ActiveWorkbook.Close
End If
WorkFile = Dir()
Loop
End Sub
Problems only surface when I am I trying to give the first loaded content an active state
Does this mean that you want to add a class to the first button?
$('.o-links').click(function(e) { // ... }).first().addClass('O_Nav_Current');
instead of using IDs for the slider's items and resetting html contents you can use classes and indexes:
CSS:
.image-area { width: 100%; height: auto; display: none; } .image-area:first-of-type { display: block; }
JavaScript:
var $slides = $('.image-area'), $btns = $('a.o-links'); $btns.on('click', function (e) { var i = $btns.removeClass('O_Nav_Current').index(this); $(this).addClass('O_Nav_Current'); $slides.filter(':visible').fadeOut(1000, function () { $slides.eq(i).fadeIn(1000); }); e.preventDefault(); }).first().addClass('O_Nav_Current');
I know this is old but I just ran into this problem and none of the answers are suitable. nickf's solution works but it requires javascript. The best way is to disable the field and still pass the value is to use a hidden input field to pass the value to the form. For example,
<input type="text" value="22.2222" disabled="disabled" />
<input type="hidden" name="lat" value="22.2222" />
This way the value is passed but the user sees the greyed out field. The readonly attribute does not gray it out.
OnClientClick="SomeMethod()"
event of that BUTTON, it return by default "true
" so after that function it do postback
for solution use
//use this code in BUTTON ==> OnClientClick="return SomeMethod();"
//and your function like this
<script type="text/javascript">
function SomeMethod(){
// put your code here
return false;
}
</script>
Try this: Goto project property -> C/C++ -> Code generation -> Runtime Library Select from combobox value : Multi-threaded DLL (/MD) It work for me :)
Default locations:
Programs > Microsoft SQL Server 2008 R2 > SQL Server Management Studio for Query Analyzer. Programs > Microsoft SQL Server 2008 R2 > Performance Tools > SQL Server Profiler for profiler.
In simplest terms :
Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).
Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.
a less-jquerish approach:
$('#mytable tr').each(function() {
if (!this.rowIndex) return; // skip first row
var customerId = this.cells[0].innerHTML;
});
this can obviously be changed to work with not-the-first cells.
You can load the form from a hidden div
element with the Bootstrap-provided hidden
class.
<button class="btn btn-default" id="form-popover">Form popover</button>
<div class="hidden">
<form id="form">
<input type="text" class="form-control" />
</form>
</div>
JavaScript:
$('#form-popover').popover({
content: $('#form').parent().html(),
html: true,
});
I think that C++.
Because c# needs additional instalation for C# runtime which only absorbs space on a disk. And C# is of course a bit slower.
Please look at the weightSum of LinearLayout and the layout_weight of each View. android:weightSum="4" android:layout_weight="2" android:layout_weight="2" Their layout_height are both 0px, but I am not sure it is relevan
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="4">
<fragment android:name="com.example.SettingFragment"
android:id="@+id/settingFragment"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="2"
/>
<Button
android:id="@+id/dummy_button"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="2"
android:text="DUMMY"
/>
</LinearLayout>
Wow! when you use src
then src
of searchPic
must be used also.
document["pic1"].src = searchPic.src
looks better
You can use the re
module for regexes, but regexes are probably overkill for what you want. I might try something like
z.write(article[:article.index("</html>") + 7]
This is much cleaner, and should be much faster than a regex based solution.
In TortiseSVN settings
right-click menu >> settings >> Saved data >> Authentication data [Clear]
The side effect is that it clears out all authentication data and you have to re-enter your own username/password.
I've always called them "compiler directives." They direct the compiler to do things, branching, including libs like shown above, disabling specific errors etc., during the compilation phase.
Compiler companies usually create their own extensions to facilitate their features. For example, (I believe) Microsoft started the "#pragma once" deal and it was only in MS products, now I'm not so sure.
Pragma Directives It includes "#pragma comment" in the table you'll see.
HTH
I suspect GCC, for example, has their own set of #pragma's.
if value.to_s == 'true'
true
elsif value.to_s == 'false'
false
end
See the relevel()
function. Here is an example:
set.seed(123)
x <- rnorm(100)
DF <- data.frame(x = x,
y = 4 + (1.5*x) + rnorm(100, sd = 2),
b = gl(5, 20))
head(DF)
str(DF)
m1 <- lm(y ~ x + b, data = DF)
summary(m1)
Now alter the factor b
in DF
by use of the relevel()
function:
DF <- within(DF, b <- relevel(b, ref = 3))
m2 <- lm(y ~ x + b, data = DF)
summary(m2)
The models have estimated different reference levels.
> coef(m1)
(Intercept) x b2 b3 b4 b5
3.2903239 1.4358520 0.6296896 0.3698343 1.0357633 0.4666219
> coef(m2)
(Intercept) x b1 b2 b4 b5
3.66015826 1.43585196 -0.36983433 0.25985529 0.66592898 0.09678759
For Windows, cd
by itself will show you the current working directory.
For UNIX and workalike systems, pwd
will perform the same task. You can also use the $PWD
shell variable under some shells. I am not sure if Windows supports getting the current working directory via a shell variable or not.
Specify complete path and grant proper permission to scriptfile. I tried following script file to run through cron:
#!/bin/bash
/bin/mkdir /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/crondir
And crontab command is
* * * * * /bin/bash /scratch/ofsaaweb/CHEF_FICHOME/ficdb/bin/test.sh
It worked for me.
Could not commit JPA transaction: Transaction marked as rollbackOnly
This exception occurs when you invoke nested methods/services also marked as @Transactional
. JB Nizet explained the mechanism in detail. I'd like to add some scenarios when it happens as well as some ways to avoid it.
Suppose we have two Spring services: Service1
and Service2
. From our program we call Service1.method1()
which in turn calls Service2.method2()
:
class Service1 {
@Transactional
public void method1() {
try {
...
service2.method2();
...
} catch (Exception e) {
...
}
}
}
class Service2 {
@Transactional
public void method2() {
...
throw new SomeException();
...
}
}
SomeException
is unchecked (extends RuntimeException) unless stated otherwise.
Scenarios:
Transaction marked for rollback by exception thrown out of method2
. This is our default case explained by JB Nizet.
Annotating method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating both method1
and method2
as @Transactional(readOnly = true)
still marks transaction for rollback (exception thrown when exiting from method1
).
Annotating method2
with @Transactional(noRollbackFor = SomeException)
prevents marking transaction for rollback (no exception thrown when exiting from method1
).
Suppose method2
belongs to Service1
. Invoking it from method1
does not go through Spring's proxy, i.e. Spring is unaware of SomeException
thrown out of method2
. Transaction is not marked for rollback in this case.
Suppose method2
is not annotated with @Transactional
. Invoking it from method1
does go through Spring's proxy, but Spring pays no attention to exceptions thrown. Transaction is not marked for rollback in this case.
Annotating method2
with @Transactional(propagation = Propagation.REQUIRES_NEW)
makes method2
start new transaction. That second transaction is marked for rollback upon exit from method2
but original transaction is unaffected in this case (no exception thrown when exiting from method1
).
In case SomeException
is checked (does not extend RuntimeException), Spring by default does not mark transaction for rollback when intercepting checked exceptions (no exception thrown when exiting from method1
).
See all scenarios tested in this gist.
One of the putty tools is pscp.exe; it will allow you to copy files from your remote host.
If you don't mind including the underscore as an allowed character, you could try simply:
result = subject.replace(/\W+/g, "");
If the underscore must be excluded also, then
result = subject.replace(/[^A-Z0-9]+/ig, "");
(Note the case insensitive flag)
I use them all the time. The only thing I worry about is giving away IP in log files. If your function names are really good you might be making a trade secret easier to uncover. It's sort of like shipping with debug symbols, only more difficult to find things. In 99.999% of the cases nothing bad will come of it.
HttpBasicAuth works for me with smaller changes
I use maven dependency
<dependency>
<groupId>net.iharder</groupId>
<artifactId>base64</artifactId>
<version>2.3.8</version>
</dependency>
Smaller change
String encoding = Base64.encodeBytes ((user + ":" + passwd).getBytes());
If you really want it to look more semantic like having the <body>
in the middle you can use the <main>
element. With all the recent advances the <body>
element is not as semantic as it once was but you just have to think of it as a wrapper in which the view port sees.
<html>
<head>
</head>
<body>
<header>
</header>
<main>
<section></section>
<article></article>
</main>
<footer>
</footer>
<body>
</html>
Pre-compiling the regex increases the speed. Re-using the Matcher gives you another slight speedup. If the method gets called frequently say gets called within a loop, the overall performace will certainly go up.
Like said above you can use
Date d = new Date();
or use
Calendar.getInstance();
or if you want it in millis
System.currentTimeMillis()
You can use this jQuery plugin I just made :) https://github.com/jpillora/jquery.rest/
Supports basic CRUD operations, nested resources, basic auth
var client = new $.RestClient('/api/rest/');
client.add('foo');
client.foo.add('baz');
client.add('bar');
client.foo.create({a:21,b:42});
// POST /api/rest/foo/ (with data a=21 and b=42)
client.foo.read();
// GET /api/rest/foo/
client.foo.read("42");
// GET /api/rest/foo/42/
client.foo.update("42");
// PUT /api/rest/foo/42/
client.foo.delete("42");
// DELETE /api/rest/foo/42/
//RESULTS USE '$.Deferred'
client.foo.read().success(function(foos) {
alert('Hooray ! I have ' + foos.length + 'foos !' );
});
If you find bugs or want new features, post them in the repositories 'Issues' page please
You can use the following code:
return RedirectToAction("Index", "Home");
See RedirectToAction
If you want to do this in VBA, then this is a shorter method:
Sub FillBlanksWithNull()
'This macro will fill all "blank" cells with the text "Null"
'When no range is selected, it starts at A1 until the last used row/column
'When a range is selected prior, only the blank cell in the range will be used.
On Error GoTo ErrHandler:
Selection.SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "Null"
Exit Sub
ErrHandler:
MsgBox "No blank cells found", vbDefaultButton1, Error
Resume Next
End Sub
Regards,
Robert Ilbrink
Quite simply, a "callable" is something that can be called like a method. The built in function "callable()" will tell you whether something appears to be callable, as will checking for a call property. Functions are callable as are classes, class instances can be callable. See more about this here and here.
I tried the above example with slight modification-
public static void main(final String[] args) {
System.out.println(test());
}
public static int test() {
int i = 0;
try {
i = 2;
return i;
} finally {
i = 12;
System.out.println("finally trumps return.");
}
}
The above code outputs:
finally trumps return.
2
This is because when return i;
is executed i
has a value 2. After this the finally
block is executed where 12 is assigned to i
and then System.out
out is executed.
After executing the finally
block the try
block returns 2, rather than returning 12, because this return statement is not executed again.
If you will debug this code in Eclipse then you'll get a feeling that after executing System.out
of finally
block the return
statement of try
block is executed again. But this is not the case. It simply returns the value 2.
My particular use-case was selecting a text range inside an editable span element, which, as far as I could see, is not described in any of the answers here.
The main difference is that you have to pass a node of type Text
to the Range
object, as described in the documentation of Range.setStart():
If the startNode is a Node of type Text, Comment, or CDATASection, then startOffset is the number of characters from the start of startNode. For other Node types, startOffset is the number of child nodes between the start of the startNode.
The Text
node is the first child node of a span element, so to get it, access childNodes[0]
of the span element. The rest is the same as in most other answers.
Here a code example:
var startIndex = 1;
var endIndex = 5;
var element = document.getElementById("spanId");
var textNode = element.childNodes[0];
var range = document.createRange();
range.setStart(textNode, startIndex);
range.setEnd(textNode, endIndex);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
Other relevant documentation:
Range
Selection
Document.createRange()
Window.getSelection()
This works for me...
#region AddressOf
/// <summary>
/// Provides the current address of the given object.
/// </summary>
/// <param name="obj"></param>
/// <returns></returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static System.IntPtr AddressOf(object obj)
{
if (obj == null) return System.IntPtr.Zero;
System.TypedReference reference = __makeref(obj);
System.TypedReference* pRef = &reference;
return (System.IntPtr)pRef; //(&pRef)
}
/// <summary>
/// Provides the current address of the given element
/// </summary>
/// <typeparam name="T"></typeparam>
/// <param name="t"></param>
/// <returns></returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static System.IntPtr AddressOf<T>(T t)
//refember ReferenceTypes are references to the CLRHeader
//where TOriginal : struct
{
System.TypedReference reference = __makeref(t);
return *(System.IntPtr*)(&reference);
}
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
static System.IntPtr AddressOfRef<T>(ref T t)
//refember ReferenceTypes are references to the CLRHeader
//where TOriginal : struct
{
System.TypedReference reference = __makeref(t);
System.TypedReference* pRef = &reference;
return (System.IntPtr)pRef; //(&pRef)
}
/// <summary>
/// Returns the unmanaged address of the given array.
/// </summary>
/// <param name="array"></param>
/// <returns><see cref="IntPtr.Zero"/> if null, otherwise the address of the array</returns>
[System.Runtime.CompilerServices.MethodImpl(System.Runtime.CompilerServices.MethodImplOptions.AggressiveInlining)]
public static System.IntPtr AddressOfByteArray(byte[] array)
{
if (array == null) return System.IntPtr.Zero;
fixed (byte* ptr = array)
return (System.IntPtr)(ptr - 2 * sizeof(void*)); //Todo staticaly determine size of void?
}
#endregion
Clicking Properties, going to the Service tab and setting Start Mode to Automatic fixed the problem for me. Now the Start item in the context menu is active again.
Check this basic code to setup html server. its work for me.
var http = require('http'), fs = require('fs'); fs.readFile('./index.html', function (err, html) { if (err) { throw err; } http.createServer(function(request, response) { response.writeHeader(200, {"Content-Type": "text/html"}); response.write(html); response.end(); }).listen(8000); });
Add a reference to the Outlook object model in the Visual Basic editor. Then you can use the code below to send an email using outlook.
Sub sendOutlookEmail()
Dim oApp As Outlook.Application
Dim oMail As MailItem
Set oApp = CreateObject("Outlook.application")
Set oMail = oApp.CreateItem(olMailItem)
oMail.Body = "Body of the email"
oMail.Subject = "Test Subject"
oMail.To = "[email protected]"
oMail.Send
Set oMail = Nothing
Set oApp = Nothing
End Sub
if ($done)
{
header("Location: /url/to/the/other/page");
exit;
}
If you have the stats toolbox, then you can compute
Z = zscore(S);
I would suggest the following:
String[] parsedInput = str.split("\n"); String firstName = parsedInput[0].split(": ")[1]; String lastName = parsedInput[1].split(": ")[1]; myMap.put(firstName,lastName);
Iframe
<iframe id="fred" style="border:1px solid #666CCC" title="PDF in an i-Frame" src="PDFData.pdf" frameborder="1" scrolling="auto" height="1100" width="850" ></iframe>
Object
<object data="your_url_to_pdf" type="application/pdf">
<embed src="your_url_to_pdf" type="application/pdf" />
</object>
Two issues jump out:
Your getData
never returns anything, so its promise (async
functions always return a promise) will resolve with undefined
when it resolves
The error message clearly shows you're trying to directly render the promise getData
returns, rather than waiting for it to resolve and then rendering the resolution
Addressing #1: getData
should return the result of calling json
:
async getData(){
const res = await axios('/data');
return await res.json();
}
Addressig #2: We'd have to see more of your code, but fundamentally, you can't do
<SomeElement>{getData()}</SomeElement>
...because that doesn't wait for the resolution. You'd need instead to use getData
to set state:
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
...and use that state when rendering:
<SomeElement>{this.state.data}</SomeElement>
Update: Now that you've shown us your code, you'd need to do something like this:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
this.getData().then(data => this.setState({data}))
.catch(err => { /*...handle the error...*/});
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
Futher update: You've indicated a preference for using await
in componentDidMount
rather than then
and catch
. You'd do that by nesting an async
IIFE function within it and ensuring that function can't throw. (componentDidMount
itself can't be async
, nothing will consume that promise.) E.g.:
class App extends React.Component{
async getData() {
const res = await axios('/data');
return await res.json(); // (Or whatever)
}
constructor(...args) {
super(...args);
this.state = {data: null};
}
componentDidMount() {
if (!this.state.data) {
(async () => {
try {
this.setState({data: await this.getData()});
} catch (e) {
//...handle the error...
}
})();
}
}
render() {
return (
<div>
{this.state.data ? <em>Loading...</em> : this.state.data}
</div>
);
}
}
jQuery and console.log
are unrelated entities, although useful when used together.
If you use a browser's built-in dev tools, console.log
will log information about the object being passed to the log
function.
If the console is not active, logging will not work, and may break your script. Be certain to check that the console exists before logging:
if (window.console) console.log('foo');
The shortcut form of this might be seen instead:
window.console&&console.log('foo');
There are other useful debugging functions as well, such as debug
, dir
and error
. Firebug's wiki lists the available functions in the console api.
add the line to your .bashrc
or .profile
. The variables set in $HOME/.profile
are active for the current user, the ones in /etc/profile
are global. The .bashrc
is pulled on each bash session start.
if you have number of columns in your database table more than number of columns in your csv you can proceed like this:
LOAD DATA LOCAL INFILE 'pathOfFile.csv'
INTO TABLE youTable
CHARACTER SET latin1 FIELDS TERMINATED BY ';' #you can use ',' if you have comma separated
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\r\n'
(yourcolumn,yourcolumn2,yourcolumn3,yourcolumn4,...);
This is a linker issue. Try:
g++ -o test_1 test_1.cpp `pkg-config opencv --cflags --libs`
This should work to compile the source. However, if you recently compiled OpenCV from source, you will meet linking issue in run-time, the library will not be found. In most cases, after compiling libraries from source, you need to do finally:
sudo ldconfig
You can use boost::optional
(or std::optional
for newer versions), which was developed in particular for decision of your problem:
boost::optional<int> y[50];
....
geoGraph.y[x] = nums[x];
....
const size_t size_y = sizeof(y)/sizeof(y[0]); //!!!! correct size of y!!!!
for(int i=0; i<size_y;i++){
if(y[i]) { //check for null
p[i].SetPoint(Recto.Height()-x,*y[i]);
....
}
}
P.S. Do not use C-type array -> use std::array or std::vector:
std::array<int, 50> y; //not int y[50] !!!
holy errors The reason for the code below is to show how to not void main every function and not to type return; for functions...... instead push everything into the sediment for which is the print function prototype... if you need to use useful functions ... you will have to below..... (p.s. this below is for people overwhelmed by these object and T templates which allow different variable declaration types(such as float and char) to use the same passed by value in a user defined function)
char arr[ ] = "This is a test";
string str(arr);
// You can also assign directly to a string.
str = "This is another string";
can anyone tell me why c++ made arrays into pass by value one at a time and the only way to eliminate spaces and punctuation is the use of string tokens. I couldn't get around the problem when i was trying to delete spaces for a palindrome...
#include <iostream>
#include <iomanip>
using namespace std;
int getgrades(float[]);
int getaverage(float[], float);
int calculateletters(float[], float, float, float[]);
int printResults(float[], float, float, float[]);
int main()
{
int i;
float maxSize=3, size;
float lettergrades[5], numericgrades[100], average;
size=getgrades(numericgrades);
average = getaverage(numericgrades, size);
printResults(numericgrades, size, average, lettergrades);
return 0;
}
int getgrades(float a[])
{
int i, max=3;
for (i = 0; i <max; i++)
{
//ask use for input
cout << "\nPlease Enter grade " << i+1 << " : ";
cin >> a[i];
//makes sure that user enters a vlue between 0 and 100
if(a[i] < 0 || a[i] >100)
{
cout << "Wrong input. Please
enter a value between 0 and 100 only." << endl;
cout << "\nPlease Reenter grade " << i+1 << " : ";
cin >> a[i];
return i;
}
}
}
int getaverage(float a[], float n)
{
int i;
float sum = 0;
if (n == 0)
return 0;
for (i = 0; i < n; i++)
sum += a[i];
return sum / n;
}
int printResults(float a[], float n, float average, float letters[])
{
int i;
cout << "Index Number | input |
array values address in memory " << endl;
for (i = 0; i < 3; i++)
{
cout <<" "<< i<<" \t\t"<<setprecision(3)<<
a[i]<<"\t\t" << &a[i] << endl;
}
cout<<"The average of your grades is: "<<setprecision(3)<<average<<endl;
}
Bootstrap Modal Events:
<script type="text/javascript">
$("#salesitems_modal").on('hide.bs.modal', function () {
//actions you want to perform after modal is closed.
});
</script>
I hope this will Help.
In order to initially set up any Git server, you have to export an existing repository into a new bare repository — a repository that doesn’t contain a working directory. This is generally straightforward to do. In order to clone your repository to create a new bare repository, you run the clone command with the --bare
option. By convention, bare repository directories end in .git
, like so:
$ git clone --bare my_project my_project.git
Initialized empty Git repository in /opt/projects/my_project.git/
This command takes the Git repository by itself, without a working directory, and creates a directory specifically for it alone.
Now that you have a bare copy of your repository, all you need to do is put it on a server and set up your protocols. Let’s say you’ve set up a server called git.example.com
that you have SSH access to, and you want to store all your Git repositories under the /opt/git
directory. You can set up your new repository by copying your bare repository over:
$ scp -r my_project.git [email protected]:/opt/git
At this point, other users who have SSH access to the same server which has read-access to the /opt/git
directory can clone your repository by running
$ git clone [email protected]:/opt/git/my_project.git
If a user SSHs into a server and has write access to the /opt/git/my_project.git
directory, they will also automatically have push access. Git will automatically add group write permissions to a repository properly if you run the git init command with the --shared
option.
$ ssh [email protected]
$ cd /opt/git/my_project.git
$ git init --bare --shared
It is very easy to take a Git repository, create a bare version, and place it on a server to which you and your collaborators have SSH access. Now you’re ready to collaborate on the same project.
One solution is to use a list/array:
var first_json = {"name":"joe", "age":27};
var second_json = {"name":"james", "age":32};
var jsons = new Array();
jsons.push(first_json);
jsons.push(second_json);
Result
jsons = [
{"name":"joe", "age":27},
{"name":"james", "age":32}
]
I was struggling for a while with this problem. Some of the solutions worked however some of my views where still being pushed up while others weren't... So it didn't completely solve my problem. In the end, what did the job was adding the following line of code to my manifest in the activity tag...
android:windowSoftInputMode="stateHidden|adjustPan|adjustResize"
Good luck
First off, this actually is being raised in the next version to 8MB
or 16MB
... but I think to put this into perspective, Eliot from 10gen (who developed MongoDB) puts it best:
EDIT: The size has been officially 'raised' to 16MB
So, on your blog example, 4MB is actually a whole lot.. For example, the full uncompresses text of "War of the Worlds" is only 364k (html): http://www.gutenberg.org/etext/36
If your blog post is that long with that many comments, I for one am not going to read it :)
For trackbacks, if you dedicated 1MB to them, you could easily have more than 10k (probably closer to 20k)
So except for truly bizarre situations, it'll work great. And in the exception case or spam, I really don't think you'd want a 20mb object anyway. I think capping trackbacks as 15k or so makes a lot of sense no matter what for performance. Or at least special casing if it ever happens.
-Eliot
I think you'd be pretty hard pressed to reach the limit ... and over time, if you upgrade ... you'll have to worry less and less.
The main point of the limit is so you don't use up all the RAM on your server (as you need to load all MB
s of the document into RAM when you query it.)
So the limit is some % of normal usable RAM on a common system ... which will keep growing year on year.
Note on Storing Files in MongoDB
If you need to store documents (or files) larger than 16MB
you can use the GridFS API which will automatically break up the data into segments and stream them back to you (thus avoiding the issue with size limits/RAM.)
Instead of storing a file in a single document, GridFS divides the file into parts, or chunks, and stores each chunk as a separate document.
GridFS uses two collections to store files. One collection stores the file chunks, and the other stores file metadata.
You can use this method to store images, files, videos, etc in the database much as you might in a SQL database. I have used this to even store multi gigabyte video files.
SparkSQl support writing programs using Dataset and Dataframe API, along with it need to support sql.
In order to support Sql on DataFrames, first it requires a table definition with column names are required, along with if it creates tables the hive metastore will get lot unnecessary tables, because Spark-Sql natively resides on hive. So it will create a temporary view, which temporarily available in hive for time being and used as any other hive table, once the Spark Context stop it will be removed.
In order to create the view, developer need an utility called createOrReplaceTempView
You can't call methods outside a method. Code like this cannot float around in the class.
You need something like:
public class MyClass {
UserInput input = new UserInput();
public void foo() {
input.name();
}
}
or inside a constructor:
public class MyClass {
UserInput input = new UserInput();
public MyClass() {
input.name();
}
}
I too have faced similar issue when i started to work on Hibernate. All in all i can say is in the createQuery one needs to pass the name of the entity class not the table name to which the entity is mapped to.
It's pandas
label-based selection, as explained here: https://pandas.pydata.org/pandas-docs/stable/indexing.html#selection-by-label
The boolean array is basically a selection method using a mask.
In my application which calls two services, I compared both Task.Run and Task.Factory.StartNew. I found that in my case both of them work fine. However, the second one is faster.
This will give you names and table count of all the databases in you mysql
SELECT TABLE_SCHEMA,COUNT(*) FROM information_schema.tables group by TABLE_SCHEMA;
Not sure what you are trying to do, but you have two select clauses. Do this instead:
SELECT *
FROM ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 181) AS A
JOIN ( SELECT *
FROM orders_products
INNER JOIN orders ON orders_products.orders_id = orders.orders_id
WHERE products_id = 180) AS B
ON A.orders_id=B.orders_id
Update:
You could probably reduce it to something like this:
SELECT o.orders_id,
op1.products_id,
op1.quantity,
op2.products_id,
op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id
WHERE op1.products_id = 180
AND op2.products_id = 181
It's easy, use a solid shadow with 0 offset:
#foo {
border-radius: 1px;
box-shadow: 0px 0px 0px 8px rgba(0,0,0,0.3);
}
Also, if you set a border-radius to the element, it gives you pretty rounded borders
1. In my opinion, the most convenient way is to search for one
occurrence first, and then invoke the following :substitute
command:
:%s///gc
Since the pattern is empty, this :substitute
command will look for
the occurrences of the last-used search pattern, and will then replace
them with the empty string, each time asking for user confirmation,
realizing exactly the desired behavior.
2. If it is a common pattern in one’s editing habits, one can further define a couple of text-object selection mappings to operate specifically on the match of the last search pattern under the cursor. The following two mappings can be used in both Visual and Operator-pending modes to select the text of the preceding match of the last search pattern.
vnoremap <silent> i/ :<c-u>call SelectMatch()<cr>
onoremap <silent> i/ :call SelectMatch()<cr>
function! SelectMatch()
if search(@/, 'bcW')
norm! v
call search(@/, 'ceW')
else
norm! gv
endif
endfunction
Using these mappings one can delete the match under the cursor with
di/
, or apply any other operator or visually select it with vi/
.
Java strings have .startsWith() and .contains() methods which will get you most of the way. For anything more complicated you'd have to use regex or write your own method.
The right solution is to use grep -v "word" file
, with its awk
equivalent:
awk '!/word/' file
However, if you happen to have a more complex situation in which you want, say, XXX
to appear and YYY
not to appear, then awk
comes handy instead of piping several grep
s:
awk '/XXX/ && !/YYY/' file
# ^^^^^ ^^^^^^
# I want it |
# I don't want it
You can even say something more complex. For example: I want those lines containing either XXX
or YYY
, but not ZZZ
:
awk '(/XXX/ || /YYY/) && !/ZZZ/' file
etc.
The standard best practice for REST APIs is to have a hyphen, not camelcase or underscores.
This comes from Mark Masse's "REST API Design Rulebook" from Oreilly.
In addition, note that Stack Overflow itself uses hyphens in the URL: .../hyphen-underscore-or-camelcase-as-word-delimiter-in-uris
As does WordPress: http://inventwithpython.com/blog/2012/03/18/how-much-math-do-i-need-to-know-to-program-not-that-much-actually
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
I think a quick and dirty way is to create a pipe between child and parent. When parent exits, children will receive a SIGPIPE.
Short answer: Use the change
event. Here's a couple of practical examples. Since I misread the question, I'll include jQuery examples along with plain JavaScript. You're not gaining much, if anything, by using jQuery though.
Using querySelector
.
var checkbox = document.querySelector("input[name=checkbox]");
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log("Checkbox is checked..");
} else {
console.log("Checkbox is not checked..");
}
});
_x000D_
<input type="checkbox" name="checkbox" />
_x000D_
$('input[name=checkbox]').change(function() {
if ($(this).is(':checked')) {
console.log("Checkbox is checked..")
} else {
console.log("Checkbox is not checked..")
}
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" name="checkbox" />
_x000D_
Here's an example of a list of checkboxes. To select multiple elements we use querySelectorAll
instead of querySelector
. Then use Array.filter
and Array.map
to extract checked values.
// Select all checkboxes with the name 'settings' using querySelectorAll.
var checkboxes = document.querySelectorAll("input[type=checkbox][name=settings]");
let enabledSettings = []
/*
For IE11 support, replace arrow functions with normal functions and
use a polyfill for Array.forEach:
https://vanillajstoolkit.com/polyfills/arrayforeach/
*/
// Use Array.forEach to add an event listener to each checkbox.
checkboxes.forEach(function(checkbox) {
checkbox.addEventListener('change', function() {
enabledSettings =
Array.from(checkboxes) // Convert checkboxes to an array to use filter and map.
.filter(i => i.checked) // Use Array.filter to remove unchecked checkboxes.
.map(i => i.value) // Use Array.map to extract only the checkbox values from the array of objects.
console.log(enabledSettings)
})
});
_x000D_
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
let checkboxes = $("input[type=checkbox][name=settings]")
let enabledSettings = [];
// Attach a change event handler to the checkboxes.
checkboxes.change(function() {
enabledSettings = checkboxes
.filter(":checked") // Filter out unchecked boxes.
.map(function() { // Extract values using jQuery map.
return this.value;
})
.get() // Get array.
console.log(enabledSettings);
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<label>
<input type="checkbox" name="settings" value="forcefield">
Enable forcefield
</label>
<label>
<input type="checkbox" name="settings" value="invisibilitycloak">
Enable invisibility cloak
</label>
<label>
<input type="checkbox" name="settings" value="warpspeed">
Enable warp speed
</label>
_x000D_
The window.navigator.platform property is not spoofed when the userAgent string is changed. I tested on my Mac if I change the userAgent to iPhone or Chrome Windows, navigator.platform remains MacIntel.
The property is also read-only
I could came up with the following table
Mac Computers
Mac68K
Macintosh 68K system.
MacPPC
Macintosh PowerPC system.
MacIntel
Macintosh Intel system.iOS Devices
iPhone
iPhone.
iPod
iPod Touch.
iPad
iPad.
Modern macs returns navigator.platform == "MacIntel"
but to give some "future proof" don't use exact matching, hopefully they will change to something like MacARM
or MacQuantum
in future.
var isMac = navigator.platform.toUpperCase().indexOf('MAC')>=0;
To include iOS that also use the "left side"
var isMacLike = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);
var isIOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);
var is_OSX = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
var is_iOS = /(iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
var is_Mac = navigator.platform.toUpperCase().indexOf('MAC') >= 0;_x000D_
var is_iPhone = navigator.platform == "iPhone";_x000D_
var is_iPod = navigator.platform == "iPod";_x000D_
var is_iPad = navigator.platform == "iPad";_x000D_
_x000D_
/* Output */_x000D_
var out = document.getElementById('out');_x000D_
if (!is_OSX) out.innerHTML += "This NOT a Mac or an iOS Device!";_x000D_
if (is_Mac) out.innerHTML += "This is a Mac Computer!\n";_x000D_
if (is_iOS) out.innerHTML += "You're using an iOS Device!\n";_x000D_
if (is_iPhone) out.innerHTML += "This is an iPhone!";_x000D_
if (is_iPod) out.innerHTML += "This is an iPod Touch!";_x000D_
if (is_iPad) out.innerHTML += "This is an iPad!";_x000D_
out.innerHTML += "\nPlatform: " + navigator.platform;
_x000D_
<pre id="out"></pre>
_x000D_
Since most O.S. use the close button on the right, you can just move the close button to the left when the user is on a MacLike O.S., otherwise isn't a problem if you put it on the most common side, the right.
setTimeout(test, 1000); //delay for demonstration_x000D_
_x000D_
function test() {_x000D_
_x000D_
var mac = /(Mac|iPhone|iPod|iPad)/i.test(navigator.platform);_x000D_
_x000D_
if (mac) {_x000D_
document.getElementById('close').classList.add("left");_x000D_
}_x000D_
}
_x000D_
#window {_x000D_
position: absolute;_x000D_
margin: 1em;_x000D_
width: 300px;_x000D_
padding: 10px;_x000D_
border: 1px solid gray;_x000D_
background-color: #DDD;_x000D_
text-align: center;_x000D_
box-shadow: 0px 1px 3px #000;_x000D_
}_x000D_
#close {_x000D_
position: absolute;_x000D_
top: 0px;_x000D_
right: 0px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
margin: -12px;_x000D_
box-shadow: 0px 1px 3px #000;_x000D_
background-color: #000;_x000D_
border: 2px solid #FFF;_x000D_
border-radius: 22px;_x000D_
color: #FFF;_x000D_
text-align: center;_x000D_
font: 14px"Comic Sans MS", Monaco;_x000D_
}_x000D_
#close.left{_x000D_
left: 0px;_x000D_
}
_x000D_
<div id="window">_x000D_
<div id="close">x</div>_x000D_
<p>Hello!</p>_x000D_
<p>If the "close button" change to the left side</p>_x000D_
<p>you're on a Mac like system!</p>_x000D_
</div>
_x000D_
http://www.nczonline.net/blog/2007/12/17/don-t-forget-navigator-platform/
See below, would welcome anyones feedback on the below code.
not common between two arrays:
List<String> l3 =list1.stream().filter(x -> !list2.contains(x)).collect(Collectors.toList());
Common between two arrays:
List<String> l3 =list1.stream().filter(x -> list2.contains(x)).collect(Collectors.toList());
Response headers are generally set on the server. Set 'Access-Control-Allow-Headers'
to 'Content-Type'
on server side
I've just jumped into the same issue and I solved it substituting 'button' tag to 'span' tag. In my case I'm using bootstrap. This is how it looks like:
<a href="#register">
<span class="btn btn-default btn-lg">
Subscribe
</span>
</a>
In MVVM (wich makes a lot of things a lot easier - you should try it) you would have two properties in your ViewModel Text
that is bound to your TextBox and you would have an ICommand
property Apply
(or similar) that is bound to the button:
<Button Command="Apply">Apply</Button>
The ICommand
interface has a Method CanExecute
that is where you return true
if (!string.IsNullOrWhiteSpace(this.Text)
. The rest is done by WPF for you (enabling/disabling, executing the actual command on click).
The linked article explains it in detail.
Using OLE Query, it's quite simple (e.g. sheetName is Sheet1):
DataTable LoadWorksheetInDataTable(string fileName, string sheetName)
{
DataTable sheetData = new DataTable();
using (OleDbConnection conn = this.returnConnection(fileName))
{
conn.Open();
// retrieve the data using data adapter
OleDbDataAdapter sheetAdapter = new OleDbDataAdapter("select * from [" + sheetName + "$]", conn);
sheetAdapter.Fill(sheetData);
conn.Close();
}
return sheetData;
}
private OleDbConnection returnConnection(string fileName)
{
return new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fileName + "; Jet OLEDB:Engine Type=5;Extended Properties=\"Excel 8.0;\"");
}
For newer Excel versions:
return new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + fileName + ";Extended Properties=Excel 12.0;");
You can also use Excel Data Reader an open source project on CodePlex. Its works really well to export data from Excel sheets.
The sample code given on the link specified:
FileStream stream = File.Open(filePath, FileMode.Open, FileAccess.Read);
//1. Reading from a binary Excel file ('97-2003 format; *.xls)
IExcelDataReader excelReader = ExcelReaderFactory.CreateBinaryReader(stream);
//...
//2. Reading from a OpenXml Excel file (2007 format; *.xlsx)
IExcelDataReader excelReader = ExcelReaderFactory.CreateOpenXmlReader(stream);
//...
//3. DataSet - The result of each spreadsheet will be created in the result.Tables
DataSet result = excelReader.AsDataSet();
//...
//4. DataSet - Create column names from first row
excelReader.IsFirstRowAsColumnNames = true;
DataSet result = excelReader.AsDataSet();
//5. Data Reader methods
while (excelReader.Read())
{
//excelReader.GetInt32(0);
}
//6. Free resources (IExcelDataReader is IDisposable)
excelReader.Close();
Reference: How do I import from Excel to a DataSet using Microsoft.Office.Interop.Excel?
An alternative solution for preventing functions to change the user par
. You can set the default parameters early on the function, so that the graphical parameters and layout will not be changed during the function execution. See ?on.exit
for further details.
on.exit(layout(1))
opar<-par(no.readonly=TRUE)
on.exit(par(opar),add=TRUE,after=FALSE)
You can write different sheets as follows
$objPHPExcel = new PHPExcel();
$objPHPExcel->getProperties()->setCreator("creater");
$objPHPExcel->getProperties()->setLastModifiedBy("Middle field");
$objPHPExcel->getProperties()->setSubject("Subject");
$objWorkSheet = $objPHPExcel->createSheet();
$work_sheet_count=3;//number of sheets you want to create
$work_sheet=0;
while($work_sheet<=$work_sheet_count){
if($work_sheet==0){
$objWorkSheet->setTitle("Worksheet$work_sheet");
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 1')->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
}
if($work_sheet==1){
$objWorkSheet->setTitle("Worksheet$work_sheet");
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 2')->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
}
if($work_sheet==2){
$objWorkSheet = $objPHPExcel->createSheet($work_sheet_count);
$objWorkSheet->setTitle("Worksheet$work_sheet");
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValue('A1', 'SR No. In sheet 3')->getStyle('A1')->getFont()->setBold(true);
$objPHPExcel->setActiveSheetIndex($work_sheet)->setCellValueByColumnAndRow($col++, $row++, $i++);//setting value by column and row indexes if needed
}
$work_sheet++;
}
$filename='file-name'.'.xls'; //save our workbook as this file name
header('Content-Type: application/vnd.ms-excel'); //mime type
header('Content-Disposition: attachment;filename="'.$filename.'"'); //tell browser what's the file name
header('Cache-Control: max-age=0'); //no cach
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
$objWriter->save('php://output');
A URL of the form https://github.com/<owner>/<project>/commit/<hash>
will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:
https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685
You can also shorten the hash to any unique prefix, like so:
https://github.com/jerith666/git-graph/commit/35e32b
I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):
git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685
Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.
I think you should be able to use a default route handler and redirect from there to a page outside the app, as detailed below:
const ROUTER_INSTANCE = new VueRouter({
mode: "history",
routes: [
{ path: "/", component: HomeComponent },
// ... other routes ...
// and finally the default route, when none of the above matches:
{ path: "*", component: PageNotFound }
]
})
In the above PageNotFound
component definition, you can specify the actual redirect, that will take you out of the app entirely:
Vue.component("page-not-found", {
template: "",
created: function() {
// Redirect outside the app using plain old javascript
window.location.href = "/my-new-404-page.html";
}
}
You may do it either on created
hook as shown above, or mounted
hook also.
Please note:
I have not verified the above. You need to build a production version of app, ensure that the above redirect happens. You cannot test this in vue-cli
as it requires server side handling.
Usually in single page apps, server sends out the same index.html along with app scripts for all route requests, especially if you have set <base href="/">
. This will fail for your /404-page.html
unless your server treats it as a special case and serves the static page.
Let me know if it works!
Update for Vue 3 onward:
You'll need to replace the '*'
path property with '/:pathMatch(.*)*'
if you're using Vue 3 as the old catch-all path of '*'
is no longer supported. The route would then look something like this:
{ path: '/:pathMatch(.*)*', component: PathNotFound },
See the docs for more info on this update.
In response to the answer by Tatu I have created a quick jsFiddle for showcasing his solution:
http://jsfiddle.net/duwood/sTX7y/
HTML
<p>Paste excel data here:</p>
<textarea name="excel_data" style="width:250px;height:150px;"></textarea><br>
<input type="button" onclick="javascript:generateTable()" value="Genereate Table"/>
<br><br>
<p>Table data will appear below</p>
<hr>
<div id="excel_table"></div>
JS
function generateTable() {
var data = $('textarea[name=excel_data]').val();
console.log(data);
var rows = data.split("\n");
var table = $('<table />');
for(var y in rows) {
var cells = rows[y].split("\t");
var row = $('<tr />');
for(var x in cells) {
row.append('<td>'+cells[x]+'</td>');
}
table.append(row);
}
// Insert into DOM
$('#excel_table').html(table);
}
You can try one even more simple:
<option value="1" ${item.quantity == 1 ? "selected" : ""}>1</option>
Here i post my code, after i have pushed myself for one working day to find this solution.
Function to get the last saved record :
private function getLastId($query) {
$conn = $this->getDoctrine()->getConnection();
$stmt = $conn->prepare($query);
$stmt->execute();
$lastId = $stmt->fetch()['id'];
return $lastId;
}
Another Function which call the above function
private function clientNum() {
$lastId = $this->getLastId("SELECT id FROM client ORDER BY id DESC LIMIT 1");
$noClient = 'C' . sprintf("%06d", $lastId + 1); // C000002 if the last record ID is 1
return $noClient;
}
you can use this command by getting your data. this will extract your data...
select * from employees where to_char(es_date,'dd/mon/yyyy')='17/jun/2003';
I had this issue and realised that whilst I did have libxml2 installed, I didn't have the necessary development libraries required by the python package. Installing them solved the problem:
sudo apt-get install libxml2-dev libxslt1-dev
sudo pip install lxml
Type properties can't be changed you need to replace or overlay the input with a text input and send the value to the password input on submit.
This is a great spot for a reduce
var uniqueArray = o.DATA.reduce(function (a, d) {
if (a.indexOf(d.name) === -1) {
a.push(d.name);
}
return a;
}, []);
Personally, I like to use named entities when they are available, because they make my HTML more readable. Because of that, I like to use ✓
for ✓ and ✗
for ✗. If you're not sure whether a named entity exists for the character you want, try the &what search site. It includes the name for each entity, if there is one.
As mentioned in the comments, ✓
and ✗
are not supported in HTML4, so you may be better off using the more cryptic ✓
and ✗
if you want to target the most browsers. The most definitive references I could find were on the W3C site: HTML4 and HTML5.
You can delete everything and recreate database + seeds with both:
rake db:reset
: loads from schema.rbrake db:drop db:create db:migrate db:seed
: loads from migrationsMake sure you have no connections to db (rails server, sql client..) or the db won't drop.
schema.rb is a snapshot of the current state of your database generated by:
rake db:schema:dump
For Sharepoint 2007
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS
The only way I've managed to do this is by using overflow: visible;
and width: 20000px;
on the parent element. There is no way to do this with CSS level 1 that I'm aware of and I refused to think I'd have to go all gung-ho with CSS level 3. The example below has 18 menus that extend beyond my 1920x1200 resolution LCD, if your screen is larger just duplicate the first tier menu elements or just resize the browser. Alternatively and with slightly lower levels of browser compatibility you could use CSS3 media queries.
Here is a full copy/paste example demonstration...
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
<title>XHTML5 Menu Demonstration</title>
<style type="text/css">
* {border: 0; box-sizing: content-box; color: #f0f; font-size: 10px; margin: 0; padding: 0; transition-property: background-color, background-image, border, box-shadow, color, float, opacity, text-align, text-shadow; transition-duration: 0.5s; white-space: nowrap;}
a:link {color: #79b; text-decoration: none;}
a:visited {color: #579;}
a:focus, a:hover {color: #fff; text-decoration: underline;}
body {background-color: #444; overflow-x: hidden;}
body > header {background-color: #000; height: 64px; left: 0; position: absolute; right: 0; z-index: 2;}
body > header > nav {height: 32px; margin-left: 16px;}
body > header > nav a {font-size: 24px;}
main {border-color: transparent; border-style: solid; border-width: 64px 0 0; bottom: 0px; left: 0; overflow-x: hidden !important; overflow-y: auto; position: absolute; right: 0; top: 0; z-index: 1;}
main > * > * {background-color: #000;}
main > section {float: left; margin-top: 16px; width: 100%;}
nav[id='menu'] {overflow: visible; width: 20000px;}
nav[id='menu'] > ul {height: 32px;}
nav[id='menu'] > ul > li {float: left; width: 140px;}
nav[id='menu'] > ul > li > ul {background-color: rgba(0, 0, 0, 0.8); display: none; margin-left: -50px; width: 240px;}
nav[id='menu'] a {display: block; height: 32px; line-height: 32px; text-align: center; white-space: nowrap;}
nav[id='menu'] > ul {float: left; list-style:none;}
nav[id='menu'] ul li:hover ul {display: block;}
p, p *, span, span * {color: #fff;}
p {font-size: 20px; margin: 0 14px 0 14px; padding-bottom: 14px; text-indent: 1.5em;}
.hidden {display: none;}
.width_100 {width: 100%;}
</style>
</head>
<body>
<main>
<section style="height: 2000px;"><p>Hover the first menu at the top-left.</p></section>
</main>
<header>
<nav id="location"><a href="">Example</a><span> - </span><a href="">Blog</a><span> - </span><a href="">Browser Market Share</a></nav>
<nav id="menu">
<ul>
<li><a href="" tabindex="2">Menu 1 - Hover</a>
<ul>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
<li><a href="" tabindex="2">Menu 1 B</a></li>
</ul>
</li>
<li><a href="" tabindex="2">Menu 2</a></li>
<li><a href="" tabindex="2">Menu 3</a></li>
<li><a href="" tabindex="2">Menu 4</a></li>
<li><a href="" tabindex="2">Menu 5</a></li>
<li><a href="" tabindex="2">Menu 6</a></li>
<li><a href="" tabindex="2">Menu 7</a></li>
<li><a href="" tabindex="2">Menu 8</a></li>
<li><a href="" tabindex="2">Menu 9</a></li>
<li><a href="" tabindex="2">Menu 10</a></li>
<li><a href="" tabindex="2">Menu 11</a></li>
<li><a href="" tabindex="2">Menu 12</a></li>
<li><a href="" tabindex="2">Menu 13</a></li>
<li><a href="" tabindex="2">Menu 14</a></li>
<li><a href="" tabindex="2">Menu 15</a></li>
<li><a href="" tabindex="2">Menu 16</a></li>
<li><a href="" tabindex="2">Menu 17</a></li>
<li><a href="" tabindex="2">Menu 18</a></li>
</ul>
</nav>
</header>
</body>
</html>
This answer comes a little bit late, but I just was in a similar need.
Observing the comments written by @ganaraj in the question, One use case I was in the need of is, passing a classname via a directive attribute to be added to a ng-repeat li tag in the template.
For example, use the directive like this:
<my-directive class2add="special-class" />
And get the following html:
<div>
<ul>
<li class="special-class">Item 1</li>
<li class="special-class">Item 2</li>
</ul>
</div>
The solution found here applied with templateUrl, would be:
app.directive("myDirective", function() {
return {
template: function(element, attrs){
return '<div><ul><li ng-repeat="item in items" class="'+attrs.class2add+'"></ul></div>';
},
link: function(scope, element, attrs) {
var list = element.find("ul");
}
}
});
Just tried it successfully with AngularJS 1.4.9.
Hope it helps.
gzip > stdin.gz
perhaps? Otherwise, you need to flesh out your question.
It is a unary "+" operator which yields a numeric expression. It would be the same as d*1
, I believe.
UIKit
uses the topLayoutGuide & bottomLayoutGuide which is UIView
propertyiOS11+ uses safeAreaLayoutGuide which is also UIView
property
Enable Safe Area Layout Guide check box from file inspector.
Safe areas help you place your views within the visible portion of the overall interface.
In tvOS, the safe area also includes the screen’s overscan insets, which represent the area covered by the screen’s bezel.
Use safe areas as an aid to laying out your content like UIButton
etc.
When designing for iPhone X, you must ensure that layouts fill the screen and aren't obscured by the device's rounded corners, sensor housing, or the indicator for accessing the Home screen.
Make sure backgrounds extend to the edges of the display, and that vertically scrollable layouts, like tables and collections, continue all the way to the bottom.
The status bar is taller on iPhone X than on other iPhones. If your app assumes a fixed status bar height for positioning content below the status bar, you must update your app to dynamically position content based on the user's device. Note that the status bar on iPhone X doesn't change height when background tasks like voice recording and location tracking are active
print(UIApplication.shared.statusBarFrame.height)//44 for iPhone X, 20 for other iPhones
Height of home indicator container is 34 points.
Once you enable Safe Area Layout Guide you can see safe area constraints property listed in the interface builder.
You can set constraints with respective of self.view.safeAreaLayoutGuide
as-
ObjC:
self.demoView.translatesAutoresizingMaskIntoConstraints = NO;
UILayoutGuide * guide = self.view.safeAreaLayoutGuide;
[self.demoView.leadingAnchor constraintEqualToAnchor:guide.leadingAnchor].active = YES;
[self.demoView.trailingAnchor constraintEqualToAnchor:guide.trailingAnchor].active = YES;
[self.demoView.topAnchor constraintEqualToAnchor:guide.topAnchor].active = YES;
[self.demoView.bottomAnchor constraintEqualToAnchor:guide.bottomAnchor].active = YES;
Swift:
demoView.translatesAutoresizingMaskIntoConstraints = false
if #available(iOS 11.0, *) {
let guide = self.view.safeAreaLayoutGuide
demoView.trailingAnchor.constraint(equalTo: guide.trailingAnchor).isActive = true
demoView.leadingAnchor.constraint(equalTo: guide.leadingAnchor).isActive = true
demoView.bottomAnchor.constraint(equalTo: guide.bottomAnchor).isActive = true
demoView.topAnchor.constraint(equalTo: guide.topAnchor).isActive = true
} else {
NSLayoutConstraint(item: demoView, attribute: .leading, relatedBy: .equal, toItem: view, attribute: .leading, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .trailing, relatedBy: .equal, toItem: view, attribute: .trailing, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .bottom, relatedBy: .equal, toItem: view, attribute: .bottom, multiplier: 1.0, constant: 0).isActive = true
NSLayoutConstraint(item: demoView, attribute: .top, relatedBy: .equal, toItem: view, attribute: .top, multiplier: 1.0, constant: 0).isActive = true
}
If your output is delimited by tabs a quick solution would be to use the tabs
command to adjust the size of your tabs.
tabs 20
keys | awk '{ print $1"\t\t" $2 }'
<form id="mailajob" method="post" action="emailthijob.php">
<input type="hidden" name="action" value="emailjob" />
<input type="hidden" name="jid" value="<?php echo $jobid; ?>" />
</form>
<a class="emailjob" onclick="document.getElementById('mailajob').submit();">Email this job</a>
The simplest and fastest solution that I found in the pip issue discussion is:
pip install pipdate
pipdate
Should be probably changed to
firstName = firstName.trim().replaceAll("\\.", "");
If you prefer it without:
flexbox / grid / table
or without the:
vertical-align: middle
You can do:
HTML
<div class="box">
<h2 class="box_label">square</h2>
</div>
CSS
.box {
box-sizing: border-box;
width: 100px;
height: 100px;
text-align: center;
border: 1px solid black;
}
.box_label {
box-sizing: border-box;
display: inline-block;
transform: translateY(50%);
text-align: center;
border: 1px solid black;
}
You don't need remove, just add again.
cordova plugin add https://github.com/apache/cordova-plugin-camera
Use CMAKE_PREFIX_PATH by adding multiple paths (separated by semicolons and no white spaces). You can set it as an environmental variable to avoid having absolute paths in your cmake configuration files
Notice that cmake will look for config file in any of the following folders where is any of the path in CMAKE_PREFIX_PATH and name is the name of the library you are looking for
<prefix>/ (W)
<prefix>/(cmake|CMake)/ (W)
<prefix>/<name>*/ (W)
<prefix>/<name>*/(cmake|CMake)/ (W)
<prefix>/(lib/<arch>|lib|share)/cmake/<name>*/ (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/ (U)
<prefix>/(lib/<arch>|lib|share)/<name>*/(cmake|CMake)/ (U)
In your case you need to add to CMAKE_PREFIX_PATH the following two paths:
D:/develop/cmake/libs/libA;D:/develop/cmake/libB
In case of ActionLink, it generally uses HttpUtility.Encode on the link text.
In that case
you can use
HttpUtility.HtmlDecode(myString)
it worked for me when using HtmlActionLink to decode the string that I wanted to pass. eg:
@Html.ActionLink(HttpUtility.HtmlDecode("myString","ActionName",..)
You can do it programatically: Or without action bar
//It's enough to remove the line
requestWindowFeature(Window.FEATURE_NO_TITLE);
//But if you want to display full screen (without action bar) write too
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.your_activity);
i had the same problem replacing with
static NSString *CellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell==nil) {
cell = [[UITableViewCell alloc]initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
solved
A Swift 3 solution along the lines of Sunkas's:
extension String {
mutating func replace(_ originalString:String, with newString:String) {
self = self.replacingOccurrences(of: originalString, with: newString)
}
}
Use:
var string = "foo!"
string.replace("!", with: "?")
print(string)
Output:
foo?
Basically, an application pool is a way to create compartments in a web server through process boundaries, and route sets of URLs to each of these compartments. See more info here: http://technet.microsoft.com/en-us/library/cc735247(WS.10).aspx
Add the class to the div you want to be scrollable.
overflow-x: hidden; hides the horizantal scrollbar. While overflow-y: scroll; allows you to scroll vertically.
<!DOCTYPE html>
<html>
<head>
<style>
.scroll {
width: 500px;
height: 300px;
overflow-x: hidden;
overflow-y: scroll;
}
</style>
</head>
<body>
<div class="scroll"><h1> DATA </h1></div>
The following may help (study the impacts of disable-verity
first):
adb root
adb disable-verity
adb reboot
I had the same error code when I was running npm run build inside node docker container.
Locally it was working while inside a container I had set option to throw error when there is a warning during compilation while locally it wasn't set. So this error can mean anything that is connected with stopping the process being done by NPM
Edit: I just noted that you are trying to use a gmail address as the from value. This is not going to work, and the ISP is right in overwriting it. If you want to redirect the replies to your outgoing messages, use reply-to
.
A workaround for valid addresses that works with many ISPs:
try adding a fifth parameter to your mail()
command:
mail($to,$subject,$message,$headers,"-f [email protected]");
You could always use ADO to write the results out to the worksheet cells from a recordset object
The primary flag seems to only work for vagrant ssh
for me.
In the past I have used the following method to hack around the issue.
# stage box intended for configuration closely matching production if ARGV[1] == 'stage' config.vm.define "stage" do |stage| box_setup stage, \ "10.9.8.31", "deploy/playbook_full_stack.yml", "deploy/hosts/vagrant_stage.yml" end end
You can also use DateTime.Now.ToString("yyyy-MM-dd")
for the date, and DateTime.Now.ToString("hh:mm:ss")
for the time.
// set
$_SESSION['test'] = 1;
// destroy
unset($_SESSION['test']);
Java and JavaScript are a fairly bad example to demonstrate this difference, because both are interpreted languages. Java (interpreted) and C (or C++) (compiled) might have been a better example.
Why the striked-through text? As this answer correctly points out, interpreted/compiled is about a concrete implementation of a language, not about the language per se. While statements like "C is a compiled language" are generally true, there's nothing to stop someone from writing a C language interpreter. In fact, interpreters for C do exist.
Basically, compiled code can be executed directly by the computer's CPU. That is, the executable code is specified in the CPU's "native" language (assembly language).
The code of interpreted languages however must be translated at run-time from any format to CPU machine instructions. This translation is done by an interpreter.
Another way of putting it is that interpreted languages are code is translated to machine instructions step-by-step while the program is being executed, while compiled languages have code has been translated before program execution.
If you can make an approximation of the number of items that will be there at the end, use the overload of the List constuctor that takes count as a parameter. You will save some expensive List duplications. Otherwise you have to pay for it.
I defined following helper class:
import traceback
class TracedExeptions(object):
def __init__(self):
pass
def __enter__(self):
pass
def __exit__(self, etype, value, tb):
if value :
if not hasattr(value, 'traceString'):
value.traceString = "\n".join(traceback.format_exception(etype, value, tb))
return False
return True
Which I can later use like this:
with TracedExeptions():
#some-code-which-might-throw-any-exception
And later can consume it like this:
def log_err(ex):
if hasattr(ex, 'traceString'):
print("ERROR:{}".format(ex.traceString));
else:
print("ERROR:{}".format(ex));
(Background: I was frustraded because of using Promise
s together with Exception
s, which unfortunately passes exceptions raised in one place to a on_rejected handler in another place, and thus it is difficult to get the traceback from original location)
OAuth builds authentication on top of authorization: The user delegates access to their identity to the application, which, then, becomes a consumer of the identity API, thereby finding out who authorized the client in the first place http://oauth.net/articles/authentication/
try this code to create a button and repeat it for 2 more times with different coordinates and the method(myButtonClick) is called when the button is pressed
UIButton *editButton = [UIButton buttonWithType: UIButtonTypeCustom];
editButton.frame = CGRectMake(0, 0, width, height);
[editButton setBackgroundImage: editButtonImage forState: UIControlStateNormal];
[myButton addTarget:self action:@selector(myButtonClick:) forControlEvents:UIControlEventTouchUpInside];
editButton.adjustsImageWhenHighlighted = YES;
editButton.titleLabel.text = @"Edit";
editButton.titleLabel.textColor = [UIColor whiteColor];
editButton.titleLabel.textAlignment = UITextAlignmentCenter;
editButton.titleLabel.font = [UIFont fontWithName: @"Helvetica" size: 14];
[self.view addSubview: editButton];
-(void) myButtonClick:(NSString *)myString{
NSLog(@"you clicked on button %@", myString);
}
This file is contained in the standard JDK download. Also your Linux system probably have JDK in the repository. In my Ubuntu Linux file is located here: /usr/lib/jvm/java-6-sun-1.6.0.20/src.zip
At the time of writing this I have discovered that chromedriver 2.46 or 2.36 works well with Chrome 75.0.3770.100
Documentation here: http://chromedriver.chromium.org/downloads states align driver and browser alike but I found I had issues even with the most up-to-date driver when using Chrome 75
I am running Selenium 2 on Windows 10 Machine.
original answer moved to this topic .
public static boolean doCollectionsContainSameElements(
Collection<Integer> c1, Collection<Integer> c2){
if (c1 == null || c2 == null) {
return false;
}
else if (c1.size() != c2.size()) {
return false;
} else {
return c1.containsAll(c2) && c2.containsAll(c1);
}
}
If only the columns are required then DataTable.Clone()
can be used. With Clone
function only the schema will be copied. But DataTable.Copy()
copies both the structure and data
E.g.
DataTable dt = new DataTable();
dt.Columns.Add("Column Name");
dt.Rows.Add("Column Data");
DataTable dt1 = dt.Clone();
DataTable dt2 = dt.Copy();
dt1
will have only the one column but dt2
will have one column with one row.
Reduce() is..
It was ..
let array=[1,2,3];
function sum(acc,val){ return acc+val;} // => can change to (acc,val)=>acc+val
let answer= array.reduce(sum); // answer is 6
Change to
let array=[1,2,3];
let answer=arrays.reduce((acc,val)=>acc+val);
Also you can use in
let array=[5,4,19,2,7];
function findMax(acc,val)
{
if(val>acc){
acc=val;
}
}
let biggest=arrays.reduce(findMax); // 19
arr = [1, 2, 5, 4, 6, 8, 9, 2, 1, 4, 5, 8, 9]
v = 0
for i in range(len(arr)):
v = v ^ arr[i]
print(value) //6
For replace you can use vbCrLf
:
Replace(string, vbCrLf, "")
You can also use chr(13)+chr(10)
.
I seem to remember in some odd cases that chr(10)
comes before chr(13)
.
You can't cast a base object to a derived type - it isn't of that type.
If you have a base type pointer to a derived object, then you can cast that pointer around using dynamic_cast. For instance:
DerivedType D;
BaseType B;
BaseType *B_ptr=&B
BaseType *D_ptr=&D;// get a base pointer to derived type
DerivedType *derived_ptr1=dynamic_cast<DerivedType*>(D_ptr);// works fine
DerivedType *derived_ptr2=dynamic_cast<DerivedType*>(B_ptr);// returns NULL
I could solve this issue with setting environment variables.
export AWS_ACCESS_KEY=
export AWS_SECRET_ACCESS_KEY=
In IntelliJ + py.test, I set environment variables with [Run] > [Edit Configurations] > [Configuration] > [Environment] > [Environment variables]
Since you are using C++11, lambda-expression is a nice&clean solution.
class blub {
void test() {}
public:
std::thread spawn() {
return std::thread( [this] { this->test(); } );
}
};
since this->
can be omitted, it could be shorten to:
std::thread( [this] { test(); } )
or just (deprecated)
std::thread( [=] { test(); } )
There is the instagram public API's tags section that can help you do this.
if you want to do it with pure HTML solution ,you can delete the border in the table if you want...or you can add align="center" attribute to your img tag like this:
<img align="center" width="100%" height="100%" src="http://dummyimage.com/68x68/000/fff" />
see the fiddle : http://jsfiddle.net/Lk2Rh/27/
but still it better to handling this with CSS, i suggest you that.
Queries should look like :
SHOW TABLES
SHOW TABLES FROM mydatabase
SHOW TABLES FROM mydatabase LIKE "tab%"
Things from the MySQL documentation in square brackets [] are optional.
Find: value="([\d]+|[\d])"
Replace: \1
It will really return you
4
403
200
201
116
15
js:
a='value="4"\nvalue="403"\nvalue="200"\nvalue="201"\nvalue="116"\nvalue="15"';
a = a.replace(/value="([\d]+|[\d])"/g, '$1');
console.log(a);
They have totally different meaning and aren't really related at all.
ORDER BY allows you to sort the result set according to different criteria, such as first sort by name from a-z, then sort by the price highest to lowest.
(ORDER BY name, price DESC)
GROUP BY allows you to take your result set, group it into logical groups and then run aggregate queries on those groups. You could for instance select all employees, group them by their workplace location and calculate the average salary of all employees of each workplace location.
The CASE
is just a "switch" to return a value - not to execute a whole code block.
You need to change your code to something like this:
SELECT
@selectoneCount = CASE @Temp
WHEN 1 THEN @selectoneCount + 1
WHEN 2 THEN @selectoneCount + 1
END
If @temp
is set to none of those values (1 or 2), then you'll get back a NULL
Use the modern version of the Fisher–Yates shuffle algorithm:
/**
* Shuffles array in place.
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
var j, x, i;
for (i = a.length - 1; i > 0; i--) {
j = Math.floor(Math.random() * (i + 1));
x = a[i];
a[i] = a[j];
a[j] = x;
}
return a;
}
/**
* Shuffles array in place. ES6 version
* @param {Array} a items An array containing the items.
*/
function shuffle(a) {
for (let i = a.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[a[i], a[j]] = [a[j], a[i]];
}
return a;
}
Note however, that swapping variables with destructuring assignment causes significant performance loss, as of October 2017.
var myArray = ['1','2','3','4','5','6','7','8','9'];
shuffle(myArray);
Using Object.defineProperty
(method taken from this SO answer) we can also implement this function as a prototype method for arrays, without having it show up in loops such as for (i in arr)
. The following will allow you to call arr.shuffle()
to shuffle the array arr
:
Object.defineProperty(Array.prototype, 'shuffle', {
value: function() {
for (let i = this.length - 1; i > 0; i--) {
const j = Math.floor(Math.random() * (i + 1));
[this[i], this[j]] = [this[j], this[i]];
}
return this;
}
});
Note: as of 2019, many of the old vulnerabilities that lead to the preventative measures discussed in this question are no longer an issue in modern browsers. I'll leave the answer below as a historical curiosity, but really the whole topic has changed radically since 2010 (!!) when this was asked.
It prevents it from being used as the target of a simple <script>
tag. (Well, it doesn't prevent it, but it makes it unpleasant.) That way bad guys can't just put that script tag in their own site and rely on an active session to make it possible to fetch your content.
edit — note the comment (and other answers). The issue has to do with subverted built-in facilities, specifically the Object
and Array
constructors. Those can be altered such that otherwise innocuous JSON, when parsed, could trigger attacker code.
php.ini
extension_dir=C:\path\to\server\php\ext
is set and adjust the path (set your PHP extension dir)extension=php_mbstring.dll
is set (uncommented)If this doesn't work and the php_mbstring.dll file is missing, then the PHP installation of this stack is simply broken.
It's an abbreviation of Error NO ENTry (or Error NO ENTity), and can actually be used for more than files/directories.
It's abbreviated because C compilers at the dawn of time didn't support more than 8 characters in symbols.
I spent many sad days trying to come up with a way to do this for C++17, which deprecated code_cvt
facets, and this is the best I was able to come up with by combining code from a few different sources:
setlocale( LC_ALL, "en_US.UTF-8" ); //Invoked in main()
std::string wideToMultiByte( std::wstring const & wideString )
{
std::string ret;
std::string buff( MB_CUR_MAX, '\0' );
for ( wchar_t const & wc : wideString )
{
int mbCharLen = std::wctomb( &buff[ 0 ], wc );
if ( mbCharLen < 1 ) { break; }
for ( int i = 0; i < mbCharLen; ++i )
{
ret += buff[ i ];
}
}
return ret;
}
std::wstring multiByteToWide( std::string const & multiByteString )
{
std::wstring ws( multiByteString.size(), L' ' );
ws.resize(
std::mbstowcs( &ws[ 0 ],
multiByteString.c_str(),
multiByteString.size() ) );
return ws;
}
I tested this code on Windows 10, and at least for my purposes, it seems to work fine. Please don't lynch me if this doesn't consider some crazy edge cases that you might need to handle, I'm sure someone with more experience can improve on this! :-)
Also, credit where it's due:
Functions that might be helpful:
open("file").read()
which reads the contents of the whole file at once'string'.splitlines()
which separates lines from each other (and discards empty lines)By using len() and those functions you could accomplish what you're doing.
If you want to do something recursively, I suggest you use recursion (yes, you can do it using stacks and so on, but hey).
recursiverm() {
for d in *; do
if [ -d "$d" ]; then
(cd -- "$d" && recursiverm)
fi
rm -f *.pdf
rm -f *.doc
done
}
(cd /tmp; recursiverm)
That said, find
is probably a better choice as has already been suggested.
JSONObject class has a method named "has". Returns true if this object has a mapping for name. The mapping may be NULL. http://developer.android.com/reference/org/json/JSONObject.html#has(java.lang.String)
If you're using Python < 3, you'll need to tell the interpreter that your string literal is Unicode by prefixing it with a u
:
Python 2.7.2 (default, Jan 14 2012, 23:14:09)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> "??".encode("utf8")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
UnicodeDecodeError: 'ascii' codec can't decode byte 0xe4 in position 0: ordinal not in range(128)
>>> u"??".encode("utf8")
'\xe4\xbd\xa0\xe5\xa5\xbd'
Further reading: Unicode HOWTO.
If you are using a local array for JSON - as you showed in your example in the question (test.json) then you can is the parseJSON()
method of JQuery ->
var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
getJSON()
is used for getting JSON from a remote site - it will not work locally (unless you are using a local HTTP Server)
You can invoke another one Bash with the different bash_profile. Also, you can create special bash_profile for using in multi-bashprofile environment.
Remember that you can use functions inside of bashprofile, and that functions will be avialable globally. for example, "function user { export USER_NAME $1 }" can set variable in runtime, for example: user olegchir && env | grep olegchir
Here is another method using .loc
to replace inf with nan on a Series:
s.loc[(~np.isfinite(s)) & s.notnull()] = np.nan
So, in response to the original question:
df = pd.DataFrame(np.ones((3, 3)), columns=list('ABC'))
for i in range(3):
df.iat[i, i] = np.inf
df
A B C
0 inf 1.000000 1.000000
1 1.000000 inf 1.000000
2 1.000000 1.000000 inf
df.sum()
A inf
B inf
C inf
dtype: float64
df.apply(lambda s: s[np.isfinite(s)].dropna()).sum()
A 2
B 2
C 2
dtype: float64
Here are the different ways in which you can create an array of booleans in typescript:
let arr1: boolean[] = [];
let arr2: boolean[] = new Array();
let arr3: boolean[] = Array();
let arr4: Array<boolean> = [];
let arr5: Array<boolean> = new Array();
let arr6: Array<boolean> = Array();
let arr7 = [] as boolean[];
let arr8 = new Array() as Array<boolean>;
let arr9 = Array() as boolean[];
let arr10 = <boolean[]> [];
let arr11 = <Array<boolean>> new Array();
let arr12 = <boolean[]> Array();
let arr13 = new Array<boolean>();
let arr14 = Array<boolean>();
You can access them using the index:
console.log(arr[5]);
and you add elements using push:
arr.push(true);
When creating the array you can supply the initial values:
let arr1: boolean[] = [true, false];
let arr2: boolean[] = new Array(true, false);
In my case it was a failed import to eclipse. I had to delete the project from eclipse (without deleting form the filesystem of course) and reimport it. After that the error was gone immediately.
(function(){
var i = 0;
function stop(){
clearTimeout(i);
}
function start(){
i = setTimeout( timed, 1000 );
}
function timed(){
document.getElementById("input").value++;
start();
}
window.stop = stop;
window.start = start;
})()
This question are greatly described here
https://developers.google.com/web/updates/2017/09/autoplay-policy-changes
TL;DR You are still always able to autoplay muted
videos
Also, if you're want to autoplay videos on iOS add playsInline
attribute, because by default iOS tries to fullscreen videos
https://webkit.org/blog/6784/new-video-policies-for-ios/
I put together an animated rotate code program.. you can get your code here ... (if not to late)
With Underscore.js A few ways with Underscore can be done. Here is one of them. Checking if the array is already unique.
function isNameUnique(values){
return _.uniq(values, function(v){ return v.name }).length == values.length
}
With vanilla JavaScript By checking if there is no recurring names in the array.
function isNameUnique(values){
var names = values.map(function(v){ return v.name });
return !names.some(function(v){
return names.filter(function(w){ return w==v }).length>1
});
}
Because Firefox does not support mp3 format. To make this work with Firefox, you should use the ogg format.
You guys don't need those complex things to set locales on Ubuntu/Debian. You don't even need /etc/local.gen
file.
Simply locale-gen
will do everything and the author only missed locales
package.
RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
&& locale-gen "en_US.UTF-8"
ENV LANG=en_US.UTF-8 \
LANGUAGE=en_US:en \
LC_ALL=en_US.UTF-8
I found this the simplest and the most effective. I confirm it works on Ubuntu 16.04.
Downloading and Configuring the Dart SDK
If you don’t already have the Dart SDK, install it. You can get it either by itself or by downloading the Flutter SDK, which (as of Flutter 1.21) includes the full Dart SDK.
Choose one:
Here’s one way to configure Dart support:
Start the IDE, and install the Dart
plugin. To find the Dart plugin
,
from the Welcome screen choose Configure > Plugins
, then click
Install JetBrains plugin
, and then search or scroll down until you
find Dart. Once you've installed the Dart plugin, restart the IDE.
Create a new Dart project:
Create New Projec
t.Dart
.If you don't see a value for the Dart SDK
path, enter it.
<dart installation directory>/dart/dart-sdk
.Use a background worker and read only a limited number of lines. Read more only when the user scrolls.
And try to never use ReadToEnd(). It's one of the functions that you think "why did they make it?"; it's a script kiddies' helper that goes fine with small things, but as you see, it sucks for large files...
Those guys telling you to use StringBuilder need to read the MSDN more often:
Performance Considerations
The Concat and AppendFormat methods both concatenate new data to an existing String or StringBuilder object. A String object concatenation operation always creates a new object from the existing string and the new data. A StringBuilder object maintains a buffer to accommodate the concatenation of new data. New data is appended to the end of the buffer if room is available; otherwise, a new, larger buffer is allocated, data from the original buffer is copied to the new buffer, then the new data is appended to the new buffer.
The performance of a concatenation operation for a String or StringBuilder object depends on how often a memory allocation occurs.
A String concatenation operation always allocates memory, whereas a StringBuilder concatenation operation only allocates memory if the StringBuilder object buffer is too small to accommodate the new data. Consequently, the String class is preferable for a concatenation operation if a fixed number of String objects are concatenated. In that case, the individual concatenation operations might even be combined into a single operation by the compiler. A StringBuilder object is preferable for a concatenation operation if an arbitrary number of strings are concatenated; for example, if a loop concatenates a random number of strings of user input.
That means huge allocation of memory, what becomes large use of swap files system, that simulates sections of your hard disk drive to act like the RAM memory, but a hard disk drive is very slow.
The StringBuilder option looks fine for who use the system as a mono-user, but when you have two or more users reading large files at the same time, you have a problem.
If the two jars that you want to create are the mostly the same, and the only difference is the main class that should be started from each, you can put all of the classes in a third jar. Then create two jars with just a manifest in each. In the MANIFEST.MF file, name the entry class using the Main-Class
attribute.
Additionally, specify the Class-Path
attribute. The value of this should be the name of the jar file that contains all of the shared code. Then deploy all three jar files in the same directory. Of course, if you have third-party libraries, those can be listed in the Class-Path attribute too.
Get the querystring collection, parse it into a (name=value pair
) string, excluding the one you want to REMOVE, and name it newQueryString
Then call Response.Redirect(known_path?newqueryString)
;
Even though this is an old question, I 've stumbled upon this issue multiple times and until now never figured out how to fix it. The update maven indices is a term coined by IntelliJ, and if it still doesn't work after you've compiled the first project, chances are that you are using 2 different maven installations.
Press CTRL+Shift+A to open up the Actions menu. Type Maven
and go to Maven Settings. Check the Home Directory to use the same maven as you use via the command line
_ = { [weak self] value in
guard let self = self else { return }
print(self) // will never be nil
}()
Yeah.ios supports RGB valur to range between 0 and 1 only..its close Range [0,1]
You need to set your @GeneratedId column with strategy GenerationType.IDENTITY instead of GenerationType.AUTO
@Id
@GeneratedValue(strategy = GenerationType.IDENTITY)
@Column(name = "JUD_ID")
private Long _judId;
Change your || to && so it will only exit if the answer is NEITHER "AM" nor "PM".
Usually, syntax and semantics analysis of the code is done in the 'frontend' part of the compiler.
Syntax: Compiler generates tokens for each keyword and symbols: the token contains the information- type of keyword and its location in the code. Using these tokens, an AST(short for Abstract Syntax Tree) is created and analysed. What compiler actually checks here is whether the code is lexically meaningful i.e. does the 'sequence of keywords' comply with the language rules? As suggested in previous answers, you can see it as the grammar of the language(not the sense/meaning of the code). Side note: Syntax errors are reported in this phase.(returns tokens with the error type to the system)
Semantics: Now, the compiler will check whether your code operations 'makes sense'. e.g. If the language supports Type Inference, sematic error will be reported if you're trying to assign a string to a float. OR declaring the same variable twice. These are errors that are 'grammatically'/ syntaxially correct, but makes no sense during the operation. Side note: For checking whether the same variable is declared twice, compiler manages a symbol table
So, the output of these 2 frontend phases is an annotated AST(with data types) and symbol table.
Considering the normal language we use; here, English:
e.g. He go to the school. - Incorrect grammar/syntax, though he wanted to convey a correct sense/semantic.
e.g. He goes to the cold. - cold is an adjective. In English, we might say this doesn't comply with grammar, but it actually is the closest example to incorrect semantic with correct syntax I could think of.
var div = getElementsByTagName('div')[0]; /* first div found; you can use getElementById for more specific element */
div.onclick = null; // OR:
div.onclick = function(){};
//edit
I didn't knew what method are you using for attaching events. For addEventListener
you can use this:
div.removeEventListener('click',functionName,false); // functionName is the name of your callback function
The problem obviously was (as you figured it out) that port 36250 wasn't open on the server side at the time you tried to connect (hence connection refused). I can see the server was supposed to open this socket after receiving SEND
command on another connection, but it apparently was "not opening [it] up in sync with the client side".
Well, the main reason would be there was no synchronisation whatsoever. Calling:
cs.send("SEND " + FILE)
cs.close()
would just place the data into a OS buffer; close
would probably flush the data and push into the network, but it would almost certainly return before the data would reach the server. Adding sleep
after close
might mitigate the problem, but this is not synchronisation.
The correct solution would be to make sure the server has opened the connection. This would require server sending you some message back (for example OK
, or better PORT 36250
to indicate where to connect). This would make sure the server is already listening.
The other thing is you must check the return values of send
to make sure how many bytes was taken from your buffer. Or use sendall
.
(Sorry for disturbing with this late answer, but I found this to be a high traffic question and I really didn't like the sleep idea in the comments section.)
In case you want to pass multiple arguments you can use a tuple
price = 33.3
with open("Output.txt", "w") as text_file:
text_file.write("Purchase Amount: %s price %f" % (TotalAmount, price))
http://blog.parkji.co.uk/2013/08/11/native-drag-and-drop-in-angularjs.html This is simple method for creating native draggable angularJS elements
ul
{
list-style-position:inside;
}
Definition and Usage
The list-style-position property specifies if the list-item markers should appear inside or outside the content flow.
Source: http://www.w3schools.com/cssref/pr_list-style-position.asp
I developed a simple light-weight jQuery plug-in for converting a well formatted HTML table to a scrollable table with fixed table header and columns.
The plugin works well to match pixel-to-pixel positioning the fixed section with the scrollable section. Additionally, you could also freeze the number of columns that will be always in view when scrolling horizontally.
Demo & Documentation: http://meetselva.github.io/fixed-table-rows-cols/
GitHub repository: https://github.com/meetselva/fixed-table-rows-cols
Below is the usage for a simple table with a fixed header,
$(<table selector>).fxdHdrCol({
width: "100%",
height: 200,
colModal: [{width: 30, align: 'center'},
{width: 70, align: 'center'},
{width: 200, align: 'left'},
{width: 100, align: 'center'},
{width: 70, align: 'center'},
{width: 250, align: 'center'}
]
});
Integer x=10;
Double y = x.doubleValue();
lsof -i tcp:8000
This command lists the information about process running in port 8000
kill -9 [PID]
This command kills the process
This is because of a higher JDK during compile time and lower JDK during runtime. So you just need to update your JDK version, possible to JDK 7
You may also check Unsupported major.minor version 51.0
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
var imageView = UIImageView(frame: CGRectMake(100, 150, 150, 150));
var image = UIImage(named: "BattleMapSplashScreen.png");
imageView.image = image;
self.view.addSubview(imageView);
}
Add up to Dmitry's answer, if you don't want to handle unique key IDs manually, you can use React.Children.toArray
as proposed in the React documentation
React.Children.toArray
Returns the children opaque data structure as a flat array with keys assigned to each child. Useful if you want to manipulate collections of children in your render methods, especially if you want to reorder or slice this.props.children before passing it down.
Note:
React.Children.toArray()
changes keys to preserve the semantics of nested arrays when flattening lists of children. That is, toArray prefixes each key in the returned array so that each element’s key is scoped to the input array containing it.
<div>
<ul>
{
React.Children.toArray(
this.state.data.map((item, i) => <li>Test</li>)
)
}
</ul>
</div>
I think Shaz's answer for local variables is hard to understand, though it works for non-recursive functions. Here's another way that I think it's clearer (but it's still his idea, exact same behavior). It's also not accessing the local variables dynamically, just the property of the local variable.
Essentially, it's using a global variable (attached to the function object)
// Here's a version of it that is more straight forward.
function doIt() {
doIt.objname = {};
var someObject = "objname";
doIt[someObject].value = "value";
console.log(doIt.objname);
})();
Which is essentially the same thing as creating a global to store the variable, so you can access it as a property. Creating a global to do this is such a hack.
Here's a cleaner hack that doesn't create global variables, it uses a local variable instead.
function doIt() {
var scope = {
MyProp: "Hello"
};
var name = "MyProp";
console.log(scope[name]);
}
You might need to revise the data in the column, but anyway you can do one of the following:-
1- check if it is numeric then convert it else put another value like 0
Select COLUMNA AS COLUMNA_s, CASE WHEN Isnumeric(COLUMNA) = 1
THEN CONVERT(DECIMAL(18,2),COLUMNA)
ELSE 0 END AS COLUMNA
2- select only numeric values from the column
SELECT COLUMNA AS COLUMNA_s ,CONVERT(DECIMAL(18,2),COLUMNA) AS COLUMNA
where Isnumeric(COLUMNA) = 1
With literal syntax you can check as follows
static const NSString* kKeyToCheck = @"yourKey"
if (xyz[kKeyToCheck])
NSLog(@"Key: %@, has Value: %@", kKeyToCheck, xyz[kKeyToCheck]);
else
NSLog(@"Key pair do not exits for key: %@", kKeyToCheck);
private static int[][] rotate(int[][] matrix, int n) {
int[][] rotated = new int[n][n];
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
rotated[i][j] = matrix[n-j-1][i];
}
}
return rotated;
}
For my case I had to specify a tab index (-1
if only focusable via script)
<div tabindex='-1'>
<!-- ... -->
</div>
pip uninstall pip
will work
This only applies to question 1.
I have an app that runs on Windows and uses a multi-line MFC editor box.
The editor box expects CRLF linebreaks, but I need to parse the text enterred
with some really big/nasty regexs'.
I didn't want to be stressing about this while writing the regex, so
I ended up normalizing back and forth between the parser and editor so that
the regexs' just use \n
. I also trap paste operations and convert them for the boxes.
This does not take much time.
This is what I use.
boost::regex CRLFCRtoLF (
" \\r\\n | \\r(?!\\n) "
, MODx);
boost::regex CRLFCRtoCRLF (
" \\r\\n?+ | \\n "
, MODx);
// Convert (All style) linebreaks to linefeeds
// ---------------------------------------
void ReplaceCRLFCRtoLF( string& strSrc, string& strDest )
{
strDest = boost::regex_replace ( strSrc, CRLFCRtoLF, "\\n" );
}
// Convert linefeeds to linebreaks (Windows)
// ---------------------------------------
void ReplaceCRLFCRtoCRLF( string& strSrc, string& strDest )
{
strDest = boost::regex_replace ( strSrc, CRLFCRtoCRLF, "\\r\\n" );
}
<?php
// Checks if key exists (doesn't care about it's value).
// @link http://php.net/manual/en/function.array-key-exists.php
if (array_key_exists(20120504, $search_array)) {
echo $search_array[20120504];
}
// Checks against NULL
// @link http://php.net/manual/en/function.isset.php
if (isset($search_array[20120504])) {
echo $search_array[20120504];
}
// No warning or error if key doesn't exist plus checks for emptiness.
// @link http://php.net/manual/en/function.empty.php
if (!empty($search_array[20120504])) {
echo $search_array[20120504];
}
?>
For your case solution is :
php artisan cache:clear
php artisan route:cache
Optimizing Route Loading is a must on production :
If you are building a large application with many routes, you should make sure that you are running the route:cache Artisan command during your deployment process:
php artisan route:cache
This command reduces all of your route registrations into a single method call within a cached file, improving the performance of route registration when registering hundreds of routes.
Since this feature uses PHP serialization, you may only cache the routes for applications that exclusively use controller based routes. PHP is not able to serialize Closures.
Laravel 5 clear cache from route, view, config and all cache data from application
I would like to share my experience and solution. when i was working on my laravel e commerce website with gitlab. I was fetching one issue suddenly my view cache with error during development. i did try lot to refresh and something other but i can't see any more change in my view, but at last I did resolve my problem using laravel command so, let's see i added several command for clear cache from view, route, config etc.
Reoptimized class loader:
php artisan optimize
Clear Cache facade value:
php artisan cache:clear
Clear Route cache:
php artisan route:cache
Clear View cache:
php artisan view:clear
Clear Config cache:
php artisan config:cache
Make sure you select the function that needs to be executed. See screenshot:
Here's an efficient option that doesn't use the clipboard.
Sub transposeAndPasteRow(rowToCopy As Range, pasteTarget As Range)
pasteTarget.Resize(rowToCopy.Columns.Count) = Application.WorksheetFunction.Transpose(rowToCopy.Value)
End Sub
Use it like this.
Sub test()
Call transposeAndPasteRow(Worksheets("Sheet1").Range("A1:A5"), Worksheets("Sheet2").Range("A1"))
End Sub