The syntax is wrong in this clause (and similar ones)
CASE lkey WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
It's either
CASE WHEN [condition] THEN [expression] ELSE [expression] END
or
CASE [expression] WHEN [value] THEN [expression] ELSE [expression] END
So in your case it would read:
CASE WHEN lkey > 5 THEN
lkey + 2
ELSE
lkey
END
Check out the documentation (The CASE expression):
If you're trying to get XAMPP to use a network drive as your document root you have to use UNC paths in httpd.conf. XAMPP will not recognize your mapped network drives.
For example the following won't work, DocumentRoot "X:/webroot"
But this will, DocumentRoot "//192.168.10.100/webroot" (note the forward slashes, not back slashes)
To round a double to the nearest integer, just use round()
.
var x = 3.7
x.round() // x = 4.0
If you don't want to modify the original value, then use rounded()
:
let x = 3.7
let y = x.rounded() // y = 4.0. x = 3.7
As one might expect (or might not), a number like 3.5
is rounded up and a number like -3.5
is rounded down. If you need different rounding behavior than that, you can use one of the rounding rules. For example:
var x = 3.7
x.round(.towardZero) // 3.0
If you need an actual Int
then just cast it to one (but only if you are certain that the Double won't be greater than Int.max
):
let myInt = Int(myDouble.rounded())
round
, lround
, floor
, and ceil
. However, now that Swift has this functionality built in, I can no longer recommend using those functions. Thanks to @dfri for pointing this out to me. Check out @dfri's excellent answer here. I also did something similar for rounding a CGFloat
. If you are using C# 3.5 you could write an extension method to System.String that does the splitting you need. You then can then use syntax:
string.SplitByMyTokens();
More info and a useful example from MS here http://msdn.microsoft.com/en-us/library/bb383977.aspx
I would suggest you have a look at BackgroundWorker. If you have a loop that large in your WinForm it will block and your app will look like it has hanged.
Look at BackgroundWorker.ReportProgress()
to see how to report progress back to the UI thread.
For example:
private void Calculate(int i)
{
double pow = Math.Pow(i, i);
}
private void button1_Click(object sender, EventArgs e)
{
progressBar1.Maximum = 100;
progressBar1.Step = 1;
progressBar1.Value = 0;
backgroundWorker.RunWorkerAsync();
}
private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
{
var backgroundWorker = sender as BackgroundWorker;
for (int j = 0; j < 100000; j++)
{
Calculate(j);
backgroundWorker.ReportProgress((j * 100) / 100000);
}
}
private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
progressBar1.Value = e.ProgressPercentage;
}
private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
{
// TODO: do something with final calculation.
}
In information technology it means that:
f(n)=O(g(n)) If there is suitable constant C and N0 independent on N,
such that
for all N>N0 "C*g(n) > f(n) > 0" is true.
Ant it seems that this notation was mostly have taken from mathematics.
In this article there is a quote: D.E. Knuth, "BIG OMICRON AND BIG OMEGA AND BIG THETA", 1976:
On the basis of the issues discussed here, I propose that members of SIGACT, and editors of computer science and mathematics journals, adopt notations as defined above, unless a better alternative can be found reasonably soon.
Today is 2016, but we use it still today.
In mathematical analysis it means that:
lim (f(n)/g(n))=Constant; where n goes to +infinity
But even in mathematical analysis sometimes this symbol was used in meaning "C*g(n) > f(n) > 0".
As I know from university the symbol was intoduced by German mathematician Landau (1877-1938)
One other option would be to use something like this
SELECT *
FROM table t INNER JOIN
(
SELECT 'Text%' Col
UNION SELECT 'Link%'
UNION SELECT 'Hello%'
UNION SELECT '%World%'
) List ON t.COLUMN LIKE List.Col
To add spacing between entries in a legend, adjust the margins of the theme element legend.text
.
To add 30pt of space to the right of each legend label (may be useful for a horizontal legend):
p + theme(legend.text = element_text(
margin = margin(r = 30, unit = "pt")))
To add 30pt of space to the left of each legend label (may be useful for a vertical legend):
p + theme(legend.text = element_text(
margin = margin(l = 30, unit = "pt")))
for a ggplot2
object p
. The keywords are legend.text
and margin
.
[Note about edit: When this answer was first posted, there was a bug. The bug has now been fixed]
Go to File > Preferences > Settings
(or press Ctrl+,) then click the leftmost icon in the top right corner, "Open Settings (JSON)"
In the JSON settings window, add this (within the curly braces {}
):
"terminal.integrated.shell.windows": "C:\\WINDOWS\\System32\\bash.exe"`
(Here you can put any other custom settings you want as well)
Checkout that path to make sure your bash.exe file is there otherwise find out where it is and point to that path instead.
Now if you open a new terminal window in VS Code, it should open with bash instead of PowerShell.
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
Use:
docker attach <container name/id here>
The other way, albeit there is a danger to it, is to use attach
, but if you Ctrl + C to exit the session, you will also stop the container. If you just want to see what is happening, use docker logs -f
.
:~$ docker attach --help
Usage: docker attach [OPTIONS] CONTAINER
Attach to a running container
Options:
--detach-keys string Override the key sequence for detaching a container
--help Print usage
--no-stdin Do not attach STDIN
--sig-proxy Proxy all received signals to the process (default true)
Thanks Friend, i got an answer. This is only possible because of your help. you all give me a ray of hope towards resolving this problem.
Here is the code:
package facebook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.interactions.Actions;
public class Facebook {
public static void main(String args[]){
WebDriver driver = new FirefoxDriver();
driver.get("http://www.facebook.com");
WebElement email= driver.findElement(By.id("email"));
Actions builder = new Actions(driver);
Actions seriesOfActions = builder.moveToElement(email).click().sendKeys(email, "[email protected]");
seriesOfActions.perform();
WebElement pass = driver.findElement(By.id("pass"));
WebElement login =driver.findElement(By.id("u_0_b"));
Actions seriesOfAction = builder.moveToElement(pass).click().sendKeys(pass, "naveench").click(login);
seriesOfAction.perform();
driver.
}
}
long a = 1111;
Long b = new Long(1113);
System.out.println(b.equals(a) ? "equal" : "different");
System.out.println((long) b == a ? "equal" : "different");
There's also split_whitespace()
fn main() {
let words: Vec<&str> = " foo bar\t\nbaz ".split_whitespace().collect();
println!("{:?}", words);
// ["foo", "bar", "baz"]
}
The environment variable to set is MAVEN_OPTS
, for example MAVEN_OPTS=-Xmx1024m
. The maxmem
configuration in the pom only applies when you set the compiler plugin to fork javac
into a new JVM. Otherwise the plugin runs inside the same VM as Maven and thus within the memory passed on the command line via the MAVEN_OPTS
.
To set MAVEN_OPTS under Windows 7:
-Xmx1024m
(or more)Open a new command window and run mvn
.
if using /bin/sh
you can use:
if [ <condition> ] && [ <condition> ]; then
...
fi
if using /bin/bash
you can use:
if [[ <condition> && <condition> ]]; then
...
fi
If you are using pwsh (powershell core), you can try
(docker ps --format='{{json .}}' | ConvertFrom-Json).Mounts
also you can see both container name and Mounts as below
docker ps --format='{{json .}}' | ConvertFrom-Json | select Names,Mounts
As the output is converted as json ,you can get any properties it has.
use getContext() instead of MainActivity.this
Intent intent = new Intent(getContext(), SecondActivity.class);
startActivity(start);
If you need a floating random number between 13 and 20
(20-13).*rand(1) + 13
If you need an integer random number between 13 and 20
floor((21-13).*rand(1) + 13)
Note: Fix problem mentioned in comment "This excludes 20" by replacing 20 with 21
Escape sequences (and variables too) work inside double quoted and heredoc strings. So change your code to:
echo '<p>' . $unit1 . "</p>\n";
PS: One clarification, single quotes strings do accept two escape sequences:
\'
when you want to use single quote inside single quoted strings\\
when you want to use backslash literallyUIButton
inherits from UIControl
. That has all of the methods to add/remove actions: UIControl Class Reference. Look at the section "Preparing and Sending Action Messages", which covers – sendAction:to:forEvent:
and – addTarget:action:forControlEvents:
.
JavaScript's OOP is a little funky (or a lot) and it takes some getting used to. This first thing you need to keep in mind is that there are no Classes and thinking in terms of classes can trip you up. And in order to use a method attached to a Constructor (the JavaScript equivalent of a Class definition) you need to instantiate your object. For example:
Ninja = function (name) {
this.name = name;
};
aNinja = new Ninja('foxy');
aNinja.name; //-> 'foxy'
enemyNinja = new Ninja('boggis');
enemyNinja.name; //=> 'boggis'
Note that Ninja
instances have the same properties but aNinja
cannot access the properties of enemyNinja
. (This part should be really easy/straightforward) Things get a bit different when you start adding stuff to the prototype
:
Ninja.prototype.jump = function () {
return this.name + ' jumped!';
};
Ninja.prototype.jump(); //-> Error.
aNinja.jump(); //-> 'foxy jumped!'
enemyNinja.jump(); //-> 'boggis jumped!'
Calling this directly will throw an error because this
only points to the correct object (your "Class") when the Constructor is instantiated (otherwise it points to the global object, window
in a browser)
I suggest:
var minutes = data.getMinutes();
minutes = minutes > 9 ? minutes : '0' + minutes;
it is one function call fewer. It is always good to think about performance. It is short as well;
Check that all your bundle resources are copied in build phase.
or you can set pointer-events:none
to your a
element and pointer-event:all
to your a:before
element, and then add hover CSS to a element
a{
pointer-events:none;
}
a:before{
pointer-events:all
}
a:hover:before{
background:blue;
}
The simplest way to update is as follows:
Go to the start screen for Android Studio. If it automatically opens a project when you open it, close that project (not exit).
At the bottom there will be a check for updates link which you can use to update to the latest version.
This is one sample dao test using junit in spring project.
import java.util.List;
import junit.framework.Assert;
import org.jboss.tools.example.springmvc.domain.Member;
import org.jboss.tools.example.springmvc.repo.MemberDao;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import org.springframework.transaction.annotation.Transactional;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations={"classpath:test-context.xml",
"classpath:/META-INF/spring/applicationContext.xml"})
@Transactional
@TransactionConfiguration(defaultRollback=true)
public class MemberDaoTest
{
@Autowired
private MemberDao memberDao;
@Test
public void testFindById()
{
Member member = memberDao.findById(0l);
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("[email protected]", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
@Test
public void testFindByEmail()
{
Member member = memberDao.findByEmail("[email protected]");
Assert.assertEquals("John Smith", member.getName());
Assert.assertEquals("[email protected]", member.getEmail());
Assert.assertEquals("2125551212", member.getPhoneNumber());
return;
}
@Test
public void testRegister()
{
Member member = new Member();
member.setEmail("[email protected]");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
Long id = member.getId();
Assert.assertNotNull(id);
Assert.assertEquals(2, memberDao.findAllOrderedByName().size());
Member newMember = memberDao.findById(id);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("[email protected]", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
@Test
public void testFindAllOrderedByName()
{
Member member = new Member();
member.setEmail("[email protected]");
member.setName("Jane Doe");
member.setPhoneNumber("2125552121");
memberDao.register(member);
List<Member> members = memberDao.findAllOrderedByName();
Assert.assertEquals(2, members.size());
Member newMember = members.get(0);
Assert.assertEquals("Jane Doe", newMember.getName());
Assert.assertEquals("[email protected]", newMember.getEmail());
Assert.assertEquals("2125552121", newMember.getPhoneNumber());
return;
}
}
GO isn't a keyword in SQL Server; it's a batch separator. GO ends a batch of statements. This is especially useful when you are using something like SQLCMD. Imagine you are entering in SQL statements on the command line. You don't necessarily want the thing to execute every time you end a statement, so SQL Server does nothing until you enter "GO".
Likewise, before your batch starts, you often need to have some objects visible. For example, let's say you are creating a database and then querying it. You can't write:
CREATE DATABASE foo;
USE foo;
CREATE TABLE bar;
because foo does not exist for the batch which does the CREATE TABLE. You'd need to do this:
CREATE DATABASE foo;
GO
USE foo;
CREATE TABLE bar;
Not at all. Lambda expressions are the one and only point of that annotation.
If you also want to make this deletion operation chainable, so you can delete some item and keep on chaining operations on the resulting array, use tap
:
[2, 4, 6, 3, 8].tap { |ary| ary.delete(3) }.count #=> 4
Since strptime
returns a datetime object which has tzinfo
attribute, We can simply replace it with desired timezone.
>>> import datetime
>>> date_time_str = '2018-06-29 08:15:27.243860'
>>> date_time_obj = datetime.datetime.strptime(date_time_str, '%Y-%m-%d %H:%M:%S.%f').replace(tzinfo=datetime.timezone.utc)
>>> date_time_obj.tzname()
'UTC'
Here is a walkthrough, Using PostgreSQL in your C# (.NET) application (An introduction):
In this article, I would like to show you the basics of using a PostgreSQL database in your .NET application. The reason why I'm doing this is the lack of PostgreSQL articles on CodeProject despite the fact that it is a very good RDBMS. I have used PostgreSQL back in the days when PHP was my main programming language, and I thought.... well, why not use it in my C# application.
Other than that you will need to give us some specific problems that you are having so that we can help diagnose the problem.
A simple way to use modals is with eModal!
Ex from github:
<script src="//rawgit.com/saribe/eModal/master/dist/eModal.min.js"></script>
use eModal to display a modal for alert, ajax, prompt or confirm
// Display an alert modal with default title (Attention)
eModal.alert('You shall not pass!');
We passed Json object by HttpPost method, and parse it in dynamic object. it works fine. this is sample code:
webapi:
[HttpPost]
public string DoJson2(dynamic data)
{
//whole:
var c = JsonConvert.DeserializeObject<YourObjectTypeHere>(data.ToString());
//or
var c1 = JsonConvert.DeserializeObject< ComplexObject1 >(data.c1.ToString());
var c2 = JsonConvert.DeserializeObject< ComplexObject2 >(data.c2.ToString());
string appName = data.AppName;
int appInstanceID = data.AppInstanceID;
string processGUID = data.ProcessGUID;
int userID = data.UserID;
string userName = data.UserName;
var performer = JsonConvert.DeserializeObject< NextActivityPerformers >(data.NextActivityPerformers.ToString());
...
}
The complex object type could be object, array and dictionary.
ajaxPost:
...
Content-Type: application/json,
data: {"AppName":"SamplePrice",
"AppInstanceID":"100",
"ProcessGUID":"072af8c3-482a-4b1c??-890b-685ce2fcc75d",
"UserID":"20",
"UserName":"Jack",
"NextActivityPerformers":{
"39??c71004-d822-4c15-9ff2-94ca1068d745":[{
"UserID":10,
"UserName":"Smith"
}]
}}
...
In a case
statement, a ,
is the equivalent of ||
in an if
statement.
case car
when 'toyota', 'lexus'
# code
end
If you want to make them a lot bigger, like for multiple lines of input, you may want to use a textarea tag instead of the input tag. This allows you to put in number of rows and columns you want on your textarea without messing with css (e.g. <textarea rows="2" cols="25"></textarea>
).
Text areas are resizable by default. If you want to disable that, just use the resize css rule:
#signin textarea {
resize: none;
}
A simple solution to your question about default text that disappears when the user clicks is to use the placeholder attribute. This will work for <input>
tags as well.
<textarea rows="2" cols="25" placeholder="This is the default text"></textarea>
This text will disappear when the user enters information rather than when they click, but that is common functionality for this kind of thing.
Since I could not run the C
executable that way, I wrote a simple shell script
that does the following
cd /..path_to_shell_script
./c_executable_name
In the cron jobs list, I call the shell script.
I found several posts telling me to run several gpg commands, but they didn't solve the problem because of two things. First, I was missing the debian-keyring package on my system and second I was using an invalid keyserver. Try different keyservers if you're getting timeouts!
Thus, the way I fixed it was:
apt-get install debian-keyring
gpg --keyserver pgp.mit.edu --recv-keys 1F41B907
gpg --armor --export 1F41B907 | apt-key add -
Then running a new "apt-get update" worked flawlessly!
Another solution I ran across tonight, which worked for my needs, was to add box-sizing
attributes:
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
These attributes force the border to be part of the box model's width and height and correct the issue as well.
According to caniuse.com » box-sizing, box-sizing
is supported in IE8+.
If you're using LESS or Sass there is a Bootstrap mixin for this.
LESS:
.box-sizing(border-box);
Sass:
@include box-sizing(border-box);
I guess this has been already answered. However, I think that you can still mix both options in a syntactically better way by doing:
switch (value)
{
case 1: case 2: case 3:
// Do Something
break;
case 4: case 5: case 6:
// Do Something
break;
default:
// Do Something
break;
}
Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx
Retrofit 2.3.0
// Load CAs from an InputStream
CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
InputStream inputStream = context.getResources().openRawResource(R.raw.ssl_certificate); //(.crt)
Certificate certificate = certificateFactory.generateCertificate(inputStream);
inputStream.close();
// Create a KeyStore containing our trusted CAs
String keyStoreType = KeyStore.getDefaultType();
KeyStore keyStore = KeyStore.getInstance(keyStoreType);
keyStore.load(null, null);
keyStore.setCertificateEntry("ca", certificate);
// Create a TrustManager that trusts the CAs in our KeyStore.
String tmfAlgorithm = TrustManagerFactory.getDefaultAlgorithm();
TrustManagerFactory trustManagerFactory = TrustManagerFactory.getInstance(tmfAlgorithm);
trustManagerFactory.init(keyStore);
TrustManager[] trustManagers = trustManagerFactory.getTrustManagers();
X509TrustManager x509TrustManager = (X509TrustManager) trustManagers[0];
// Create an SSLSocketFactory that uses our TrustManager
SSLContext sslContext = SSLContext.getInstance("SSL");
sslContext.init(null, new TrustManager[]{x509TrustManager}, null);
sslSocketFactory = sslContext.getSocketFactory();
//create Okhttp client
OkHttpClient client = new OkHttpClient.Builder()
.sslSocketFactory(sslSocketFactory,x509TrustManager)
.build();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(url)
.addConverterFactory(GsonConverterFactory.create())
.client(client)
.build();
For Sharepoint 2007
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS
I don't think so. The API's will provide access to delayed quotes, there is no way that real time data or tick data, will be provided for free.
check this quick reminder of file path
Here is all you need to know about relative file paths:
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
I wrapped Rob's answer up into a slightly more general function, which can be used to find the 2nd, 3rd, 4th (etc.) max:
maxN <- function(x, N=2){
len <- length(x)
if(N>len){
warning('N greater than length(x). Setting N=length(x)')
N <- length(x)
}
sort(x,partial=len-N+1)[len-N+1]
}
maxN(1:10)
this file starts to appear when you choose the system shows you the hidden files: $defaults write com.apple.finder AppleShowAllFiles TRUE If you run this command disapear $defaults write com.apple.finder AppleShowAllFiles FALSE Use terminal
If you want to select multiple cells and copy their values to the clipboard without all those annoying quotes the following code may be useful. This is an enhancement of the code given above from user3616725.
Sub CopyCells()
'Attach Microsoft Forms 2.0 Library: tools\references\Browse\FM20.DLL
'Then set a keyboard shortcut to the CopyCells Macro (eg Crtl T)
Dim objData As New DataObject
Dim cell As Object
Dim concat As String
Dim cellValue As String
CR = ""
For Each cell In Selection
If IsNumeric(cell.Value) Then
cellValue = LTrim(Str(cell.Value))
Else
cellValue = cell.Value
End If
concat = concat + CR + cellValue
CR = Chr(13)
Next
objData.SetText (concat)
objData.PutInClipboard
End Sub
Well if you have N objects and you need to get the Title of all of them you have to use a loop. If you only need the title and you really want to improve this, maybe you can make a separated array containing only the title, this would improve the performance. You need to define the amount of memory available and the amount of objects that you can handle before saying this can damage the performance, and in any case the solution would be changing the design of the program not the algorithm.
No forks, no pipes. Pure POSIX shell:
case $var in
(*[!0-9]*|'') echo not a number;;
(*) echo a number;;
esac
(Assumes number := a string of digits). If you want to allow signed numbers with a single leading -
or +
as well, strip the optional sign like this:
case ${var#[-+]} in
(*[!0-9]*|'') echo not a number;;
(*) echo a number;;
esac
There should be svn
utility on you box, if installed:
$ svn checkout http://example.com/svn/somerepo somerepo
This will check out a working copy from a specified repository to a directory somerepo
on our file system.
You may want to print commands, supported by this utility:
$ svn help
uname -a
output in your question is identical to one, used by Parallels Virtuozzo Containers for Linux 4.0 kernel, which is based on Red Hat 5 kernel, thus your friends are rpm
or the following command:
$ sudo yum install subversion
You could read the entire input line from scanner, then split the line by ,
then you have a String[]
, parse each number into int[]
with index one to one matching...(assuming valid input and no NumberFormatExceptions
) like
String line = scanner.nextLine();
String[] numberStrs = line.split(",");
int[] numbers = new int[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
// Note that this is assuming valid input
// If you want to check then add a try/catch
// and another index for the numbers if to continue adding the others (see below)
numbers[i] = Integer.parseInt(numberStrs[i]);
}
As YoYo's answer suggests, the above can be achieved more concisely in Java 8:
int[] numbers = Arrays.stream(line.split(",")).mapToInt(Integer::parseInt).toArray();
To handle invalid input
You will need to consider what you want need to do in this case, do you want to know that there was bad input at that element or just skip it.
If you don't need to know about invalid input but just want to continue parsing the array you could do the following:
int index = 0;
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[index] = Integer.parseInt(numberStrs[i]);
index++;
}
catch (NumberFormatException nfe)
{
//Do nothing or you could print error if you want
}
}
// Now there will be a number of 'invalid' elements
// at the end which will need to be trimmed
numbers = Arrays.copyOf(numbers, index);
The reason we should trim the resulting array is that the invalid elements at the end of the int[]
will be represented by a 0
, these need to be removed in order to differentiate between a valid input value of 0
.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,10]
If you need to know about invalid input later you could do the following:
Integer[] numbers = new Integer[numberStrs.length];
for(int i = 0;i < numberStrs.length;i++)
{
try
{
numbers[i] = Integer.parseInt(numberStrs[i]);
}
catch (NumberFormatException nfe)
{
numbers[i] = null;
}
}
In this case bad input (not a valid integer) the element will be null.
Results in
Input: "2,5,6,bad,10"
Output: [2,3,6,null,10]
You could potentially improve performance by not catching the exception (see this question for more on this) and use a different method to check for valid integers.
You are mixing razor and aspx syntax,if your view engine is razor just do this:
<button class="btn btn-info" type="button" id="addressSearch"
onclick="location.href='@Url.Action("List", "Search")'">
select * from xyz where (1=(CASE WHEN @AnnualFeeType = 'All' THEN 1 ELSE 0 END) OR AnnualFeeType = @AnnualFeeType)
For JDBC based project (directly or indirectly, e.g. JPA, EJB, ...) you can mockup not the entire database (in such case it would be better to use a test db on a real RDBMS), but only mockup at JDBC level.
Advantage is abstraction which comes with that way, as JDBC data (result set, update count, warning, ...) are the same whatever is the backend: your prod db, a test db, or just some mockup data provided for each test case.
With JDBC connection mocked up for each case there is no need to manage test db (cleanup, only one test at time, reload fixtures, ...). Every mockup connection is isolated and there is no need to clean up. Only minimal required fixtures are provided in each test case to mock up JDBC exchange, which help to avoid complexity of managing a whole test db.
Acolyte is my framework which includes a JDBC driver and utility for this kind of mockup: http://acolyte.eu.org .
Using Kotlin
val data = "{\"ApiInfo\":{\"description\":\"userDetails\",\"status\":\"success\"},\"userDetails\":{\"Name\":\"somename\",\"userName\":\"value\"},\"pendingPushDetails\":[]}\n"
try {
val jsonObject = JSONObject(data)
val infoObj = jsonObject.getJSONObject("ApiInfo")
} catch (e: Exception) {
}
To properly add IOException (to RuntimeException) handling code, your method will look like this:
Stream<Account> s = accounts.values().stream();
s = s.filter(a -> { try { return a.isActive(); }
catch (IOException e) { throw new RuntimeException(e); }});
Stream<String> ss = s.map(a -> { try { return a.getNumber() }
catch (IOException e) { throw new RuntimeException(e); }});
return ss.collect(Collectors.toSet());
The problem now is that the IOException
will have to be captured as a RuntimeException
and converted back to an IOException
-- and that will add even more code to the above method.
Why use Stream
when it can be done just like this -- and the method throws IOException
so no extra code is needed for that too:
Set<String> set = new HashSet<>();
for(Account a: accounts.values()){
if(a.isActive()){
set.add(a.getNumber());
}
}
return set;
from the FAQ
elem = $("#elemid");
if (elem.is (".class")) {
// whatever
}
or:
elem = $("#elemid");
if (elem.hasClass ("class")) {
// whatever
}
If you git and GitHub user:
generate-package
more simply, than npm init
.
else
and/or you don't like package.json
template, that generate-package or npm init
generate:
you can generate your own template via scaffolding apps as generate, sails or yeoman.
This answer is relevant for March 2018. In the future, the data from this answer may be obsolete.
Author of this answer personally used generate-package at March 2018.
You need use git and GitHub for using generate-package.
For example, I create blank folder sasha-npm-init-vs-generate-package
.
Command:
D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>gen package
[16:58:52] starting generate
[16:59:01] v running tasks: [ 'package' ]
[16:59:04] starting package
? Project description? generate-package demo
? Author's name? Sasha Chernykh
? Author's URL? https://vk.com/hair_in_the_wind
[17:00:19] finished package v 1m
package.json
:
{
"name": "sasha-npm-init-vs-generate-package",
"description": "generate-package demo",
"version": "0.1.0",
"homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package",
"author": "Sasha Chernykh (https://vk.com/hair_in_the_wind)",
"repository": "Kristinita/sasha-npm-init-vs-generate-package",
"bugs": {
"url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
},
"license": "MIT",
"engines": {
"node": ">=4"
},
"scripts": {
"test": "mocha"
},
"keywords": [
"generate",
"init",
"npm",
"package",
"sasha",
"vs"
]
}
D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package>npm init
This utility will walk you through creating a package.json file.
It only covers the most common items, and tries to guess sensible defaults.
See `npm help json` for definitive documentation on these fields
and exactly what they do.
Use `npm install <pkg>` afterwards to install a package and
save it as a dependency in the package.json file.
Press ^C at any time to quit.
package name: (sasha-npm-init-vs-generate-package)
version: (1.0.0) 0.1.0
description: npm init demo
entry point: (index.js)
test command: mocha
git repository: https://github.com/Kristinita/sasha-npm-init-vs-generate-package
keywords: generate, package, npm, package, sasha, vs
author: Sasha Chernykh
license: (ISC) MIT
About to write to D:\SashaDemoRepositories\sasha-npm-init-vs-generate-package\package.json:
{
"name": "sasha-npm-init-vs-generate-package",
"version": "0.1.0",
"description": "npm init demo",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
},
"keywords": [
"generate",
"package",
"npm",
"package",
"sasha",
"vs"
],
"author": "Sasha Chernykh",
"license": "MIT",
"bugs": {
"url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
},
"homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}
Is this ok? (yes) y
{
"name": "sasha-npm-init-vs-generate-package",
"version": "0.1.0",
"description": "npm init demo",
"main": "index.js",
"scripts": {
"test": "mocha"
},
"repository": {
"type": "git",
"url": "git+https://github.com/Kristinita/sasha-npm-init-vs-generate-package.git"
},
"keywords": [
"generate",
"package",
"npm",
"package",
"sasha",
"vs"
],
"author": "Sasha Chernykh",
"license": "MIT",
"bugs": {
"url": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package/issues"
},
"homepage": "https://github.com/Kristinita/sasha-npm-init-vs-generate-package#readme"
}
I think, that generate-package
more simply, that npm init
.
That create your own package.json
template, see generate and yeoman examples.
<% @images.each_with_index do |page, index| %>
<% end %>
Other Significant practical differences:
// Boolean
var str3 = true ;
alert(str3);
alert(str3 instanceof Boolean); // false: expect true
alert(typeof str3 == "boolean" ); // true
// Number
var str4 = 100 ;
alert(str4);
alert(str4 instanceof Number); // false: expect true
alert(typeof str4 == "number" ); // true
You can write queries like this in SQL Server:
--each [0-9] matches a single digit, this would match 5xx
SELECT * FROM YourTable WHERE SomeField LIKE '5[0-9][0-9]'
Use the DEFAULT keyword:
$query = "INSERT INTO myTable VALUES (DEFAULT,'Fname', 'Lname', 'Website')";
Also, you can specify the columns, (which is better practice):
$query = "INSERT INTO myTable
(fname, lname, website)
VALUES
('fname', 'lname', 'website')";
Reference:
First, we need GOPATH
The $GOPATH
is a folder (or set of folders) specified by its environment variable. We must notice that this is not the $GOROOT
directory where Go is installed.
export GOPATH=$HOME/gocode
export PATH=$PATH:$GOPATH/bin
We used ~/gocode
path in our computer to store the source of our application and its dependencies. The GOPATH
directory will also store the binaries of their packages.
Then check Go env
You system must have $GOPATH
and $GOROOT
, below is my Env:
GOARCH="amd64"
GOBIN=""
GOCHAR="6"
GOEXE=""
GOHOSTARCH="amd64"
GOHOSTOS="linux"
GOOS="linux"
GOPATH="/home/elpsstu/gocode"
GORACE=""
GOROOT="/home/pravin/go"
GOTOOLDIR="/home/pravin/go/pkg/tool/linux_amd64"
CC="gcc"
GOGCCFLAGS="-fPIC -m64 -pthread -fmessage-length=0"
CXX="g++"
CGO_ENABLED="1"
Now, you run download go package:
go get [-d] [-f] [-fix] [-t] [-u] [build flags] [packages]
Get downloads and installs the packages named by the import paths, along with their dependencies. For more details you can look here.
There are two methods to consider which achieve the same effect for handling null pointers to C-style strings.
The ternary operator
void setvalue(const char *value)
{
std::string mValue = value ? value : "";
}
or the humble if statement
void setvalue(const char *value)
{
std::string mValue;
if(value) mValue = value;
}
In both cases, value
is only assigned to mValue
when value
is not a null pointer. In all other cases (i.e. when value
is null), mValue
will contain an empty string.
The ternary operator method may be useful for providing an alternative default string literal in the absence of a value from value
:
std::string mValue = value ? value : "(NULL)";
application/font-woff for woff: http://www.iana.org/assignments/media-types/application/font-woff
we have to install the M2E Eclipse WTP plugin To install: Preferences->Maven->Discovery->Open Catalog and choose the WTP plugin.
And restart eclipse
If Image folder location is public/assets/img/default.jpg.
You can try in view
<img src="{{ URL::to('/assets/img/default.jpg') }}">
From your Obc-C code I think you want to set an Image for button so try this way:
let playButton = UIButton(type: .Custom)
if let image = UIImage(named: "play.png") {
playButton.setImage(image, forState: .Normal)
}
In Short:
playButton.setImage(UIImage(named: "play.png"), forState: UIControlState.Normal)
For Swift 3:
let playButton = UIButton(type: .custom)
playButton.setImage(UIImage(named: "play.png"), for: .normal)
Adding to @Luca Davanzo
iOS 11, some permissions settings have moved to the app path:
iOS 11 Support
static func open(_ preferenceType: PreferenceType) throws {
var preferencePath: String
if #available(iOS 11.0, *), preferenceType == .video || preferenceType == .locationServices || preferenceType == .photos {
preferencePath = UIApplicationOpenSettingsURLString
} else {
preferencePath = "\(PreferencesExplorer.preferencePath)=\(preferenceType.rawValue)"
}
if let url = URL(string: preferencePath) {
if #available(iOS 10.0, *) {
UIApplication.shared.open(url, options: [:], completionHandler: nil)
} else {
UIApplication.shared.openURL(url)
}
} else {
throw PreferenceExplorerError.notFound(preferencePath)
}
}
Take a look at my answer Maven and dependent modules.
The Maven Reactor plugin is designed to deal with building part of a project.
The particular goal you'll want to use it reactor:make
.
Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:
Some code that would serve you specifically as well:
var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;
for (var i = 0, n = pix.length; i < n; i += 4) {
console.log pix[i+3]
}
This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.
Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:
$('el').click(function(e){
console.log(e.clientX, e.clientY)
}
Those should grab your x and y values.
In order to use nslookup
, host
or gethostbyname()
then the target's name will need to be registered with DNS or statically defined in the hosts file on the machine running your program. Yes, you could connect to the target with SSH or some other application and query it directly, but for a generic solution you'll need some sort of DNS entry for it.
PHP has a built in function called bool chmod(string $filename, int $mode )
private function writeFileContent($file, $content){
$fp = fopen($file, 'w');
fwrite($fp, $content);
fclose($fp);
chmod($file, 0777); //changed to add the zero
return true;
}
You might often find
cond and on_true or on_false
but this lead to problem when on_true == 0
>>> x = 0
>>> print x == 0 and 0 or 1
1
>>> x = 1
>>> print x == 0 and 0 or 1
1
where you would expect for a normal ternary operator this result
>>> x = 0
>>> print 0 if x == 0 else 1
0
>>> x = 1
>>> print 0 if x == 0 else 1
1
When running Wget with -r
or -p
, but without -N
, -nd
, or -nc
, re-downloading a file will result in the new copy simply overwriting the old.
So adding -nc
will prevent this behavior, instead causing the original version to be preserved and any newer copies on the server to be ignored.
C# 6 adds a new feature just for this: extension Add methods. This has always been possible for VB.net but is now available in C#.
Now you don't have to add Add()
methods to your classes directly, you can implement them as extension methods. When extending any enumerable type with an Add()
method, you'll be able to use it in collection initializer expressions. So you don't have to derive from lists explicitly anymore (as mentioned in another answer), you can simply extend it.
public static class TupleListExtensions
{
public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
T1 item1, T2 item2)
{
list.Add(Tuple.Create(item1, item2));
}
public static void Add<T1, T2, T3>(this IList<Tuple<T1, T2, T3>> list,
T1 item1, T2 item2, T3 item3)
{
list.Add(Tuple.Create(item1, item2, item3));
}
// and so on...
}
This will allow you to do this on any class that implements IList<>
:
var numbers = new List<Tuple<int, string>>
{
{ 1, "one" },
{ 2, "two" },
{ 3, "three" },
{ 4, "four" },
{ 5, "five" },
};
var points = new ObservableCollection<Tuple<double, double, double>>
{
{ 0, 0, 0 },
{ 1, 2, 3 },
{ -4, -2, 42 },
};
Of course you're not restricted to extending collections of tuples, it can be for collections of any specific type you want the special syntax for.
public static class BigIntegerListExtensions
{
public static void Add(this IList<BigInteger> list,
params byte[] value)
{
list.Add(new BigInteger(value));
}
public static void Add(this IList<BigInteger> list,
string value)
{
list.Add(BigInteger.Parse(value));
}
}
var bigNumbers = new List<BigInteger>
{
new BigInteger(1), // constructor BigInteger(int)
2222222222L, // implicit operator BigInteger(long)
3333333333UL, // implicit operator BigInteger(ulong)
{ 4, 4, 4, 4, 4, 4, 4, 4 }, // extension Add(byte[])
"55555555555555555555555555555555555555", // extension Add(string)
};
C# 7 will be adding in support for tuples built into the language, though they will be of a different type (System.ValueTuple
instead). So to it would be good to add overloads for value tuples so you have the option to use them as well. Unfortunately, there are no implicit conversions defined between the two.
public static class ValueTupleListExtensions
{
public static void Add<T1, T2>(this IList<Tuple<T1, T2>> list,
ValueTuple<T1, T2> item) => list.Add(item.ToTuple());
}
This way the list initialization will look even nicer.
var points = new List<Tuple<int, int, int>>
{
(0, 0, 0),
(1, 2, 3),
(-1, 12, -73),
};
But instead of going through all this trouble, it might just be better to switch to using ValueTuple
exclusively.
var points = new List<(int, int, int)>
{
(0, 0, 0),
(1, 2, 3),
(-1, 12, -73),
};
Since the other answers cover what's wrong with it, I'll try the other half, how to fix it. Unfortunately, I don't know that you have a CSS only solution here, at least not that I can think of. There are some other options though....
Assign a first
class to the element when you generate it, like this:
<p class="red first"></p>
<div class="red"></div>
CSS:
.first.red {
border:5px solid red;
}
This CSS only matches elements with both first
and red
classes.
Alternatively, do the same in JavaScript, for example here's what jQuery you would use to do this, using the same CSS as above:
$(".red:first").addClass("first");
make sure your pc and android is on same wifi connection.
start adb server from your phone... download any wireless adb app from playstore...here is what I am using WiFi ADB - Debug Over Air
on your computer start cmd and run: Code (csharp): adb connect 192.168.1.100:5555 Be sure to replace 192.168.1.100 with the IP address that is actually assigned to your device.
check if it is connected by : Code (csharp): adb devices 4. start unity or restart if it is already running and hit play..
Either make your friends download the runtime DLL (@Kay's answer), or compile the app with static linking.
In visual studio, go to Project tab -> properties - > configuration properties -> C/C++ -> Code Generation
on runtime library choose /MTd
for debug mode and /MT
for release mode.
This will cause the compiler to embed the runtime into the app. The executable will be significantly bigger, but it will run without any need of runtime dlls.
Those files are created and used by Android Studio editor.
You don't need to check in those files to version control.
Git uses .gitignore file, that contains list of files and directories, to know the list of files and directories that don't need to be checked in.
Android studio automatically creates .gitingnore files listing all files and directories which don't need to be checked in to any version control.
Angular only points to src/assets
folder, nothing else is public to access via url so you should use full path
this.fullImagePath = '/assets/images/therealdealportfoliohero.jpg'
Or
this.fullImagePath = 'assets/images/therealdealportfoliohero.jpg'
This will only work if the base href tag is set with /
You can also add other folders for data in angular/cli
.
All you need to modify is angular-cli.json
"assets": [
"assets",
"img",
"favicon.ico",
".htaccess"
]
Note in edit : Dist command will try to find all attachments from assets so it is also important to keep the images and any files you want to access via url inside assets, like mock json data files should also be in assets.
There's a faster way, just use
YourActivity.setTitle("New Title");
You can also find it inside the onCreate() with this, for example:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
this.setTitle("My Title");
}
By the way, what you simply cannot do is call setTitle() in a static way without passing any Activity object.
You're changing what a
refers to. Try this:
String a="a";
System.out.println("a 1-->"+a);
String b=a;
a="ty";
System.out.println("a 2-->"+a);
System.out.println("b -->"+b);
You will see that the object to which a
and then b
refers has not changed.
If you want to prevent your code from changing which object a
refers to, try:
final String a="a";
You must be providing the wrong path to the debug.keystore
file.
Follow these steps to get the correct path and complete your command:
And finally, use the path you just copied from Step 3 to construct your command:
For example, in my case, it would be:
C:\Program Files\Java\jre7\bin>keytool -list -v -keystore "C:\Users\Siddharth Lele.android\debug.keystore" -alias androiddebugkey -storepass android -keypass android
UPDATED:
If you had already followed the steps mentioned above, the only other solution is to delete the debug.keystore
and let Eclipse recreate it for you.
Step 1: Go to the path where your keystore is stored. In your case, C:\Users\Suresh\.android\debug.keystore
Step 2: Close and restart Eclipse.
Step 3 (Optional): You may need to clean your project before the debug.keystore
is created again.
Source: http://www.coderanch.com/t/440920/Security/KeyTool-genkeypair-exception-Keystore-file
You can refer to this for the part about deleting your debug.keystore
file: "Debug certificate expired" error in Eclipse Android plugins
If you make your parent element be "position: relative", then it will be the "offset parent" for the stuff you're tracking mouse events over. Thus the jQuery "position()" will be relative to that.
The thread you linked to does answer the question for you. You need to target the a
elements themselves. E.g.
.nav.navbar-nav.navbar-right a {
color: blue;
}
If that doesn't work, it just needs to be more specific. E.g.
.nav.navbar-nav.navbar-right li a {
color: blue;
}
The standard way, which has already been proposed several times is:
for (var name in myObject) {
alert(name);
}
However Internet Explorer 6, 7 and 8 have a bug in the JavaScript interpreter, which has the effect that some keys are not enumerated. If you run this code:
var obj = { toString: 12};
for (var name in obj) {
alert(name);
}
If will alert "12" in all browsers except IE. IE will simply ignore this key. The affected key values are:
isPrototypeOf
hasOwnProperty
toLocaleString
toString
valueOf
To be really safe in IE you have to use something like:
for (var key in myObject) {
alert(key);
}
var shadowedKeys = [
"isPrototypeOf",
"hasOwnProperty",
"toLocaleString",
"toString",
"valueOf"
];
for (var i=0, a=shadowedKeys, l=a.length; i<l; i++) {
if map.hasOwnProperty(a[i])) {
alert(a[i]);
}
}
The good news is that EcmaScript 5 defines the Object.keys(myObject)
function, which returns the keys of an object as array and some browsers (e.g. Safari 4) already implement it.
Here are some demo & short cuts if you uses GitHub, the basic ideas are the same.
1. Open terminal like this
2. Paste the below command to terminal followed by a space and then paste the path of the .xcuserstate file simply like this
3. Make sure you have the correct git ignore and then commit the code :)
Non of above answers works fine in case of container: 'body'
, and the following solution does:
// Assign custom CSS class after the tooltip template has been added to the DOM
$(document).on('inserted.bs.tooltip', function(e) {
var tooltip = $(e.target).data('bs.tooltip');
tooltip.$tip.addClass($(e.target).data('tooltip-custom-class'));
});
And a simple CSS snippet:
.tooltip.tooltip-danger > .tooltip-inner {
background-color: #d9534f;
}
.tooltip.tooltip-danger.left > .tooltip-arrow {
border-left-color: #d9534f;
}
Now you can init your tooltip as a usual, passing custom CSS class via data-tooltip-custom-class
attribute:
<span class="js-tooltip">Hover me totally</span>
<script>
$('.js-tooltip')
.data('tooltip-custom-class', 'tooltip-danger')
.tooltip(/*your options*/)
;
</script>
Your code works for me. When does addSalespersonOption
get called? There may be a problem with that call.
Also some of your html is a bit off (maybe copy/paste problem?), but that didn't seem to cause any problems. Your select should look like this:
<select id="salesperson">
<option value="">(select)</option>
</select>
instead of this:
<select id="salesperson" />
<option value"">(select)</option>
</select>
Edit: When does your options list get dynamically populated? Are you sure you are passing 'on'
for the defSales
value in your call to addSalespersonOption
? Try changing that code to this:
if (selected == "on") {
alert('setting default selected option to ' + text);
html = '<option value="'+value+'" selected="selected">'+text+'</option>';
}
and see if the alert happens and what is says if it does happen.
Edit: Working example of my testing (the error:undefined is from jsbin, not my code).
You have a lot of variants for using @RequestParam
with additional optional elements, e.g.
@RequestParam(required = false, defaultValue = "someValue", value="someAttr") String someAttr
If you don't put required = false
- param will be required by default.
defaultValue = "someValue"
- the default value to use as a fallback when the request parameter is not provided or has an empty value.
If request and method param are the same - you don't need value = "someAttr"
if you're goal is to reset EVERYTHING then @Björn's answer should be your goal but applied as:
* {
padding: initial;
}
if this is loaded after your original reset.css should have the same weight and will rely on each browser's default padding as initial value.
git pull
= git fetch
+ git merge
against tracking upstream branch
git pull --rebase
= git fetch
+ git rebase
against tracking upstream branch
If you want to know how git merge
and git rebase
differ, read this.
//Javascript_x000D_
$scope.update = function () {_x000D_
$scope.myItem;_x000D_
alert('Hello');_x000D_
}
_x000D_
<!--HTML-->_x000D_
<div class="form-group">_x000D_
<select name="name"_x000D_
id="id" _x000D_
ng-model="myItem" _x000D_
ng-options="size as size.name for size in sizes"_x000D_
class="form-control" _x000D_
ng-change="update()"_x000D_
multiple_x000D_
required>_x000D_
</select>_x000D_
</div>
_x000D_
If you want to write, name, id, class, multiple, required , You can write in this way.
You appear to have a heredoc
containing a single SQL*Plus command, though it doesn't look right as noted in the comments. You can either pass a value in the heredoc
:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql BUILDING
exit;
EOF
or if BUILDING
is $2
in your script:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql $2
exit;
EOF
If your file.sql
had an exit
at the end then it would be even simpler as you wouldn't need the heredoc
:
sqlplus -S user/pass@localhost @/opt/D2RQ/file.sql $2
In your SQL you can then refer to the position parameters using substitution variables:
...
}',SEM_Models('&1'),NULL,
...
The &1
will be replaced with the first value passed to the SQL script, BUILDING
; because that is a string it still needs to be enclosed in quotes. You might want to set verify off
to stop if showing you the substitutions in the output.
You can pass multiple values, and refer to them sequentially just as you would positional parameters in a shell script - the first passed parameter is &1
, the second is &2
, etc. You can use substitution variables anywhere in the SQL script, so they can be used as column aliases with no problem - you just have to be careful adding an extra parameter that you either add it to the end of the list (which makes the numbering out of order in the script, potentially) or adjust everything to match:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count BUILDING
exit;
EOF
or:
sqlplus -S user/pass@localhost << EOF
@/opt/D2RQ/file.sql total_count $2
exit;
EOF
If total_count
is being passed to your shell script then just use its positional parameter, $4
or whatever. And your SQL would then be:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&2'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
If you pass a lot of values you may find it clearer to use the positional parameters to define named parameters, so any ordering issues are all dealt with at the start of the script, where they are easier to maintain:
define MY_ALIAS = &1
define MY_MODEL = &2
SELECT COUNT(*) as &MY_ALIAS
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&MY_MODEL'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
From your separate question, maybe you just wanted:
SELECT COUNT(*) as &1
FROM TABLE(SEM_MATCH(
'{
?s rdf:type :ProcessSpec .
?s ?p ?o
}',SEM_Models('&1'),NULL,
SEM_ALIASES(SEM_ALIAS('','http://VISION/DataSource/SEMANTIC_CACHE#')),NULL));
... so the alias will be the same value you're querying on (the value in $2
, or BUILDING
in the original part of the answer). You can refer to a substitution variable as many times as you want.
That might not be easy to use if you're running it multiple times, as it will appear as a header above the count value in each bit of output. Maybe this would be more parsable later:
select '&1' as QUERIED_VALUE, COUNT(*) as TOTAL_COUNT
If you set pages 0
and set heading off
, your repeated calls might appear in a neat list. You might also need to set tab off
and possibly use rpad('&1', 20)
or similar to make that column always the same width. Or get the results as CSV with:
select '&1' ||','|| COUNT(*)
Depends what you're using the results for...
The shortest version I found is to use the --cat
option of parallel
like below. This version avoids using xargs, only relying on features of parallel
:
cat files.txt | \
parallel -n 500 --lb --pipe --cat rsync --files-from={} user@remote:/dir /dir -avPi
#### Arg explainer
# -n 500 :: split input into chunks of 500 entries
#
# --cat :: create a tmp file referenced by {} containing the 500
# entry content for each process
#
# user@remote:/dir :: the root relative to which entries in files.txt are considered
#
# /dir :: local root relative to which files are copied
Sample content from files.txt
:
/dir/file-1
/dir/subdir/file-2
....
Note that this doesn't use -j 50
for job count, that didn't work on my end here. Instead I've used -n 500
for record count per job, calculated as a reasonable number given the total number of records.
Actually, on investigating this, I think all these answers are incorrect. Your question is misleading because of our level of understanding of maven
. And I say our because I'm just getting introduced to maven
.
In Eclipse
, when you want to add a jar file to your project, normally you download the jar manually and then drop it into the lib directory. With maven, you don't do it this way. Here's what you do:
dependency
statement into your pom.xml
mvn
Now, maven
will connect and download the jar
along with the list of dependencies, and automatically resolve any additional dependencies that jar
may have had. So if the jar
also needed commons-logging, that will be downloaded as well.
If you ever need to delete all the indexes, this may come in handy:
curl -X DELETE 'http://localhost:9200/_all'
Powershell:
Invoke-WebRequest -method DELETE http://localhost:9200/_all
Predicate<Client> hasSameNameAsOneUser =
c -> users.stream().anyMatch(u -> u.getName().equals(c.getName()));
return clients.stream()
.filter(hasSameNameAsOneUser)
.collect(Collectors.toList());
But this is quite inefficient, because it's O(m * n). You'd better create a Set of acceptable names:
Set<String> acceptableNames =
users.stream()
.map(User::getName)
.collect(Collectors.toSet());
return clients.stream()
.filter(c -> acceptableNames.contains(c.getName()))
.collect(Collectors.toList());
Also note that it's not strictly equivalent to the code you have (if it compiled), which adds the same client twice to the list if several users have the same name as the client.
Couldn't you just use
function getFormatedDate(date) {
if (date.isValid()) {
var month = date.GetMonth();
}
}
You could try using a Polyfill. The following Polyfill was published in 2019 and did the trick for me. It assigns the Promise function to the window object.
used like: window.Promise
https://www.npmjs.com/package/promise-polyfill
If you want more information on Polyfills check out the following MDN web doc https://developer.mozilla.org/en-US/docs/Glossary/Polyfill
I know this is very old question but I had the same requirement and just discovered that after c#6 you can use static in using for classes to import.
I hope this helps someone....
using static yourNameSpace.YourClass;
I had the same problem. Try to make a bat-file to start the Qt Creator. Add something like this to the bat-file:
call "C:\Program Files\Microsoft Visual Studio 9.0\VC\bin\vcvars32.bat"
"C:\QTsdk\qtcreator\bin\qtcreator"
Now I can compile and get:
jom 1.0.8 - empower your cores
11:10:08: The process "C:\QTsdk\qtcreator\bin\jom.exe" exited normally.
If you are using java technology(Servlet/JSP) for making web application you will probably use Apache Tomcat. However, if you are using other technologies like Perl, PHP or ruby, its better(easier) to use Apache HTTP Server.
I always prefer to read input using nextLine()
and then parse the string.
Using next()
will only return what comes before the delimiter (defaults to whitespace). nextLine()
automatically moves the scanner down after returning the current line.
A useful tool for parsing data from nextLine()
would be str.split("\\s+")
.
String data = scanner.nextLine();
String[] pieces = data.split("\\s+");
// Parse the pieces
For more information regarding the Scanner class or String class refer to the following links.
Scanner: http://docs.oracle.com/javase/7/docs/api/java/util/Scanner.html
String: http://docs.oracle.com/javase/7/docs/api/java/lang/String.html
foreach (DataGridViewColumn column in dataGridView.Columns)
{
column.SortMode = DataGridViewColumnSortMode.NotSortable;
}
Another option is to create a self-signed certificate that allows you to specify the domain name per website. This means you can use it across many domain names.
In IIS Manager
Now, on your website in IIS...
In order to do this, you need to have a small program that displays a messagebox and run that from your batch file.
You could open a console window that displays a prompt though, but getting a GUI message box using cmd.exe and friends only is not possible, AFAIK.
this is probably the best way to use react-router-dom with a cookie handler
in index.js
import React, { Component } from 'react'
import {Switch,Route,Redirect} from "react-router-dom"
import {RouteWithLayout} from "./cookieCheck"
import Login from "../app/pages/login"
import DummyLayout from "../app/layouts/dummy"
import DummyPage from "../app/pages/dummy"
export default ({props})=>{
return(
<Switch>
<Route path="/login" component={Login} />
<RouteWithLayout path="/dummy" layout={DummyLayout} component={DummyPage}
{...props}/>
<Redirect from="/*" to="/login" />
</Switch>
)
}
and use a cookieCheck
import React , {createElement} from 'react'
import {Route,Redirect} from "react-router-dom"
import {COOKIE,getCookie} from "../services/"
export const RouteWithLayout = ({layout,component,...rest})=>{
if(getCookie(COOKIE)==null)return <Redirect to="/login"/>
return (
<Route {...rest} render={(props) =>
createElement(layout, {...props, ...rest}, createElement(component,
{...props, ...rest}))
}
/>
)
}
Boys and Girls!
Since Django's 1.7 in send_email method the html_message
parameter was added.
html_message: If html_message is provided, the resulting email will be a multipart/alternative email with message as the text/plain content type and html_message as the text/html content type.
So you can just:
from django.core.mail import send_mail
from django.template.loader import render_to_string
msg_plain = render_to_string('templates/email.txt', {'some_params': some_params})
msg_html = render_to_string('templates/email.html', {'some_params': some_params})
send_mail(
'email title',
msg_plain,
'[email protected]',
['[email protected]'],
html_message=msg_html,
)
The right solution would be if you have android studio installed then
Android SDK Tools (Obsolete)
flutter doctor
and it should now prompt you to run flutter doctor --android-licenses
once you run the license command accept all licenses by hitting y and it should solve the problemYou can also use RedirectMatch directive to deny access to a folder.
To deny access to a folder, you can use the following RedirectMatch in htaccess :
RedirectMatch 403 ^/folder/?$
This will forbid an external access to /folder/ eg : http://example.com/folder/ will return a 403 forbidden error.
To deny access to everything inside the folder, You can use this :
RedirectMatch 403 ^/folder/.*$
This will block access to the entire folder eg : http://example.com/folder/anyURI will return a 403 error response to client.
Use jQuery's beforeSend
callback to add an HTTP header with the authentication information:
beforeSend: function (xhr) {
xhr.setRequestHeader ("Authorization", "Basic " + btoa(username + ":" + password));
},
I compare strings using =
and not <>
. I've found out that in this context =
seems to work in more reasonable fashion than <>
. I have specified that two empty (or NULL) strings are equal. The real implementation returns PL/SQL boolean, but here I changed that to pls_integer (0 is false and 1 is true) to be able easily demonstrate the function.
create or replace function is_equal(a in varchar2, b in varchar2)
return pls_integer as
begin
if a is null and b is null then
return 1;
end if;
if a = b then
return 1;
end if;
return 0;
end;
/
show errors
begin
/* Prints 0 */
dbms_output.put_line(is_equal('AAA', 'BBB'));
dbms_output.put_line(is_equal('AAA', null));
dbms_output.put_line(is_equal(null, 'BBB'));
dbms_output.put_line(is_equal('AAA', ''));
dbms_output.put_line(is_equal('', 'BBB'));
/* Prints 1 */
dbms_output.put_line(is_equal(null, null));
dbms_output.put_line(is_equal(null, ''));
dbms_output.put_line(is_equal('', ''));
dbms_output.put_line(is_equal('AAA', 'AAA'));
end;
/
The log file is not visible because the slf4j configuration file location needs to passed to the java run command using the following arguments .(e.g.)
-Dlogging.config={file_location}\log4j2.xml
or this:
-Dlog4j.configurationFile={file_location}\log4j2.xml
There's no easy way to do this, but something like this will work:
SELECT ET.TrainingID,
ET.CompletedDate,
ET.Notes
FROM
HR_EmployeeTrainings ET
inner join
(
select TrainingID, Max(CompletedDate) as CompletedDate
FROM HR_EmployeeTrainings
WHERE (ET.AvantiRecID IS NULL OR ET.AvantiRecID = @avantiRecID)
GROUP BY AvantiRecID, TrainingID
) ET2
on ET.TrainingID = ET2.TrainingID
and ET.CompletedDate = ET2.CompletedDate
you can also use this code
public static double roundToDecimals(double d, int c)
{
int temp = (int)(d * Math.pow(10 , c));
return ((double)temp)/Math.pow(10 , c);
}
It gives you control of how many numbers after the point are needed.
d = number to round;
c = number of decimal places
think it will be helpful
You can use block (/***/) or single line comment (//) for each line. You should use "#" in sh command.
Block comment
/* _x000D_
post {_x000D_
success {_x000D_
mail to: "[email protected]", _x000D_
subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
body: "Yay, we passed."_x000D_
}_x000D_
failure {_x000D_
mail to: "[email protected]", _x000D_
subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
body: "Boo, we failed."_x000D_
}_x000D_
}_x000D_
*/
_x000D_
Single Line
// post {_x000D_
// success {_x000D_
// mail to: "[email protected]", _x000D_
// subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
// body: "Yay, we passed."_x000D_
// }_x000D_
// failure {_x000D_
// mail to: "[email protected]", _x000D_
// subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
// body: "Boo, we failed."_x000D_
// }_x000D_
// }
_x000D_
Comment in 'sh' command
stage('Unit Test') {_x000D_
steps {_x000D_
ansiColor('xterm'){_x000D_
sh '''_x000D_
npm test_x000D_
# this is a comment in sh_x000D_
'''_x000D_
}_x000D_
}_x000D_
}
_x000D_
I got the same error when I was calling
this.handleClick = this.handleClick.bind(this);
in my constructor when handleClick didn't exist
(I had erased it and had accidentally left the "this" binding statement in my constructor).
Solution = remove the "this" binding statement.
Something like:
if exists (select top 1 * from Sites S where S.Id IS NOT NULL AND S.Status = 1 AND (S.WebUserId = @WebUserId OR S.AllowUploads = 1))
select 1
else
select 0
Series.apply(func, convert_dtype=True, args=(), **kwds)
args : tuple
x = my_series.apply(my_function, args = (arg1,))
Assuming you mean "file on a local filesystem" when you say .json file.
You'll need to save the json data formatted as jsonp, and use a file:// url
to access it.
Your HTML will look like this:
<script src="file://c:\\data\\activity.jsonp"></script>
<script type="text/javascript">
function updateMe(){
var x = 0;
var activity=jsonstr;
foreach (i in activity) {
date = document.getElementById(i.date).innerHTML = activity.date;
event = document.getElementById(i.event).innerHTML = activity.event;
}
}
</script>
And the file c:\data\activity.jsonp contains the following line:
jsonstr = [ {"date":"July 4th", "event":"Independence Day"} ];
You can use the "export" solution just like what other guys have suggested. I'd like to provide you with another solution for permanent convenience: you can use any path as GOPATH when running Go commands.
Firstly, you need to download a small tool named gost
: https://github.com/byte16/gost/releases . If you use ubuntu, you can download the linux version(https://github.com/byte16/gost/releases/download/v0.1.0/gost_linux_amd64.tar.gz).
Then you need to run the commands below to unpack it :
$ cd /path/to/your/download/directory
$ tar -xvf gost_linux_amd64.tar.gz
You would get an executable gost
. You can move it to /usr/local/bin
for convenient use:
$ sudo mv gost /usr/local/bin
Run the command below to add the path you want to use as GOPATH into the pathspace gost
maintains. It is required to give the path a name which you would use later.
$ gost add foo /home/foobar/bar # 'foo' is the name and '/home/foobar/bar' is the path
Run any Go command you want in the format:
gost goCommand [-p {pathName}] -- [goFlags...] [goArgs...]
For example, you want to run go get github.com/go-sql-driver/mysql
with /home/foobar/bar
as the GOPATH, just do it as below:
$ gost get -p foo -- github.com/go-sql-driver/mysql # 'foo' is the name you give to the path above.
It would help you to set the GOPATH and run the command. But remember that you have added the path into gost
's pathspace. If you are under any level of subdirectories of /home/foobar/bar
, you can even just run the command below which would do the same thing for short :
$ gost get -- github.com/go-sql-driver/mysql
gost
is a Simple Tool of Go which can help you to manage GOPATHs and run Go commands. For more details about how to use it to run other Go commands, you can just run gost help goCmdName
. For example you want to know more about install
, just type words below in:
$ gost help install
You can also find more details in the README of the project: https://github.com/byte16/gost/blob/master/README.md
This worked for me, combo of two answers from above:
set a WebViewClient
to your WebView, start your progress dialog on you onCreate()
method an dismiss it when the page has finished loading in onPageFinished(WebView view, String url)
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Main extends Activity {
private WebView webview;
private static final String TAG = "Main";
private ProgressDialog progressBar;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.main);
this.webview = (WebView)findViewById(R.id.webview);
WebSettings settings = webview.getSettings();
settings.setJavaScriptEnabled(true);
webview.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
final AlertDialog alertDialog = new AlertDialog.Builder(this).create();
progressBar = ProgressDialog.show(Main.this, "WebView Example", "Loading...");
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Log.i(TAG, "Processing webview url click...");
view.loadUrl(url);
return true;
}
public void onPageFinished(WebView view, String url) {
Log.i(TAG, "Finished loading URL: " +url);
if (progressBar.isShowing()) {
progressBar.dismiss();
}
}
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
Log.e(TAG, "Error: " + description);
Toast.makeText(activity, "Oh no! " + description, Toast.LENGTH_SHORT).show();
alertDialog.setTitle("Error");
alertDialog.setMessage(description);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
return;
}
});
alertDialog.show();
}
});
webview.loadUrl("http://www.google.com");
}
}
your main.xml layout
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<WebView android:id="@string/webview"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_weight="1" />
</LinearLayout>
A more simplified version of the above and presuming you're not using custom indexes...
$len = count($array);
foreach ($array as $index => $item) {
if ($index == 0) {
// first
} else if ($index == $len - 1) {
// last
}
}
Version 2 - Because I have come to loathe using the else unless necessary.
$len = count($array);
foreach ($array as $index => $item) {
if ($index == 0) {
// first
// do something
continue;
}
if ($index == $len - 1) {
// last
// do something
continue;
}
}
tabindex HTML attribute indicates if its element can be focused, and if/where it participates in sequential keyboard navigation (usually with the Tab
key). Read MDN Web Docs for full reference.
$( "#division" ).keydown(function(evt) {
evt = evt || window.event;
console.log("keydown: " + evt.keyCode);
});
_x000D_
#division {
width: 90px;
height: 30px;
background: lightgrey;
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="division" tabindex="0"></div>
_x000D_
var el = document.getElementById("division");
el.onkeydown = function(evt) {
evt = evt || window.event;
console.log("keydown: " + evt.keyCode);
};
_x000D_
#division {
width: 90px;
height: 30px;
background: lightgrey;
}
_x000D_
<div id="division" tabindex="0"></div>
_x000D_
I break the task up into smaller units. Test with different batch size intervals for your table, until you find an interval that performs optimally. Here is a sample that I have used in the past.
declare @counter int
declare @numOfRecords int
declare @batchsize int
set @numOfRecords = (SELECT COUNT(*) AS NumberOfRecords FROM <TABLE> with(nolock))
set @counter = 0
set @batchsize = 2500
set rowcount @batchsize
while @counter < (@numOfRecords/@batchsize) +1
begin
set @counter = @counter + 1
Update table set int_field = -1 where int_field <> -1;
end
set rowcount 0
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
$('textarea').val();
textarea.value
would be pure JavaScript, but here you're trying to use JavaScript as a not-valid jQuery method (.value
).
No.
First off, append
is a function, so you can't write append[i+1:i+4]
because you're trying to get a slice of a thing that isn't a sequence. (You can't get an element of it, either: append[i+1]
is wrong for the same reason.) When you call a function, the argument goes in parentheses, i.e. the round ones: ()
.
Second, what you're trying to do is "take a sequence, and put every element in it at the end of this other sequence, in the original order". That's spelled extend
. append
is "take this thing, and put it at the end of the list, as a single item, even if it's also a list". (Recall that a list is a kind of sequence.)
But then, you need to be aware that i+1:i+4
is a special construct that appears only inside square brackets (to get a slice from a sequence) and braces (to create a dict
object). You cannot pass it to a function. So you can't extend
with that. You need to make a sequence of those values, and the natural way to do this is with the range
function.
If the string is at the beginning of the name, you can do this
$ compgen -f .bash
.bashrc
.bash_profile
.bash_prompt
Because Dictionary
is a generic class ( Dictionary<TKey, TValue>
), so that accessing its content is type-safe (i.e. you do not need to cast from Object
, as you do with a Hashtable
).
Compare
var customers = new Dictionary<string, Customer>();
...
Customer customer = customers["Ali G"];
to
var customers = new Hashtable();
...
Customer customer = customers["Ali G"] as Customer;
However, Dictionary
is implemented as hash table internally, so technically it works the same way.
For each conflicted file you get, you can specify
git checkout --ours -- <paths>
# or
git checkout --theirs -- <paths>
From the git checkout
docs
git checkout [-f|--ours|--theirs|-m|--conflict=<style>] [<tree-ish>] [--] <paths>...
--ours
--theirs
When checking out paths from the index, check out stage #2 (ours
) or #3 (theirs
) for unmerged paths.The index may contain unmerged entries because of a previous failed merge. By default, if you try to check out such an entry from the index, the checkout operation will fail and nothing will be checked out. Using
-f
will ignore these unmerged entries. The contents from a specific side of the merge can be checked out of the index by using--ours
or--theirs
. With-m
, changes made to the working tree file can be discarded to re-create the original conflicted merge result.
See http://adamalbrecht.com/2013/12/12/creating-a-simple-modal-dialog-directive-in-angular-js/ for a simple way of doing modal dialog with Angular and without needing bootstrap
Edit: I've since been using ng-dialog from http://likeastore.github.io/ngDialog which is flexible and doesn't have any dependencies.
You can try DexPatcher. It even integrates with Android Studio. It uses Apktool and Dex2Jar internally.
You can use those tools independently as well.
Apktool decompiles apk, and extracts .dex files, which can further be converted to jar using Dex2Jar. Jar can be decompiled by using JD-GUI. You can see the Java code with the help of that tool. Although the similarity of decompiled code to the actual code cannot be guaranteed. There are some advanced code obfuscation tools available in the market, which mess up the code to make it difficult to decompile / understand. eg. Proguard
You should use a hidden input as a refresh indicator, with a value of "no":
<input type="hidden" id="refresh" value="no">
Now using jQuery, you can check its value:
$(document).ready(function(e) {
var $input = $('#refresh');
$input.val() == 'yes' ? location.reload(true) : $input.val('yes');
});
When you click on the back button, the values in hidden fields retain the same value as when you originally left the page.
So the first time you load the page, the input's value would be "no". When you return to the page, it'll be "yes" and your JavaScript code will trigger a refresh.
I have difficulty in decrypting a long string that is encrypted in python. Here is the python encryption function:
def RSA_encrypt(public_key, msg, chunk_size=214):
"""
Encrypt the message by the provided RSA public key.
:param public_key: RSA public key in PEM format.
:type public_key: binary
:param msg: message that to be encrypted
:type msg: string
:param chunk_size: the chunk size used for PKCS1_OAEP decryption, it is determined by \
the private key length used in bytes - 42 bytes.
:type chunk_size: int
:return: Base 64 encryption of the encrypted message
:rtype: binray
"""
rsa_key = RSA.importKey(public_key)
rsa_key = PKCS1_OAEP.new(rsa_key)
encrypted = b''
offset = 0
end_loop = False
while not end_loop:
chunk = msg[offset:offset + chunk_size]
if len(chunk) % chunk_size != 0:
chunk += " " * (chunk_size - len(chunk))
end_loop = True
encrypted += rsa_key.encrypt(chunk.encode())
offset += chunk_size
return base64.b64encode(encrypted)
The decryption in PHP:
/**
* @param base64_encoded string holds the encrypted message.
* @param Resource your private key loaded using openssl_pkey_get_private
* @param integer Chunking by bytes to feed to the decryptor algorithm.
* @return String decrypted message.
*/
public function RSADecyrpt($encrypted_msg, $ppk, $chunk_size=256){
if(is_null($ppk))
throw new Exception("Returned message is encrypted while you did not provide private key!");
$encrypted_msg = base64_decode($encrypted_msg);
$offset = 0;
$chunk_size = 256;
$decrypted = "";
while($offset < strlen($encrypted_msg)){
$decrypted_chunk = "";
$chunk = substr($encrypted_msg, $offset, $chunk_size);
if(openssl_private_decrypt($chunk, $decrypted_chunk, $ppk, OPENSSL_PKCS1_OAEP_PADDING))
$decrypted .= $decrypted_chunk;
else
throw new exception("Problem decrypting the message");
$offset += $chunk_size;
}
return $decrypted;
}
I have created a simple library that takes a screenshot from a View
and either gives you a Bitmap object or saves it directly to any path you want
Mac OS: On Terminal:
vim <your jar location>
after jar gets opened, press / and pass your class name and hit enter
get_or_create
returns a tuple.
customer.source, created = Source.objects.get_or_create(name="Website")
If your code is:
<input type="text" id="mytext"/>
And If you are using JQuery, You can use this too:
<script>
function setFocusToTextBox(){
$("#mytext").focus();
}
</script>
Keep in mind that you must draw the input first $(document).ready()
I know the post is old but after a 3 months time and with various email combinations I came across, able to make this sql for validating Email IDs.
CREATE FUNCTION [dbo].[isValidEmailFormat]
(
@EmailAddress varchar(500)
)
RETURNS bit
AS
BEGIN
DECLARE @Result bit
SET @EmailAddress = LTRIM(RTRIM(@EmailAddress));
SELECT @Result =
CASE WHEN
CHARINDEX(' ',LTRIM(RTRIM(@EmailAddress))) = 0
AND LEFT(LTRIM(@EmailAddress),1) <> '@'
AND RIGHT(RTRIM(@EmailAddress),1) <> '.'
AND LEFT(LTRIM(@EmailAddress),1) <> '-'
AND CHARINDEX('.',@EmailAddress,CHARINDEX('@',@EmailAddress)) - CHARINDEX('@',@EmailAddress) > 2
AND LEN(LTRIM(RTRIM(@EmailAddress))) - LEN(REPLACE(LTRIM(RTRIM(@EmailAddress)),'@','')) = 1
AND CHARINDEX('.',REVERSE(LTRIM(RTRIM(@EmailAddress)))) >= 3
AND (CHARINDEX('.@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
AND (CHARINDEX('-@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
AND (CHARINDEX('_@',@EmailAddress) = 0 AND CHARINDEX('..',@EmailAddress) = 0)
AND ISNUMERIC(SUBSTRING(@EmailAddress, 1, 1)) = 0
AND CHARINDEX(',', @EmailAddress) = 0
AND CHARINDEX('!', @EmailAddress) = 0
AND CHARINDEX('-.', @EmailAddress)=0
AND CHARINDEX('%', @EmailAddress)=0
AND CHARINDEX('#', @EmailAddress)=0
AND CHARINDEX('$', @EmailAddress)=0
AND CHARINDEX('&', @EmailAddress)=0
AND CHARINDEX('^', @EmailAddress)=0
AND CHARINDEX('''', @EmailAddress)=0
AND CHARINDEX('\', @EmailAddress)=0
AND CHARINDEX('/', @EmailAddress)=0
AND CHARINDEX('*', @EmailAddress)=0
AND CHARINDEX('+', @EmailAddress)=0
AND CHARINDEX('(', @EmailAddress)=0
AND CHARINDEX(')', @EmailAddress)=0
AND CHARINDEX('[', @EmailAddress)=0
AND CHARINDEX(']', @EmailAddress)=0
AND CHARINDEX('{', @EmailAddress)=0
AND CHARINDEX('}', @EmailAddress)=0
AND CHARINDEX('?', @EmailAddress)=0
AND CHARINDEX('<', @EmailAddress)=0
AND CHARINDEX('>', @EmailAddress)=0
AND CHARINDEX('=', @EmailAddress)=0
AND CHARINDEX('~', @EmailAddress)=0
AND CHARINDEX('`', @EmailAddress)=0
AND CHARINDEX('.', SUBSTRING(@EmailAddress, CHARINDEX('@', @EmailAddress)+1, 2))=0
AND CHARINDEX('.', SUBSTRING(@EmailAddress, CHARINDEX('@', @EmailAddress)-1, 2))=0
AND LEN(SUBSTRING(@EmailAddress, 0, CHARINDEX('@', @EmailAddress)))>1
AND CHARINDEX('.', REVERSE(@EmailAddress)) > 2
AND CHARINDEX('.', REVERSE(@EmailAddress)) < 5
THEN 1 ELSE 0 END
RETURN @Result
END
Any suggestions are welcomed!
int arr[5][4];
For the row subscript(4 raise to 2, include cmath to use pow):
sizeof(arr1)/pow(4,2)
Column subscript:
sizeof(*arr1)/4
4 means 4 bytes, size of int.
You need to examine (put a breakpoint on / Quick Watch) the Request object in the Page_Load
method of your Test.aspx.cs
file.
If you're only concerned with mobile:
input[type="date"]:invalid:before{
color: rgb(117, 117, 117);
content: attr(placeholder);
}
code example below:
g.setFont(new Font("TimesRoman", Font.PLAIN, 30));
g.drawString("Welcome to the Java Applet", 20 , 20);
To Determine if a string is Int or Float and to represent in longer format.
Integer
String cost=Long.MAX_VALUE+"";
if (isNumeric (cost)) // returns false for non numeric
{
BigInteger bi = new BigInteger(cost);
}
public static boolean isNumeric(String str)
{
NumberFormat formatter = NumberFormat.getInstance();
ParsePosition pos = new ParsePosition(0);
formatter.parse(str, pos);
return str.length() == pos.getIndex();
}
This is a little bit fancy... but it works:
Step 1: Create a Powershell Profile:
FILE: install_profile.ps1
# THIS SCRIPT BLOWS AWAY YOUR DEFAULT POWERSHELL PROFILE SCRIPT
# AND INSTALLS A POINTER TO A GLOBAL POWERSHELL PROFILE
$ErrorActionPreference = "Stop"
function print ([string]$msg)
{
Write-Host -ForegroundColor Green $msg
}
print ""
# User's Powershell Profile
$psdir = "$env:USERPROFILE\Documents\WindowsPowerShell"
$psfile = $psdir + "\Microsoft.PowerShell_profile.ps1"
print "Creating Directory: $psdir"
md $psdir -ErrorAction SilentlyContinue | out-null
# this is your auto-generated powershell profile to be installed
$content = @(
"",
". ~/Documents/tools/profile.ps1",
""
)
print "Creating File: $psfile"
[System.IO.File]::WriteAllLines($psfile, $content)
print ""
# Make sure Powershell profile is readable
Set-ExecutionPolicy -Scope CurrentUser Unrestricted
Step 2: then in tools ~/Documents/tools/profile.ps1:
function Do-ActualThing {
# do actual thing
}
Set-Alias MyAlias Do-ActualThing
Step 3:
$ Set-ExecutionPolicy -Scope CurrentUser Unrestricted $ . ./install_profile.ps1
header files contain prototypes for functions you define in a .c or .cpp/.cxx file (depending if you're using c or c++). You want to place #ifndef/#defines around your .h code so that if you include the same .h twice in different parts of your programs, the prototypes are only included once.
client.h
#ifndef CLIENT_H
#define CLIENT_H
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize);
#endif /** CLIENT_H */
Then you'd implement the .h in a .c file like so:
client.c
#include "client.h"
short socketConnect(char *host,unsigned short port,char *sendbuf,char *recievebuf, long rbufsize) {
short ret = -1;
//some implementation here
return ret;
}
With ggplot2
:
p<-qplot(spray,count,data=InsectSprays,geom='boxplot')
p<-p+stat_summary(fun.y=mean,shape=1,col='red',geom='point')
print(p)
Another tool I like is Open STA: http://opensta.org/
It is mainly focused on the performance testing and it is free.
UPDATE 2018:
Since the answer is quite old, the OpenSTA project seems not very active (however the tool is still available) but now there are two other tool I would also recommends:
In my opinion Gatling seems better as there is no limitation and they also provide commercial Enterprise solution and fit with continuous integration tools like Jenkins.
NeoLoad in the contrary have a free version but limited to 50 user (that can be enough for some cases). The full comparison of features is here.
To check for local differences:
git diff myfile.txt
or you can use a diff tool (in case you'd like to revert some changes):
git difftool myfile.txt
To use git difftool
more efficiently, install and use your favourite GUI tool such as Meld, DiffMerge or OpenDiff.
Note: You can also use .
(instead of filename) to see current dir changes.
In order to check changes per each line, use: git blame
which will display which line was commited in which commit.
To view the actual file before the commit (where master
is your branch), run:
git show master:path/my_file
First click show all files. Then in the bin folder choose any xml file and then right click and by selecting 'browse with' select your desired browser.
I had a similar problem due to a zombie vim.exe process.
Killing it in Task Manager, followed by a git rebase --abort
fixed it.
You do not define a binding in your service's config, so you are getting the default values for wsHttpBinding
, and the default value for securityMode\transport
for that binding is Message
.
Try copying your binding configuration from the client's config to your service config and assign that binding to the endpoint via the bindingConfiguration
attribute:
<bindings>
<wsHttpBinding>
<binding name="ota2010AEndpoint"
.......>
<readerQuotas maxDepth="32" ... />
<reliableSession ordered="true" .... />
<security mode="Transport">
<transport clientCredentialType="None" proxyCredentialType="None"
realm="" />
<message clientCredentialType="Windows" negotiateServiceCredential="true"
establishSecurityContext="true" />
</security>
</binding>
</wsHttpBinding>
</bindings>
(Snipped parts of the config to save space in the answer).
<service name="Synxis" behaviorConfiguration="SynxisWCF">
<endpoint address="" name="wsHttpEndpoint"
binding="wsHttpBinding"
bindingConfiguration="ota2010AEndpoint"
contract="Synxis" />
This will then assign your defined binding (with Transport security) to the endpoint.
Ideally runtime exceptions should not be thrown. A checked exception(business exception) should be created for your scenario. Because if either of these exception is thrown and logged, it misguides the developer while going through the logs. Instead business exceptions do not create that panic and usually ignored while troubleshooting logs.
All you need to do is a post request like below :-
POST https://www.googleapis.com/oauth2/v4/token
Content-Type: application/json
{
"client_id": <client_id>,
"client_secret": <client_secret>,
"refresh_token": <refresh_token>,
"grant_type": "refresh_token"
}
//the following code checks if your radio button having name like 'yourRadioName'
//is checked or not
$(document).ready(function() {
if($("input:radio[name='yourRadioName']").is(":checked")) {
//its checked
}
});
Dang this is hard. Here is what I did to reject/delete/replace my ios build before it was released. The app was approved how ever I found found a bug I wanted to fix before releasing
To replace the bad build I did the following
Tried all of the options above. What worked for me was:
Domain
Path=/
Resulting Set-Cookie
header:
Set-Cookie: session_token=74528588-7c48-4546-a3ae-4326e22449e5; Expires=Sun, 16 Aug 2020 04:40:42 GMT; Path=/
A nice practical use of this is if you want to make your own HtmlHelper
extensions. For example, I hate trying to remember the <link>
tag syntax, so I've created my own extension method to make a <link>
tag:
<Extension()> _
Public Function CssBlock(ByVal html As HtmlHelper, ByVal src As String, ByVal Optional ByVal htmlAttributes As Object = Nothing) As MvcHtmlString
Dim tag = New TagBuilder("link")
tag.MergeAttribute("type", "text/css")
tag.MergeAttribute("rel", "stylesheet")
tag.MergeAttribute("href", src)
tag.MergeAttributes(New RouteValueDictionary(htmlAttributes))
Dim result = tag.ToString(TagRenderMode.Normal)
Return MvcHtmlString.Create(result)
End Function
I could have returned String
from this method, but if I had the following would break:
<%: Html.CssBlock(Url.Content("~/sytles/mysite.css")) %>
With MvcHtmlString
, using either <%: ... %>
or <%= ... %>
will both work correctly.
It would help you... assume you have a form with "formname" form and a text box with "txt" name. then you can use following code to allow only aphanumeric values
var checkString = document.formname.txt.value;
if (checkString != "") {
if ( /[^A-Za-z\d]/.test(checkString)) {
alert("Please enter only letter and numeric characters");
document.formname.txt.focus();
return (false);
}
}
Just to add to what Cade said, this is usually a front-end display thing and should therefore be handled there. I know that sometimes it's easier to write something 100% in SQL for things like file export or other "SQL only" solutions, but most of the times this concatenation should be handled in your display layer.
You can do some thing like this,
Initialize with empty array and assign the values later
String importRt = "23:43 43:34";
if(null != importRt) {
importArray = Arrays.stream(importRt.split(" "))
.map(String::trim)
.toArray(String[]::new);
}
System.out.println(Arrays.toString(exportImportArray));
Hope it helps..
The Instagram API requires user authentication through OAuth to access the recent media endpoint for a user. There doesn't appear to be any other way right now to get all media for a user.
Open eclipse.ini
Search for -Xmx512m
or maybe more size it is.
Just change it to a required size such as I changed it to -Xmx1024m
Depending on the Tkinter activity, and especially when using Tkinter.after, stopping this activity with destroy()
-- even by using protocol(), a button, etc. -- will disturb this activity ("while executing" error) rather than just terminate it. The best solution in almost every case is to use a flag. Here is a simple, silly example of how to use it (although I am certain that most of you don't need it! :)
from Tkinter import *
def close_window():
global running
running = False # turn off while loop
print( "Window closed")
root = Tk()
root.protocol("WM_DELETE_WINDOW", close_window)
cv = Canvas(root, width=200, height=200)
cv.pack()
running = True;
# This is an endless loop stopped only by setting 'running' to 'False'
while running:
for i in range(200):
if not running:
break
cv.create_oval(i, i, i+1, i+1)
root.update()
This terminates graphics activity nicely. You only need to check running
at the right place(s).
if not exist "%USERPROFILE%\.qgis-custom\" (
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
)
You have it almost done. The logic is correct, just some little changes.
This code checks for the existence of the folder (see the ending backslash, just to differentiate a folder from a file with the same name).
If it does not exist then it is created and creation status is checked. If a file with the same name exists or you have no rights to create the folder, it will fail.
If everyting is ok, files are copied.
All paths are quoted to avoid problems with spaces.
It can be simplified (just less code, it does not mean it is better). Another option is to always try to create the folder. If there are no errors, then copy the files
mkdir "%USERPROFILE%\.qgis-custom" 2>nul
if not errorlevel 1 (
xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
)
In both code samples, files are not copied if the folder is not being created during the script execution.
EDITED - As dbenham comments, the same code can be written as a single line
md "%USERPROFILE%\.qgis-custom" 2>nul && xcopy "%OSGEO4W_ROOT%\qgisconfig" "%USERPROFILE%\.qgis-custom" /s /v /e
The code after the &&
will only be executed if the previous command does not set errorlevel. If mkdir
fails, xcopy
is not executed.
I solved this removing the various empty files that git fsck was detecting, and then running a simple git pull.
I find it disappointing that now that even filesystems implement journaling and other "transactional" techniques to keep the fs sane, git can get to a corrupted state (and not be able to recover by itself) because of a power failure or space on device.
2.39KB minified. One file. https://github.com/rhroyston/clock-js
Current Time is
var str = clock.month;
var m = str.charAt(0).toUpperCase() + str.slice(1,3); //gets you abbreviated month
clock.weekday + ' ' + clock.time + ' ' + clock.day + ' ' + m + ' ' + clock.year; //"tuesday 5:50 PM 3 May 2016"
Add your own flavour of the font awesome style
[class^="icon-"], [class*=" icon-"] {
display: inline-block;
width: 100%;
}
which along with your
td i {
text-align:center;
}
should center just the icons.
this is the query you need:
SELECT b.id, a.home,b.[datetime],b.player,a.resource FROM
(SELECT home,MAX(resource) AS resource FROM tbl_1 GROUP BY home) AS a
LEFT JOIN
(SELECT id,home,[datetime],player,resource FROM tbl_1) AS b
ON a.resource = b.resource WHERE a.home =b.home;
It is actually possible to return an anonymous type from a method in a particular use-case. Let's have a look!
With C# 7 it is possible to return anonymous types from a method, although it comes with a slight constraint. We are going to use a new language feature called local function together with an indirection trick (another layer of indirection can solve any programming challenge, right?).
Here's a use-case I recently identified. I want to log all configuration values after I have loaded them from AppSettings
. Why? Because there's some logic around missing values that revert to default values, some parsing and so on. An easy way to log the values after applying the logic is to put them all in a class and serialize it to a logfile (using log4net). I also want to encapsulate the complex logic of dealing with settings and separate that from whatever I need to do with them. All without creating a named class that exists just for a single use!
Let's see how to solve this using a local function that creates an anonymous type.
public static HttpClient CreateHttpClient()
{
// I deal with configuration values in this slightly convoluted way.
// The benefit is encapsulation of logic and we do not need to
// create a class, as we can use an anonymous class.
// The result resembles an expression statement that
// returns a value (similar to expressions in F#)
var config = Invoke(() =>
{
// slightly complex logic with default value
// in case of missing configuration value
// (this is what I want to encapsulate)
int? acquireTokenTimeoutSeconds = null;
if (int.TryParse(ConfigurationManager.AppSettings["AcquireTokenTimeoutSeconds"], out int i))
{
acquireTokenTimeoutSeconds = i;
}
// more complex logic surrounding configuration values ...
// construct the aggregate configuration class as an anonymous type!
var c = new
{
AcquireTokenTimeoutSeconds =
acquireTokenTimeoutSeconds ?? DefaultAcquireTokenTimeoutSeconds,
// ... more properties
};
// log the whole object for monitoring purposes
// (this is also a reason I want encapsulation)
Log.InfoFormat("Config={0}", c);
return c;
});
// use this configuration in any way necessary...
// the rest of the method concerns only the factory,
// i.e. creating the HttpClient with whatever configuration
// in my case this:
return new HttpClient(...);
// local function that enables the above expression
T Invoke<T>(Func<T> func) => func.Invoke();
}
I have succeeded in constructing an anonymous class and also encapsulated the logic of dealing with complex settings management, all inside CreateHttpClient
and within its own "expression". This might not be exactly what the OP wanted but it is a lightweight approach with anonymous types that is currently possible in modern C#.
KeyStore Explorer is an open source GUI replacement for the Java command-line utilities keytool and jarsigner. KeyStore Explorer presents their functionality, and more, via an intuitive graphical user interface.
Based on @md-nazrul-islam reply, This is what I did with SCSS:
ul.ui-autocomplete {
position: absolute;
top: 100%;
left: 0;
z-index: 1000;
float: left;
display: none;
min-width: 160px;
margin: 0 0 10px 25px;
list-style: none;
background-color: #ffffff;
border: 1px solid #ccc;
border-color: rgba(0, 0, 0, 0.2);
//@include border-radius(5px);
@include box-shadow( rgba(0, 0, 0, 0.1) 0 5px 10px );
@include background-clip(padding-box);
*border-right-width: 2px;
*border-bottom-width: 2px;
li.ui-menu-item{
padding:0 .5em;
line-height:2em;
font-size:.8em;
&.ui-state-focus{
background: #F7F7F7;
}
}
}
SSH File
~/.ssh/config file
Host *
StrictHostKeyChecking no
UserKnownHostsFile=/dev/null
LogLevel QUIET
ConnectTimeout=10
Host github.com
User git
AddKeystoAgent yes
UseKeychain yes
Identityfile ~/github_rsa
Edit reponame/.git/config
[remote "origin"]
url = [email protected]:username/repo.git
I'm a few years late to the party, but I kind of like this one-line solution I used to get rails to include everything in app/workers/concerns:
Dir[ Rails.root.join *%w(app workers concerns *) ].each{ |f| require f }
If you are using a POSIX compliant OS, you could use nftw()
for file tree traversal and remove (removes files or directories). If you are in C++ and your project uses boost, it is not a bad idea to use the Boost.Filesystem as suggested by Manuel.
In the code example below I decided not to traverse symbolic links and mount points (just to avoid a grand removal:) ):
#include <stdio.h>
#include <stdlib.h>
#include <ftw.h>
static int rmFiles(const char *pathname, const struct stat *sbuf, int type, struct FTW *ftwb)
{
if(remove(pathname) < 0)
{
perror("ERROR: remove");
return -1;
}
return 0;
}
int main(int argc, char *argv[])
{
if (argc != 2)
{
fprintf(stderr,"usage: %s path\n",argv[0]);
exit(1);
}
// Delete the directory and its contents by traversing the tree in reverse order, without crossing mount boundaries and symbolic links
if (nftw(argv[1], rmFiles,10, FTW_DEPTH|FTW_MOUNT|FTW_PHYS) < 0)
{
perror("ERROR: ntfw");
exit(1);
}
return 0;
}
ListenForClients
is getting invoked twice (on two different threads) - once from the constructor, once from the explicit method call in Main
. When two instances of the TcpListener
try to listen on the same port, you get that error.
so the .animate method works only if you have given a position attribute to an element, if not it didn't move?
for example i've seen that if i declare the div but i declare nothing in the css, it does not assume his default position and it does not move it into the page, even if i declare property margin: x w y z;
I second Wireshark. It is very powerful and versatile. And since this tool will work not only on Windows but also on Linux or Mac OSX, investing your time to learn it (quite easy actually) makes sense. Whatever the platform or the language you use, it makes sense.
Regards,
Richard Just Programmer http://sili.co.nz/blog
This is caused by the limited support for the MP4 format within the video tag in Firefox. Support was not added until Firefox 21, and it is still limited to Windows 7 and above. The main reason for the limited support revolves around the royalty fee attached to the mp4 format.
Check out Supported media formats and Media formats supported by the audio and video elements directly from the Mozilla crew or the following blog post for more information:
http://pauljacobson.org/2010/01/22/2010122firefox-and-its-limited-html-5-video-support-html/
I know this is old but I had a similar need for this and I did not want to do the find and replace version. It turns out that you can nest the substitute method like so:
=SUBSTITUTE(SUBSTITUTE(F149, "a", " AM"), "p", " PM")
In my case, I am using excel to view a DBF file and however it was populated has times like this:
9:16a
2:22p
So I just made a new column and put that formula in it to convert it to the excel time format.
Title_Authors is a look up two things join at a time project results and continue chaining
DataClasses1DataContext db = new DataClasses1DataContext();
var queryresults = from a in db.Authors
join ba in db.Title_Authors
on a.Au_ID equals ba.Au_ID into idAuthor
from c in idAuthor
join t in db.Titles
on c.ISBN equals t.ISBN
select new { Author = a.Author1,Title= t.Title1 };
foreach (var item in queryresults)
{
MessageBox.Show(item.Author);
MessageBox.Show(item.Title);
return;
}
I've experienced a problem with length of None, which leads to Internal Server Error: TypeError: object of type 'NoneType' has no len()
My workaround is just displaying 0 if object is None and calculate length of other types, like list in my case:
{{'0' if linked_contacts == None else linked_contacts|length}}
providedRuntime("org.springframework.boot:spring-boot-starter-tomcat")
This should be
compile("org.springframework.boot:spring-boot-starter-tomcat")
Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet
and inside it you will have two methods that look like
public void doPost(HttpServletRequest req, HttpServletResponse resp){
}
and
public void doGet(HttpServletRequest req, HttpServletResponse resp){
}
One of them is called to handle GET
operations and another is used to handle POST
operations. You will then use the HttpServletRequest
object to get the parameters that were passed as part of the form like so:
String name = req.getParameter("name");
Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.
Finally I did a small test and while I was programming it it came to my mind, that without the setNull(..) method there would be no way to set null values for the Java primitives. For Objects both ways
setNull(..)
and
set<ClassName>(.., null))
behave the same way.
The list method index
will return -1
if the item is not present, and will return the index of the item in the list if it is present. Alternatively in an if
statement you can do the following:
if myItem in list:
#do things
You can also check if an element is not in a list with the following if statement:
if myItem not in list:
#do things
In my case I needed the configuration stage to be blocking as a whole, but execute each role in parallel. I've tackled this issue using the following code:
echo webserver loadbalancer database | tr ' ' '\n' \
| xargs -I % -P 3 bash -c 'ansible-playbook $1.yml' -- %
the -P 3 argument in xargs makes sure that all the commands are ran in parallel, each command executes the respective playbook and the command as a whole blocks until all parts are finished.
if you are adding multiple items to the list use this:
mAdapter.notifyItemRangeInserted(startPosition, itemcount);
This notify any registered observers that the currently reflected itemCount items starting at positionStart have been newly inserted. The item previously located at positionStart and beyond can now be found starting at position positinStart+itemCount
existing item in the dataset still considered up to date.
Rebooting the PC was the only thing that worked for me. It worked when I had this problem with an Android 2.2 phone, and also an Android 3.1 tablet.
git-bash uses standard unix commands.
ls for directory listing cd for change directory
more here -> http://ss64.com/bash/ Not all of these will work, but the file based ones mostly do.
What's wrong with just simply using a single, simple UPDATE
statement??
UPDATE dbo.Coupon
SET NoofUses = (SELECT COUNT(*) FROM dbo.CouponUse WHERE Couponid = dbo.Coupon.ID)
That's all that's needed ! No messy and complicated cursor, no looping, no RBAR (row-by-agonizing-row) processing ..... just a nice, simple, clean set-based SQL statement.
Check the following example:
// First get your image
$imgPath = 'path-to-your-picture/image.jpg';
$img = base64_encode(file_get_contents($imgPath));
echo '<img width="100" height="100" src="data:image/jpg;base64,'. $img .'" />'