Variables are available only in the scope you defined them. If you define a variable inside a function, you won't be able to access it outside of it.
Define variable with var
outside the function (and of course before it) and then assign 10
to it inside function:
var value;
$(function() {
value = "10";
});
console.log(value); // 10
Note that you shouldn't omit the first line in this code (var value;
), because otherwise you are assigning value to undefined variable. This is bad coding practice and will not work in strict mode. Defining a variable (var variable;
) and assigning value to a variable (variable = value;
) are two different things. You can't assign value to variable that you haven't defined.
It might be irrelevant here, but $(function() {})
is a shortcut for $(document).ready(function() {})
, which executes a function as soon as document is loaded. If you want to execute something immediately, you don't need it, otherwise beware that if you run it before DOM has loaded, value will be undefined
until it has loaded, so console.log(value);
placed right after $(function() {})
will return undefined
. In other words, it would execute in following order:
var value;
console.log(value);
value = "10";
See also:
In general you can use Object class for any type, but you have do type casting later!
eg:-
Object object = 12;
Object object1 = "Aditya";
Object object2 = 12.12;
System.out.println(Integer.parseInt(object.toString()) + 2);
System.out.println(object1.toString() + " Kumar");
System.out.println(Double.parseDouble(object2.toString()) + 2.12);
Use:
/* @var $objs Test[] */
foreach ($objs as $obj) {
// Typehinting will occur after typing $obj->
}
when typehinting inline variables, and
class A {
/** @var Test[] */
private $items;
}
for class properties.
Previous answer from '09 when PHPDoc (and IDEs like Zend Studio and Netbeans) didn't have that option:
The best you can do is say,
foreach ($Objs as $Obj)
{
/* @var $Obj Test */
// You should be able to get hinting after the preceding line if you type $Obj->
}
I do that a lot in Zend Studio. Don't know about other editors, but it ought to work.
So, to be clear, it's a lazy coding style. I prefer native types, given the choice; I'll take that extra bit of "noise" to ensure I'm writing and reading exactly what I think I am at code/debug time. * shrug *
/var/www/html
is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf
file (usually located in /etc/apache/conf
) and changing the DocumentRoot
attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)
Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.
It's really just a coding style. The compiler generates the exact same for both variants.
See also here for the performance question:
<html>
<head>
<script type="text/javascript">
var number = 123;
var string = "abcd";
function docWrite(variable) {
document.write(variable);
}
</script>
</head>
<body>
<h1>the value for number is: <script>docWrite(number)</script></h1>
<h2>the text is: <script>docWrite(string)</script> </h2>
</body>
</html>
You can shorten document.write
but
can't avoid <script>
tag
const
' and 'let
'You should be using block scoping for every variable you create, just like most other major languages. var
is obsolete. This makes your code safer and more maintainable.
const
should be used for 95% of cases. It makes it so the variable reference can't change. Array, object, and DOM node properties can change and should likely be const
.
let
should be be used for any variable expecting to be reassigned. This includes within a for loop. If you ever change value beyond initialization, use let
.
Block scope means that the variable will only be available within the brackets in which it is declared. This extends to internal scopes, including anonymous functions created within your scope.
var
variables still have a type - and the compiler error message says this type must be established during the declaration.
The specific request (assigning an initial null value) can be done, but I don't recommend it. It doesn't provide an advantage here (as the type must still be specified) and it could be viewed as making the code less readable:
var x = (String)null;
Which is still "type inferred" and equivalent to:
String x = null;
The compiler will not accept var x = null
because it doesn't associate the null with any type - not even Object. Using the above approach, var x = (Object)null
would "work" although it is of questionable usefulness.
Generally, when I can't use var
's type inference correctly then
The second approach can be done by moving code into methods or functions.
Give this a go:
string format = "{0} / {1} / {2} {3}";
string date = string.Format(format,mon.ToString(),da.ToString(),yer.ToString();
Console.WriteLine(date);
In fact, there's probably a way to format it automatically without even doing it yourself.
Check out http://msdn.microsoft.com/en-us/library/8kb3ddd4.aspx
Variable Not Hoisting
let
will not hoist to the entire scope of the block they appear in. By contrast, var
could hoist as below.
{
console.log(cc); // undefined. Caused by hoisting
var cc = 23;
}
{
console.log(bb); // ReferenceError: bb is not defined
let bb = 23;
}
Actually, Per @Bergi, Both var
and let
are hoisted.
Garbage Collection
Block scope of let
is useful relates to closures and garbage collection to reclaim memory. Consider,
function process(data) {
//...
}
var hugeData = { .. };
process(hugeData);
var btn = document.getElementById("mybutton");
btn.addEventListener( "click", function click(evt){
//....
});
The click
handler callback does not need the hugeData
variable at all. Theoretically, after process(..)
runs, the huge data structure hugeData
could be garbage collected. However, it's possible that some JS engine will still have to keep this huge structure, since the click
function has a closure over the entire scope.
However, the block scope can make this huge data structure to garbage collected.
function process(data) {
//...
}
{ // anything declared inside this block can be garbage collected
let hugeData = { .. };
process(hugeData);
}
var btn = document.getElementById("mybutton");
btn.addEventListener( "click", function click(evt){
//....
});
let
loops
let
in the loop can re-binds it to each iteration of the loop, making sure to re-assign it the value from the end of the previous loop iteration. Consider,
// print '5' 5 times
for (var i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
However, replace var
with let
// print 1, 2, 3, 4, 5. now
for (let i = 0; i < 5; ++i) {
setTimeout(function () {
console.log(i);
}, 1000);
}
Because let
create a new lexical environment with those names for a) the initialiser expression b) each iteration (previosly to evaluating the increment expression), more details are here.
Sure, int
is easy, but when the variable's type is IEnumerable<MyStupidLongNamedGenericClass<int, string>>
, var makes things much easier.
If you want to make interactive console:
#!/usr/bin/env ruby
require "readline"
addends = []
while addend_string = Readline.readline("> ", true)
addends << addend_string.to_i
puts "#{addends.join(' + ')} = #{addends.sum}"
end
Usage (assuming you put above snippet into summator
file in current directory):
chmod +x summator
./summator
> 1
1 = 1
> 2
1 + 2 = 3
Use Ctrl + D
to exit
First check the default-jdk
package, good chance it already provide you an OpenJDK >= 11
.
ref: https://packages.ubuntu.com/search?keywords=default-jdk&searchon=names&suite=all§ion=all
So starting from Ubuntu 18.04 LTS it should be ok.
sudo apt update -qq
sudo apt install -yq default-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/default-java
mvn -version
For Ubuntu 16.04 LTS, only openjdk-8-jdk
is provided in the official repos so you need to find it in a ppa:
sudo add-apt-repository -y ppa:openjdk-r/ppa
sudo apt update -qq
sudo apt install -yq openjdk-11-jdk
note: don't forget to set JAVA_HOME
export JAVA_HOME=/usr/lib/jvm/java-11-openjdk-amd64
mvn -version
You can use 'Select' class of selenium WebDriver as posted by Maitreya. Sorry, but I'm a bit confused about, for selecting gender from drop down why to compare string with "Germany". Here is the code snippet,
Select gender = new Select(driver.findElement(By.id("gender")));
gender.selectByVisibleText("Male/Female");
Import import org.openqa.selenium.support.ui.Select;
after adding the above code.
Now gender will be selected which ever you gave ( Male/Female).
Try changing
$client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', ['trace' => true]);
to
$client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', ['trace' => true, 'cache_wsdl' => WSDL_CACHE_MEMORY]);
Also (whether that works or not), check to make sure that /tmp
is writeable by your web server and that it isn't full.
Now with ES6 we have a very powerful spread operator (...Object) which can make this job very easy. It can be done as follows:
let alerts = {
1: { app: 'helloworld', message: 'message' },
2: { app: 'helloagain', message: 'another message' }
}
//now suppose you want to add another key called alertNo. with value 2 in the alerts object.
alerts = {
...alerts,
alertNo: 2
}
Thats it. It will add the key you want. Hope this helps!!
Here are more code examples that will produce the argument null exception:
List<Myobj> myList = null;
//from this point on, any linq statement you perform on myList will throw an argument null exception
myList.ToList();
myList.GroupBy(m => m.Id);
myList.Count();
myList.Where(m => m.Id == 0);
myList.Select(m => m.Id == 0);
//etc...
You can use arguments with default values.
def someMethod(def mandatory,def optional=null){}
if argument "optional" not exist, it turns to "null".
I know this is a bit late, but I made a clean little function with a little ES6 syntax
function getHost(href){
return Object.assign(document.createElement('a'), { href }).host;
}
It could also be writen in ES5 like
function getHost(href){
return Object.assign(document.createElement('a'), { href: href }).host;
}
Of course IE doesn't support Object.assign
, but in my line of work, that doesn't matter.
Correct me if I'm wrong but what you're getting at is that with strings, "Hi" == "Hi" doesn't always come out true (because they're not necessarily the same object).
The reason you're getting an answer of 1 though is because the JVM will reuse strings objects where possible. In this case the JVM is reusing the string object, and thus overwriting the item in the Hashmap/Hashset.
But you aren't guaranteed this behavior (because it could be a different string object that has the same value "Hi"). The behavior you see is just because of the JVM's optimization.
If you are trying to do something very similar: a is not None
, the same issue comes up. That is, Numpy complains that one must use a.any
or a.all
.
A workaround is to do:
if not (a is None):
pass
Not too pretty, but it does the job.
The following is a decent solution across Unix/Linux installations, that does not rely on any unusual program features. This supports a multi-line message body, multiple attachments, and all the other typical features of mailx
.
Unfortunately, it does not fit on a single line.
#!/bin/ksh
# Get the date stamp for temporary files
DT_STAMP=`date +'%C%y%m%d%H%M%S'`
# Create a multi-line body
echo "here you put the message body
which can be split across multiple lines!
woohoo!
" > body-${DT_STAMP}.mail
# Add several attachments
uuencode File1.pdf File1.pdf > attachments-${DT_STAMP}.mail
uuencode File2.pdf File2.pdf >> attachments-${DT_STAMP}.mail
# Put everything together and send it off!
cat body-${DT_STAMP}.mail attachments-${DT_STAMP}.mail > out-${DT_STAMP}.mail
mailx -s "here you put the message subject" [email protected] < out-${DT_STAMP}.mail
# Clean up temporary files
rm body-${DT_STAMP}.mail
rm attachments-${DT_STAMP}.mail
rm out-${DT_STAMP}.mail
Overview of the services used by all sessions provides the distionary view v$session
(or gv$session
for RAC databases) in the column SERVICE_NAME
.
To limit the information to the connected session use the SID from the view V$MYSTAT
:
select SERVICE_NAME from gv$session where sid in (
select sid from V$MYSTAT)
If the name is SYS$USERS
the session is connected to a default service, i.e. in the connection string no explicit service_name was specified.
To see what services are available in the database use following queries:
select name from V$SERVICES;
select name from V$ACTIVE_SERVICES;
I don't have much experience with Flexbox
but it seems to me that the forced height on the html
and body
tags cause the text to disappear on top when resized-- I wasn't able to test in IE but I found the same effect in Chrome.
I forked your fiddle and removed the height
and width
declarations.
body
{
margin: 0;
}
It also seemed like the flex
settings must be applied to other flex
elements. However, applying display: flex
to the .inner
caused issues so I explicitly set the .inner
to display: block
and set the .outer
to flex
for positioning.
I set the minimum .outer
height to fill the viewport, the display: flex
, and set the horizontal and vertical alignment:
.outer
{
display:flex;
min-height: 100%;
min-height: 100vh;
align-items: center;
justify-content: center;
}
I set .inner
to display: block
explicitly. In Chrome, it looked like it inherited flex
from .outer
. I also set the width:
.inner
{
display:block;
width: 80%;
}
This fixed the issue in Chrome, hopefully it might do the same in IE11. Here's my version of the fiddle: http://jsfiddle.net/ToddT/5CxAy/21/
One other way, using the splat operator:
*a, last = [1, 3, 4, 5]
STDOUT:
a: [1, 3, 4]
last: 5
If you want an ImageView
that both scales up and down while keeping the proper aspect ratio, add this to your XML:
android:adjustViewBounds="true"
android:scaleType="fitCenter"
Add this to your code:
// We need to adjust the height if the width of the bitmap is
// smaller than the view width, otherwise the image will be boxed.
final double viewWidthToBitmapWidthRatio = (double)image.getWidth() / (double)bitmap.getWidth();
image.getLayoutParams().height = (int) (bitmap.getHeight() * viewWidthToBitmapWidthRatio);
It took me a while to get this working, but this appears to work in the cases both where the image is smaller than the screen width and larger than the screen width, and it does not box the image.
Check if your project is opened as a Maven project and not just a regular Java project. Actually a no-brainer, but that is exactly the same reason why you might miss it.
Taking it further you could even parse on the fly
e.g.
& "my.exe" | %{
if ($_ -match 'OK')
{ Write-Host $_ -f Green }
else if ($_ -match 'FAIL|ERROR')
{ Write-Host $_ -f Red }
else
{ Write-Host $_ }
}
As always the best solution is to use recursion:
loop(document);
function loop(node){
// do some thing with the node here
var nodes = node.childNodes;
for (var i = 0; i <nodes.length; i++){
if(!nodes[i]){
continue;
}
if(nodes[i].childNodes.length > 0){
loop(nodes[i]);
}
}
}
Unlike other suggestions, this solution does not require you to create an array for all the nodes, so its more light on the memory. More importantly, it finds more results. I am not sure what those results are, but when testing on chrome it finds about 50% more nodes compared to document.getElementsByTagName("*");
I have use this method
function getString()
{
var vars = [], hash;
var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
for(var i = 0; i < hashes.length; i++)
{
hash = hashes[i].split('=');
vars.push(hash[0]);
vars[hash[0]] = hash[1];
}
return vars;
}
var buisnessArea = getString();
Thankyou Frank.i got the idea. Here is the working code.
Option Explicit
Private Sub CommandButton1_Click()
Dim directory As String, fileName As String, sheet As Worksheet, total As Integer
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
.Title = "Please select the file."
.Filters.Clear
.Filters.Add "Excel 2003", "*.xls?"
If .Show = True Then
fileName = Dir(.SelectedItems(1))
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Workbooks.Open (fileName)
For Each sheet In Workbooks(fileName).Worksheets
total = Workbooks("import-sheets.xlsm").Worksheets.Count
Workbooks(fileName).Worksheets(sheet.Name).Copy _
after:=Workbooks("import-sheets.xlsm").Worksheets(total)
Next sheet
Workbooks(fileName).Close
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
You open the variable "file" as a read only then attempt to write to it:
file = open('ValidEmails.txt','r')
Instead, use the 'w' flag.
file = open('ValidEmails.txt','w')
...
file.write(email)
If you are using SQL Server 2005 (or greater) you might want to consider switching to NVARCHAR(MAX) in your table definition; TEXT, NTEXT, and IMAGE data types of SQL Server 2000 will be deprecated in future versions of SQL Server. SQL Server 2005 provides backward compatibility to data types, but you should probably be using VARCHAR(MAX), NVARCHAR(MAX), and VARBINARY(MAX) instead.
Use the return
keyword to exit from a method.
public void someMethod() {
//... a bunch of code ...
if (someCondition()) {
return;
}
//... otherwise do the following...
}
From the Java Tutorial that I linked to above:
Any method declared void doesn't return a value. It does not need to contain a return statement, but it may do so. In such a case, a return statement can be used to branch out of a control flow block and exit the method and is simply used like this:
return;
I think it's better to use the Microsoft.VisualBasic.FileIO.TextFieldParser Class if you're working with comma separated values text files.
First install your targeted version
npm i [email protected] --save-dev --save-exact
Then before compiling do
npm i
I have the same problem, in build.gradle (Module:app) add the following line of code inside dependencies:
dependencies
{
...
compile 'com.android.support:support-annotations:27.1.1'
}
It worked for me perfectly
F9 executes only one statement. By default Toad will try to execute the statement wherever your cursor is or treat all the highlighted text as a statement and try to execute that. A ;
is not necessary in this case.
F5 is "Execute as Script" which means that Toad will take either the complete highlighted text (or everything in your editor if nothing is highlighted) containing more than one statement and execute it like it was a script in SQL*Plus. So, in this case every statement must be followed by a ;
and sometimes (in PL/SQL cases) ended with a /
.
In general, it's easiest to parse such typical config files in two stages: first read the lines, and then parse those one by one.
In C++, lines can be read from a stream using std::getline()
. While by default it will read up to the next '\n'
(which it will consume, but not return), you can pass it some other delimiter, too, which makes it a good candidate for reading up-to-some-char, like =
in your example.
For simplicity, the following presumes that the =
are not surrounded by whitespace. If you want to allow whitespaces at these positions, you will have to strategically place is >> std::ws
before reading the value and remove trailing whitespaces from the keys. However, IMO the little added flexibility in the syntax is not worth the hassle for a config file reader.
const char config[] = "url=http://example.com\n"
"file=main.exe\n"
"true=0";
std::istringstream is_file(config);
std::string line;
while( std::getline(is_file, line) )
{
std::istringstream is_line(line);
std::string key;
if( std::getline(is_line, key, '=') )
{
std::string value;
if( std::getline(is_line, value) )
store_line(key, value);
}
}
(Adding error handling is left as an exercise to the reader.)
Here is the jsFiddle
#backdrop{
border: 2px solid red;
width: 400px;
height: 200px;
position: absolute;
}
#curtain {
border: 1px solid blue;
width: 400px;
height: 200px;
position: absolute;
}
Use Z-index to move the one you want on top.
if your php version is Non-Thread-Safe (nts) you must use php extension with format example: extension=php_cl_dbg_5_2_nts.dll else if your php version is Thread-Safe (ts) you must use php extension with format example: extension=php_cl_dbg_5_2_ts.dll (notice bolded words)
So if get error like above. Firstly, check your PHP version is nts or ts, if is nts.
Then check in php.ini whether has any line like zend_extension_ts="C:\xammp\php\ext\php_dbg.dll-5.2.x" choose right version of php_dbg.dll-5.2.x from it homepage (google for it).
Change from zend_extension_ts to zend_extension_nts.
Hope this help.
By default, html buttons submit a form.
This is due to the fact that even buttons located outside of a form act as submitters (see the W3Schools website: http://www.w3schools.com/tags/att_button_form.asp)
In other words, the button type is "submit" by default
<button type="submit">Button Text</button>
Therefore an easy way to get around this is to use the button type.
<button type="button">Button Text</button>
Other options include returning false at the end of the onclick or any other handler for when the button is clicked, or to using an < input> tag instead
To find out more, check out the Mozilla Developer Network's information on buttons: https://developer.mozilla.org/en/docs/Web/HTML/Element/button
UPDATE: Following your comment, it is not currently possible to change the default registry, see this issue for more info.
You should be able to do this, substituting the host and port to your own:
docker pull localhost:5000/registry-demo
If the server is remote/has auth you may need to log into the server with:
docker login https://<YOUR-DOMAIN>:8080
Then running:
docker pull <YOUR-DOMAIN>:8080/test-image
This thread is a bit older, but thought I'd post what I currently do (work in progress).
Though I'm still hitting situations where the system is under heavy load and when I click a submit button (e.g., login.jsp), all three conditions (see below) return true
but the next page (e.g., home.jsp) hasn't started loading yet.
This is a generic wait method that takes a list of ExpectedConditions.
public boolean waitForPageLoad(int waitTimeInSec, ExpectedCondition<Boolean>... conditions) {
boolean isLoaded = false;
Wait<WebDriver> wait = new FluentWait<>(driver)
.withTimeout(waitTimeInSec, TimeUnit.SECONDS)
.ignoring(StaleElementReferenceException.class)
.pollingEvery(2, TimeUnit.SECONDS);
for (ExpectedCondition<Boolean> condition : conditions) {
isLoaded = wait.until(condition);
if (isLoaded == false) {
//Stop checking on first condition returning false.
break;
}
}
return isLoaded;
}
I have defined various reusable ExpectedConditions (three are below). In this example, the three expected conditions include document.readyState = 'complete', no "wait_dialog" present, and no 'spinners' (elements indicating async data is being requested).
Only the first one can be generically applied to all web pages.
/**
* Returns 'true' if the value of the 'window.document.readyState' via
* JavaScript is 'complete'
*/
public static final ExpectedCondition<Boolean> EXPECT_DOC_READY_STATE = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
String script = "if (typeof window != 'undefined' && window.document) { return window.document.readyState; } else { return 'notready'; }";
Boolean result;
try {
result = ((JavascriptExecutor) driver).executeScript(script).equals("complete");
} catch (Exception ex) {
result = Boolean.FALSE;
}
return result;
}
};
/**
* Returns 'true' if there is no 'wait_dialog' element present on the page.
*/
public static final ExpectedCondition<Boolean> EXPECT_NOT_WAITING = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
Boolean loaded = true;
try {
WebElement wait = driver.findElement(By.id("F"));
if (wait.isDisplayed()) {
loaded = false;
}
} catch (StaleElementReferenceException serex) {
loaded = false;
} catch (NoSuchElementException nseex) {
loaded = true;
} catch (Exception ex) {
loaded = false;
System.out.println("EXPECTED_NOT_WAITING: UNEXPECTED EXCEPTION: " + ex.getMessage());
}
return loaded;
}
};
/**
* Returns true if there are no elements with the 'spinner' class name.
*/
public static final ExpectedCondition<Boolean> EXPECT_NO_SPINNERS = new ExpectedCondition<Boolean>() {
@Override
public Boolean apply(WebDriver driver) {
Boolean loaded = true;
try {
List<WebElement> spinners = driver.findElements(By.className("spinner"));
for (WebElement spinner : spinners) {
if (spinner.isDisplayed()) {
loaded = false;
break;
}
}
}catch (Exception ex) {
loaded = false;
}
return loaded;
}
};
Depending on the page, I may use one or all of them:
waitForPageLoad(timeoutInSec,
EXPECT_DOC_READY_STATE,
EXPECT_NOT_WAITING,
EXPECT_NO_SPINNERS
);
There are also predefined ExpectedConditions in the following class: org.openqa.selenium.support.ui.ExpectedConditions
@JSideris, sample code for getting insertedId.
db.collection(COLLECTION).insertOne(data, (err, result) => {
if (err)
return err;
else
return result.insertedId;
});
You can use this function that gets promiseFactories List:
function executeSequentially(promiseFactories) {
var result = Promise.resolve();
promiseFactories.forEach(function (promiseFactory) {
result = result.then(promiseFactory);
});
return result;
}
Promise Factory is just simple function that returns a Promise:
function myPromiseFactory() {
return somethingThatCreatesAPromise();
}
It works because a promise factory doesn't create the promise until it's asked to. It works the same way as a then function – in fact, it's the same thing!
You don't want to operate over an array of promises at all. Per the Promise spec, as soon as a promise is created, it begins executing. So what you really want is an array of promise factories...
If you want to learn more on Promises, you should check this link: https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html
To be Honest All Are good but it will be easy if or more efficient if someone use n time numbers and show them in out put.so prefer this will be a good option. Do not predefined array variable let user define and show the result. Like this..
int main()
{
int i,j,n,t;
int arry[100];
scanf("%d",&n);
for (i=0;i<n;i++)
{ scanf("%d",&t);
arry[i]=t;
}
for(j=0;j<n;j++)
printf("%d",arry[j]);
return 0;
}
The enum (abbreviation of enumeration) is used to enumerate a set of values (enumerators). A value is an abstract thing represented by a symbol (a word). For example, a basic enum could be
enum { xs,s,m,l,xl,xxl,xxxl,xxxxl };
This enum is called anonymous because you do not have a symbol to name it. But it is still perfectly correct. Just use it like this
enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;
Ok. The life is beautiful and everything goes well. But one day you need to reuse this enum to define a new variable to store myGrandFatherPantSize, then you write:
enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;
enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandFatherPantSize;
But then you have a compiler error "redefinition of enumerator". Actually, the problem is that the compiler is not sure that you first enum and you are second describe the same thing.
Then if you want to reuse the same set of enumerators (here xs...xxxxl) in several places you must tag it with a unique name. The second time you use this set you just have to use the tag. But don't forget that this tag does not replace the enum word but just the set of enumerators. Then take care to use enum as usual. Like this:
// Here the first use of my enum
enum sizes { xs,s,m,l,xl,xxl,xxxl,xxxxl } myGrandMotherDressSize;
// here the second use of my enum. It works now!
enum sizes myGrandFatherPantSize;
you can use it in a parameter definition as well:
// Observe that here, I still use the enum
- (void) buyANewDressToMyGrandMother:(enum sizes)theSize;
You could say that rewriting enum everywhere is not convenient and makes the code looks a bit strange. You are right. A real type would be better.
This is the final step of our great progression to the summit. By just adding a typedef let's transform our enum in a real type. Oh the last thing, typedef is not allowed within your class. Then define your type just above. Do it like this:
// enum definition
enum sizes { xs,s,m,l,xl,xxl,xxxl,xxxxl };
typedef enum sizes size_type
@interface myClass {
...
size_type myGrandMotherDressSize, myGrandFatherPantSize;
...
}
Remember that the tag is optional. Then since here, in that case, we do not tag the enumerators but just to define a new type. Then we don't really need it anymore.
// enum definition
typedef enum { xs,s,m,l,xl,xxl,xxxl,xxxxl } size_type;
@interface myClass : NSObject {
...
size_type myGrandMotherDressSize, myGrandFatherPantSize;
...
}
@end
If you are developing in Objective-C with XCode I let you discover some nice macros prefixed with NS_ENUM. That should help you to define good enums easily and moreover will help the static analyzer to do some interesting checks for you before to compile.
Good Enum!
Just start from there that in CSS, if you repeat 2 values or more, always last one gets applied, unless using !important
tag, but at the same time avoid using !important
as much as you can, so in your case that's the problem, so the second transform override the first one in this case...
So how you can do what you want then?...
Don't worry, transform accepts multiple values at the same time... So this code below will work:
li:nth-child(2) {
transform: rotate(15deg) translate(-20px, 0px); //multiple
}
If you like to play around with transform run the iframe from MDN below:
<iframe src="https://interactive-examples.mdn.mozilla.net/pages/css/transform.html" class="interactive " width="100%" frameborder="0" height="250"></iframe>
_x000D_
Look at the link below for more info:
<audio src="/music/good_enough.mp3" autoplay>
<p>If you are reading this, it is because your browser does not support the audio element. </p>
<embed src="/music/good_enough.mp3" width="180" height="90" hidden="true" />
</audio>
Works for me just fine.
When you need to toggle an element away, and you don't need to animate the margin property. You could try margin-top: -999999em
. Just don't transition all.
I got this problem on freeBSD. It seems lapack packages are missing, I solved it installing them (as root) with:
pkg install lapack
pkg install atlas-devel #not sure this is needed, but just in case
I imagine it could work on other system too using the appropriate package installer (e.g. apt-get)
In my case, boolean values in my Python dict were the problem. JSON boolean values are in lowercase ("true", "false") whereas in Python they are in Uppercase ("True", "False"). Couldn't find this solution anywhere online but hope it helps.
One Google search later we've learned that you can set the entire plotting device background color as Owen indicates. If you just want the plotting region altered, you have to do something like what is outlined in that R-Help thread:
plot(df)
rect(par("usr")[1],par("usr")[3],par("usr")[2],par("usr")[4],col = "gray")
points(df)
The barplot
function has an add
parameter that you'll likely need to use.
Maybe this will help someone. I was using a nested app. project.appname and I actually had project and project.appname in INSTALLED_APPS. Removing project from INSTALLED_APPS allowed the changes to be detected.
Answers above describe well why and how it is used on twitter and facebook, what I missed is explanation what #
does by default...
On a 'normal' (not a single page application) you can do anchoring with hash
to any element that has id by placing that elements id in url after hash #
Example:
(on Chrome) Click F12 or Rihgt Mouse and Inspect element
then take id="answer-10831233"
and add to url like following
https://stackoverflow.com/questions/3009380/whats-the-shebang-hashbang-in-facebook-and-new-twitter-urls-for#answer-10831233
and you will get a link that jumps to that element on the page
What's the shebang/hashbang (#!) in Facebook and new Twitter URLs for?
By using #
in a way described in the answers above you are introducing conflicting behaviour... although I wouldn't loose sleep over it... since Angular it became somewhat of a standard....
For me, just setting the compatibility level to higher level works fine. To see C.Level :
select compatibility_level from sys.databases where name = [your_database]
To remove migration (if you already migrated the migration)
rake db:migrate:down VERSION="20130417185845" #Your migration version
To remove Model
rails d model name #name => Your model name
You will have to do this via AJAX. I HEAVILY reccommend you use jQuery to make this easier for you....
$("#idOfElement").on('click', function(){
$.ajax({
url: 'pathToPhpFile.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
)};
Most explanations miss one important step, let's fill the gap using another example.
Given the following:
Dividend: 16
Divisor: 6
The modulus function looks like this:
16 % 6 = 4
Let's determine why this is.
First, perform integer division, which is similar to normal division, except any fractional number (a.k.a. remainder) is discarded:
16 / 6 = 2
Then, multiply the result of the above division (2
) with our divisor (6
):
2 * 6 = 12
Finally, subtract the result of the above multiplication (12
) from our dividend (16
):
16 - 12 = 4
The result of this subtraction, 4
, the remainder, is the same result of our modulus above!
More answers, along with timings in the answer to this question: What is the most efficient way to cast a list as a data frame?
The quickest way, that doesn't produce a dataframe with lists rather than vectors for columns appears to be (from Martin Morgan's answer):
l <- list(list(col1="a",col2=1),list(col1="b",col2=2))
f = function(x) function(i) unlist(lapply(x, `[[`, i), use.names=FALSE)
as.data.frame(Map(f(l), names(l[[1]])))
Returning the new object fits with the REST principle of "Uniform Interface - Manipulation of resources through representations." The complete object is the representation of the new state of the object that was created.
There is a really excellent reference for API design, here: Best Practices for Designing a Pragmatic RESTful API
It includes an answer to your question here: Updates & creation should return a resource representation
It says:
To prevent an API consumer from having to hit the API again for an updated representation, have the API return the updated (or created) representation as part of the response.
Seems nicely pragmatic to me and it fits in with that REST principle I mentioned above.
Based on other answers, for linux
and mac
you can run the following:
echo "export PATH=\"`python3 -m site --user-base`/bin:$PATH\"" >> ~/.bashrc
source ~/.bashrc
instead of python3
you can use any other link to python version: python
, python2.7
, python3.6
, python3.9
, etc.
In order to know where the user packages are installed in the current OS (win, mac, linux), we run:
python3 -m site --user-base
We know that the scripts go to the bin/
folder where the packages are installed.
So we concatenate the paths:
echo `python3 -m site --user-base`/bin
Then we export that to an environment variable.
export PATH=\"`python3 -m site --user-base`/bin:$PATH\"
Finally, in order to avoid repeating the export command we add it to our .bashrc
file and we run source
to run the new changes, giving us the suggested solution mentioned at the beginning.
Watch out the react lifecycle methods!
I worked for several hours to find out that getDerivedStateFromProps
will be called after every setState()
.
You can use map lambda
a = [2,3,4]
b = [5,6,7]
c = map(lambda x,y:(x,y),a,b)
This will also work if there lengths of original lists do not match
public class Form1 : Form
{
public Form1()
{
InitializeComponents(); // or whatever that method is called :)
this.button.Click += new RoutedEventHandler(buttonClick);
}
private void buttonClick(object sender, EventArgs e)
{
this.Close();
}
}
Not sure about solutions but a temporary workaround is to ask eslint to ignore it by adding the following on top of the problem line.
// eslint-disable-next-line @typescript-eslint/no-unused-expressions
In recent versions of jQuery, setting "dataType" to an appropriate value also sets the accepts header. For instance, dataType: "json"
sets the accept header to Accept: application/json, text/javascript, */*; q=0.01
.
Additional Version of PHP can be installed directly from the APP (using MAMP PRO v5 at least).
Here's how (All Steps):
MAMP PRO --> Preferences --> click [Check Now] to check for updates (even if you have automatic updates enabled!) --> click [Show PHP Versions] --> Install as needed!
Step-by-step screenshots:
I was playing around with this solution to maintain consistency throughout the app:
def bootstrap_django_fields(field_klass, css_class):
class Wrapper(field_klass):
def __init__(self, **kwargs):
super().__init__(**kwargs)
def widget_attrs(self, widget):
attrs = super().widget_attrs(widget)
if not widget.is_hidden:
attrs["class"] = css_class
return attrs
return Wrapper
MyAppCharField = bootstrap_django_fields(forms.CharField, "form-control")
Then you don't have to define your css classes on a form by form basis, just use your custom form field.
It's also technically possible to redefine Django's forms
classes on startup like so:
forms.CharField = bootstrap_django_fields(forms.CharField, "form-control")
Then you could set the styling globally even for apps not in your direct control. This seems pretty sketchy, so I am not sure if I can recommend this.
Let's suppose these values for common_id:
Common - 1
Table1 - 2
Table2 - 3, null
We want the row in Common to return, because it doesn't exist in any of the other tables. However, the null throws in a monkey wrench.
With those values, the query is equivalent to:
select *
from Common
where 1 not in (2)
and 1 not in (3, null)
That is equivalent to:
select *
from Common
where not (1=2)
and not (1=3 or 1=null)
This is where the problem starts. When comparing with a null, the answer is unknown. So the query reduces to
select *
from Common
where not (false)
and not (false or unkown)
false or unknown is unknown:
select *
from Common
where true
and not (unknown)
true and not unkown is also unkown:
select *
from Common
where unknown
The where condition does not return records where the result is unkown, so we get no records back.
One way to deal with this is to use the exists operator rather than in. Exists never returns unkown because it operates on rows rather than columns. (A row either exists or it doesn't; none of this null ambiguity at the row level!)
select *
from Common
where not exists (select common_id from Table1 where common_id = Common.common_id)
and not exists (select common_id from Table2 where common_id = Common.common_id)
If it's raising a KeyError with no message, then it won't print anything. If you do...
try:
connection = manager.connect("I2Cx")
except Exception as e:
print repr(e)
...you'll at least get the exception class name.
A better alternative is to use multiple except
blocks, and only 'catch' the exceptions you intend to handle...
try:
connection = manager.connect("I2Cx")
except KeyError as e:
print 'I got a KeyError - reason "%s"' % str(e)
except IndexError as e:
print 'I got an IndexError - reason "%s"' % str(e)
There are valid reasons to catch all exceptions, but you should almost always re-raise them if you do...
try:
connection = manager.connect("I2Cx")
except KeyError as e:
print 'I got a KeyError - reason "%s"' % str(e)
except:
print 'I got another exception, but I should re-raise'
raise
...because you probably don't want to handle KeyboardInterrupt
if the user presses CTRL-C, nor SystemExit
if the try
-block calls sys.exit()
.
As an extend to @Eugene's answer another version which will work to push code from local repo to master/develop branch .
Switch to branch ‘master’:
$ git checkout master
Merge from local repo to master:
$ git merge --no-ff FEATURE/<branch_Name>
Push to master:
$ git push
The best way is probably to use the list method .index.
For the objects in the list, you can do something like:
def __eq__(self, other):
return self.Value == other.Value
with any special processing you need.
You can also use a for/in statement with enumerate(arr)
Example of finding the index of an item that has value > 100.
for index, item in enumerate(arr):
if item > 100:
return index, item
I personally find it easier use MySQL event scheduler than cron.
Enable it with
SET GLOBAL event_scheduler = ON;
and create an event like this:
CREATE EVENT name_of_event
ON SCHEDULE EVERY 1 DAY
STARTS '2014-01-18 00:00:00'
DO
DELETE FROM tbl_message WHERE DATEDIFF( NOW( ) , timestamp ) >=7;
and that's it.
Read more about the syntax here and here is more general information about it.
For static queries, like the one in your question, table names and column names need to be static.
For dynamic queries, you should generate the full SQL dynamically, and use sp_executesql to execute it.
Here is an example of a script used to compare data between the same tables of different databases:
Static query:
SELECT * FROM [DB_ONE].[dbo].[ACTY]
EXCEPT
SELECT * FROM [DB_TWO].[dbo].[ACTY]
Since I want to easily change the name of table
and schema
, I have created this dynamic query:
declare @schema varchar(50)
declare @table varchar(50)
declare @query nvarchar(500)
set @schema = 'dbo'
set @table = 'ACTY'
set @query = 'SELECT * FROM [DB_ONE].[' + @schema + '].[' + @table + '] EXCEPT SELECT * FROM [DB_TWO].[' + @schema + '].[' + @table + ']'
EXEC sp_executesql @query
Since dynamic queries have many details that need to be considered and they are hard to maintain, I recommend that you read: The curse and blessings of dynamic SQL
Font Squirrel has a wonderful web font generator.
I think you should find what you need here to generate OTF fonts and the needed CSS to use them. It will even support older IE versions.
Kos's answer is almost right, but can have damaging side effects. This is more correct:
#myTable tr td:nth-child(1), #myTable th:nth-child(1) {
display: none;
}
CSS (Cascading Style Sheets) will cascade attributes to all of its children. This means that *:nth-child(1)
will hide the first td
of each tr
AND hide the first element of all td
children. If any of your td
have things like buttons, icons, inputs, or selects, the first one will be hidden (woops!).
Even if you don't currently have things that will be hidden, image your frustration down the road if you need to add one. Don't punish your future self like that, that's going to be a pain to debug!
My answer will only hide the first td
and th
on all tr
in #myTable
keeping your other elements safe.
There are a lot of helpful solutions out there, but there is no simplified way with extension. Here is the code to solve the issue with an extension:
extension UIImage {
var getWidth: CGFloat {
get {
let width = self.size.width
return width
}
}
var getHeight: CGFloat {
get {
let height = self.size.height
return height
}
}
}
To make more than one element fade in/out sequentially such as 5 elements fade each 4s,
1- make unique animation for each element with animation-duration
equal to [ 4s (duration for each element) * 5 (number of elements) ] = 20s
animation-name: anim1 , anim2, anim3 ...
animation-duration : 20s, 20s, 20s ...
2- get animation keyframe for each element.
100% (keyframes percentage) / 5 (elements) = 20% (frame for each element)
3- define starting and ending point for each animation:
each animation has 20% frame length and @keyframes percentage always starts from 0%, so first animation will start from 0% and end in his frame(20%), and each next animation will starts from previous animation ending point and end when it reach his frame (+20% ),
@keyframes animation1 { 0% {}, 20% {}}
@keyframes animation2 { 20% {}, 40% {}}
@keyframes animation3 { 40% {}, 60% {}}
and so on
now we need to make each animation fade in from 0 to 1 opacity and fade out from 1 to 0,
so we will add another 2 points (steps) for each animation after starting and before ending point to handle the full opacity(1)
http://codepen.io/El-Oz/pen/WwPPZQ
.slide1 {
animation: fadeInOut1 24s ease reverse forwards infinite
}
.slide2 {
animation: fadeInOut2 24s ease reverse forwards infinite
}
.slide3 {
animation: fadeInOut3 24s ease reverse forwards infinite
}
.slide4 {
animation: fadeInOut4 24s ease reverse forwards infinite
}
.slide5 {
animation: fadeInOut5 24s ease reverse forwards infinite
}
.slide6 {
animation: fadeInOut6 24s ease reverse forwards infinite
}
@keyframes fadeInOut1 {
0% { opacity: 0 }
1% { opacity: 1 }
14% {opacity: 1 }
16% { opacity: 0 }
}
@keyframes fadeInOut2 {
0% { opacity: 0 }
14% {opacity: 0 }
16% { opacity: 1 }
30% { opacity: 1 }
33% { opacity: 0 }
}
@keyframes fadeInOut3 {
0% { opacity: 0 }
30% {opacity: 0 }
33% {opacity: 1 }
46% { opacity: 1 }
48% { opacity: 0 }
}
@keyframes fadeInOut4 {
0% { opacity: 0 }
46% { opacity: 0 }
48% { opacity: 1 }
64% { opacity: 1 }
65% { opacity: 0 }
}
@keyframes fadeInOut5 {
0% { opacity: 0 }
64% { opacity: 0 }
66% { opacity: 1 }
80% { opacity: 1 }
83% { opacity: 0 }
}
@keyframes fadeInOut6 {
80% { opacity: 0 }
83% { opacity: 1 }
99% { opacity: 1 }
100% { opacity: 0 }
}
With Winforms you can use Form.BackColor to do this.
From within the Form's code:
BackColor = Color.LightPink;
If you mean a WPF Window you can use the Background property.
From within the Window's code:
Background = Brushes.LightPink;
You can use CSS Flexbox instead another display value, The Flexbox Layout (Flexible Box) module aims at providing a more efficient way to lay out, align and distribute space among items in a container, even when their size is unknown and/or dynamic.
Example
/* CONTAINER */
#wrapper
{
width:300px;
height:300px;
display: -webkit-box; /* OLD - iOS 6-, Safari 3.1-6 */
display: -moz-box; /* OLD - Firefox 19- (buggy but mostly works) */
display: -ms-flexbox; /* TWEENER - IE 10 */
display: -webkit-flex; /* NEW - Chrome */
display: flex; /* NEW, Spec - Opera 12.1, Firefox 20+ */
-ms-flex-direction: column;
-moz-flex-direction: column;
-webkit-flex-direction: column;
flex-direction: column;
}
/* SOME ITEM CHILD ELEMENTS */
#first
{
width:300px;
height: 200px;
background-color:#F5DEB3;
}
#second
{
width:300px;
background-color: #9ACD32;
-webkit-box-flex: 1; /* OLD - iOS 6-, Safari 3.1-6 */
-moz-box-flex: 1; /* OLD - Firefox 19- */
-webkit-flex: 1; /* Chrome */
-ms-flex: 1; /* IE 10 */
flex: 1; /* NEW, */
}
If you want to have full support for old browsers like IE9 or below, you will have to use a polyfills like flexy, this polyfill enable support for Flexbox model but only for 2012 spec of flexbox model.
Recently I found another polyfill to help you with Internet Explorer 8 & 9 or any older browser that not have support for flexbox model, I still have not tried it but I leave the link here
You can find a usefull and complete Guide to Flexbox model by Chris Coyer here
You can pass the format in to the ToString
method, e.g.:
myFloatVariable.ToString("0.00"); //2dp Number
myFloatVariable.ToString("n2"); // 2dp Number
myFloatVariable.ToString("c2"); // 2dp currency
int myArray[10][10][10];
should be
int myArray[10][10][10][10];
hi just to come back at the question. If you want to sort the List of this sequence "1" "10" "100" "200" "2" "20" "3" "30" "300" and get the sorted items in this form 1;2;3;10;20;30;100;200;300 you can use this:
public class OrderingAscending : IComparer<String>
{
public int Compare(String x, String y)
{
Int32.TryParse(x, out var xtmp);
Int32.TryParse(y, out var ytmp);
int comparedItem = xtmp.CompareTo(ytmp);
return comparedItem;
}
}
and you can use it in code behind in this form:
IComparer<String> comparerHandle = new OrderingAscending();
yourList.Sort(comparerHandle);
int i = 0; // Counter used to determine when you're at the 3rd gun
for (Gun g : gunList) { // For each gun in your list
System.out.println(g); // Print out the gun
if (i == 2) { // If you're at the third gun
ArrayList<Bullet> bullets = g.getBullet(); // Get the list of bullets in the gun
for (Bullet b : bullets) { // Then print every bullet
System.out.println(b);
}
i++; // Don't forget to increment your counter so you know you're at the next gun
}
isin()
is ideal if you have a list of exact matches, but if you have a list of partial matches or substrings to look for, you can filter using the str.contains
method and regular expressions.
For example, if we want to return a DataFrame where all of the stock IDs which begin with '600'
and then are followed by any three digits:
>>> rpt[rpt['STK_ID'].str.contains(r'^600[0-9]{3}$')] # ^ means start of string
... STK_ID ... # [0-9]{3} means any three digits
... '600809' ... # $ means end of string
... '600141' ...
... '600329' ...
... ... ...
Suppose now we have a list of strings which we want the values in 'STK_ID'
to end with, e.g.
endstrings = ['01$', '02$', '05$']
We can join these strings with the regex 'or' character |
and pass the string to str.contains
to filter the DataFrame:
>>> rpt[rpt['STK_ID'].str.contains('|'.join(endstrings)]
... STK_ID ...
... '155905' ...
... '633101' ...
... '210302' ...
... ... ...
Finally, contains
can ignore case (by setting case=False
), allowing you to be more general when specifying the strings you want to match.
For example,
str.contains('pandas', case=False)
would match PANDAS
, PanDAs
, paNdAs123
, and so on.
$the_date_time = new DateTime($date_string);
$the_date_time_in_ms = ($the_date_time->format('U') * 1000) +
($the_date_time->format('u') / 1000);
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, 1);
ABOVE CODE TO SELECT IMAGE FROM GALLERY
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1)
if (resultCode == Activity.RESULT_OK) {
Uri selectedImage = data.getData();
String filePath = getPath(selectedImage);
String file_extn = filePath.substring(filePath.lastIndexOf(".") + 1);
image_name_tv.setText(filePath);
try {
if (file_extn.equals("img") || file_extn.equals("jpg") || file_extn.equals("jpeg") || file_extn.equals("gif") || file_extn.equals("png")) {
//FINE
} else {
//NOT IN REQUIRED FORMAT
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
public String getPath(Uri uri) {
String[] projection = {MediaColumns.DATA};
Cursor cursor = managedQuery(uri, projection, null, null, null);
column_index = cursor
.getColumnIndexOrThrow(MediaColumns.DATA);
cursor.moveToFirst();
imagePath = cursor.getString(column_index);
return cursor.getString(column_index);
}
NOW POST THE DATA USING MULTIPART FORM DATA
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("LINK TO SERVER");
Multipart FORM DATA
MultipartEntity mpEntity = new MultipartEntity(HttpMultipartMode.BROWSER_COMPATIBLE);
if (filePath != null) {
File file = new File(filePath);
Log.d("EDIT USER PROFILE", "UPLOAD: file length = " + file.length());
Log.d("EDIT USER PROFILE", "UPLOAD: file exist = " + file.exists());
mpEntity.addPart("avatar", new FileBody(file, "application/octet"));
}
FINALLY POST DATA TO SERVER
httppost.setEntity(mpEntity);
HttpResponse response = httpclient.execute(httppost);
You can definitely do this with vanilla JS like stecb has shown, but I think each
is the best answer to the core question concerning how to do it with lodash.
_.each( myObject.options, ( val, key ) => {
console.log( key, val );
} );
Like JohnnyHK mentioned, there is also the has
method which would be helpful for the use case, but from what is originally stated set
may be more useful. Let's say you wanted to add something to this object dynamically as you've mentioned:
let dynamicKey = 'someCrazyProperty';
let dynamicValue = 'someCrazyValue';
_.set( myObject.options, dynamicKey, dynamicValue );
That's how I'd do it, based on the original description.
Another way to do this would be to add this line to the assembly info of the web application:
// Configure log4net using the .config file
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
Similar to Shriek's.
I had this problem @ one of my wordpress sites after updating and/or moving :)
Check in database table 'wp_options' the 'upload_path' and edit it properly...
Just to expand niko's answer:
You can reference any image via its URL. No matter where it is, as long as it's accesible you can use it as the src
. Example:
Relative location:
<img src="images/image.png">
The image is sought relative to the document's location. If your document is at http://example.com/site/document.html
, then your images
folder should be on the same directory where your document.html
file is.
Absolute location:
<img src="/site/images/image.png">
<img src="http://example.com/site/images/image.png">
or
<img src="http://another-example.com/images/image.png">
In this case, your image will be sought from the document site's root, so, if your document.html
is at http://example.com/site/document.html
, the root would be at http://example.com/
(or it's respective directory on the server's filesystem, commonly www/
). The first two examples are the same, since both point to the same host, Think of the first /
as an alias for your server's root. In the second case, the image is located in another host, so you'd have to specify the complete URL of the image.
Regarding /
, .
and ..
:
The /
symbol will always return the root of a filesystem or site.
The single point ./
points to the same directory where you are.
And the double point ../
will point to the upper directory, or the one that contains the actual working directory.
So you can build relative routes using them.
Examples given the route http://example.com/dir/one/two/three/
and your calling document being inside three/
:
"./pictures/image.png"
or just
"pictures/image.png"
Will try to find a directory named pictures
inside http://example.com/dir/one/two/three/
.
"../pictures/image.png"
Will try to find a directory named pictures
inside http://example.com/dir/one/two/
.
"/pictures/image.png"
Will try to find a directory named pictures
directly at /
or example.com
(which are the same), on the same level as directory
.
Using UITableViewController
The solution accepted will change the height of the TableViewCell
. To fix that, perform following steps:
Write code snippet given below in ViewDidLoad
method.
tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
Add following method in the TableViewClass.m
file.
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return (cell height set on storyboard);
}
That's it. You can build and run your project.
The functionality of creating SQL Agent Jobs is not available in SQL Server Express Edition. An alternative is to execute a batch file that executes a SQL script using Windows Task Scheduler.
In order to do this first create a batch file named sqljob.bat
sqlcmd -S servername -U username -P password -i <path of sqljob.sql>
Replace the servername
, username
, password
and path
with yours.
Then create the SQL Script file named sqljob.sql
USE [databasename]
--T-SQL commands go here
GO
Replace the [databasename]
with your database name. The USE
and GO
is necessary when you write the SQL script.
sqlcmd
is a command-line utility to execute SQL scripts. After creating these two files execute the batch file using Windows Task Scheduler.
NB: An almost same answer was posted for this question before. But I felt it was incomplete as it didn't specify about login information using sqlcmd
.
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
print(D.x.value)
See the Programmatic access to enumeration members and their attributes section:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
You could add a __str__
method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
I've tried all the above and NOTHING worked.
I solved the problem as follows:
First I define a custom Button called ListButton
public class ListButton extends android.widget.Button
{
private ButtonClickedListener clickListener;
public ListButton(Context context)
{
this(context, null);
}
public ListButton(Context context, AttributeSet attrs)
{
this(context, attrs, 0);
}
public ListButton(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
}
public void setClickListener(ButtonClickedListener listener) {
this.clickListener = listener;
}
@Override
public boolean isInTouchMode() {
return true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return false;
}
@Override
public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction())
{
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
eventClicked();
break;
case MotionEvent.ACTION_CANCEL:
break;
case MotionEvent.ACTION_MOVE:
break;
default :
}
return true;
}
private void eventClicked() {
if (this.clickListener!=null) {
this.clickListener.ButtonClicked();
}
}
}
The XML looks like:
<dk.example.views.ListButton
android:id="@+id/cancel_button"
android:layout_width="125dp"
android:layout_height="80dp"
android:text="Cancel"
android:textSize="20sp"
android:layout_margin="10dp"
android:padding="2dp"
android:background="#000000"
android:textColor="#ffffff"
android:textStyle="bold"
/>
Then I define my own ButtonClicked
Listener interface:
public interface ButtonClickedListener {
public void ButtonClicked();
}
Then I use my own listener just as if it was the normal OnClickListener
:
final ListButton cancelButton = (ListButton) viewLayout.findViewById(R.id.cancel_button);
cancelButton.setClickListener(new ButtonClickedListener() {
@Override
public void ButtonClicked() {
//Do your own stuff here...
}
});
The Array.prototype.join() method:
var arr = ["Zero", "One", "Two"];_x000D_
_x000D_
document.write(arr.join(", "));
_x000D_
Brief answer to your question: No. You shouldn't call ConfigureAwait(false)
at the application level like that.
TL;DR version of the long answer: If you are writing a library where you don't know your consumer and don't need a synchronization context (which you shouldn't in a library I believe), you should always use ConfigureAwait(false)
. Otherwise, the consumers of your library may face deadlocks by consuming your asynchronous methods in a blocking fashion. This depends on the situation.
Here is a bit more detailed explanation on the importance of ConfigureAwait
method (a quote from my blog post):
When you are awaiting on a method with await keyword, compiler generates bunch of code in behalf of you. One of the purposes of this action is to handle synchronization with the UI (or main) thread. The key component of this feature is the
SynchronizationContext.Current
which gets the synchronization context for the current thread.SynchronizationContext.Current
is populated depending on the environment you are in. TheGetAwaiter
method of Task looks up forSynchronizationContext.Current
. If current synchronization context is not null, the continuation that gets passed to that awaiter will get posted back to that synchronization context.When consuming a method, which uses the new asynchronous language features, in a blocking fashion, you will end up with a deadlock if you have an available SynchronizationContext. When you are consuming such methods in a blocking fashion (waiting on the Task with Wait method or taking the result directly from the Result property of the Task), you will block the main thread at the same time. When eventually the Task completes inside that method in the threadpool, it is going to invoke the continuation to post back to the main thread because
SynchronizationContext.Current
is available and captured. But there is a problem here: the UI thread is blocked and you have a deadlock!
Also, here are two great articles for you which are exactly for your question:
Finally, there is a great short video from Lucian Wischik exactly on this topic: Async library methods should consider using Task.ConfigureAwait(false).
Hope this helps.
In combination with try
method, to support nil
value:
'string'.try(:upcase)
'string'.try(:capitalize)
'string'.try(:titleize)
Wrap the xml in another element
<wrapper>
<parent>
<child>
Text
</child>
</parent>
<parent>
<child>
<grandchild>
Text
</grandchild>
<grandchild>
Text
</grandchild>
</child>
<child>
Text
</child>
</parent>
</wrapper>
I know this is old but here's a one liner list comprehension:
data = ['word1, 23, 12','word2, 10, 19','word3, 11, 15']
[[int(item) if item.isdigit() else item for item in items.split(', ')] for items in data]
or
[int(item) if item.isdigit() else item for items in data for item in items.split(', ')]
The difference is in the arguments. It's very common to generate a random number from a uniform distribution in the range [0.0, 1.0), so random.random()
just does this. Use random.uniform(a, b)
to specify a different range.
this my solution:
json string $columns_validation = string(1736) "[{"colId":"N_ni","hide":true,"aggFunc":null,"width":136,"pivotIndex":null,"pinned":null,"rowGroupIndex":null},{"colId":"J_2_fait","hide":true,"aggFunc":null,"width":67,"pivotIndex":null,"pinned":null,"rowGroupIndex":null}]"
so i use json_decode twice like that :
$js_column_validation = json_decode($columns_validation);
$js_column_validation = json_decode($js_column_validation);
var_dump($js_column_validation);
and the result is :
array(15) { [0]=> object(stdClass)#23 (7) { ["colId"]=> string(4) "N_ni" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(136) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL } [1]=> object(stdClass)#2130 (7) { ["colId"]=> string(8) "J_2_fait" ["hide"]=> bool(true) ["aggFunc"]=> NULL ["width"]=> int(67) ["pivotIndex"]=> NULL ["pinned"]=> NULL ["rowGroupIndex"]=> NULL }
Or you could just perform a trim()
on the string to handle the case when people use spaces instead of tabs (unless you are reading makefiles)
Going back to the __getattribute__ function; if the default implementation was not overridden; the following checks are done when executing the method:
This is the actual implementation of the object.__getattribute__ method:
.. c:function:: PyObject* PyObject_GenericGetAttr(PyObject *o, PyObject *name) Generic attribute getter function that is meant to be put into a type object's tp_getattro slot. It looks for a descriptor in the dictionary of classes in the object's MRO as well as an attribute in the object's :attr:~object.dict (if present). As outlined in :ref:descriptors, data descriptors take preference over instance attributes, while non-data descriptors don't. Otherwise, an :exc:AttributeError is raised.
I just added the Query key (Refit lib) in the property for the request.
[Query(CollectionFormat.Multi)]
public class ExampleRequest
{
[FromQuery(Name = "name")]
public string Name { get; set; }
[AliasAs("category")]
[Query(CollectionFormat.Multi)]
public List<string> Categories { get; set; }
}
You can do this without a JOIN
:
SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
FROM YourTable
)sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids
Demo: SQL Fiddle
I found another solution elsewhere; that is, to use
upper(@yourString)
but everyone here is saying that, in SQL Server, it doesn't matter because it's ignoring case anyway? I'm pretty sure our database is case-sensitive.
You can use forEach starting from Java 8:
List<String> nameList = new ArrayList<>(
Arrays.asList("USA", "USSR", "UK"));
nameList.forEach((v) -> System.out.println(v));
The following example by Paul McGuire, originally from the pyparsing wiki, but now available only through the Wayback Machine, gives a grammar for parsing some regexes, for the purposes of returning the set of matching strings. As such, it rejects those re's that include unbounded repetition terms, like '+' and '*'. But it should give you an idea about how to structure a parser that would process re's.
#
# invRegex.py
#
# Copyright 2008, Paul McGuire
#
# pyparsing script to expand a regular expression into all possible matching strings
# Supports:
# - {n} and {m,n} repetition, but not unbounded + or * repetition
# - ? optional elements
# - [] character ranges
# - () grouping
# - | alternation
#
__all__ = ["count","invert"]
from pyparsing import (Literal, oneOf, printables, ParserElement, Combine,
SkipTo, operatorPrecedence, ParseFatalException, Word, nums, opAssoc,
Suppress, ParseResults, srange)
class CharacterRangeEmitter(object):
def __init__(self,chars):
# remove duplicate chars in character range, but preserve original order
seen = set()
self.charset = "".join( seen.add(c) or c for c in chars if c not in seen )
def __str__(self):
return '['+self.charset+']'
def __repr__(self):
return '['+self.charset+']'
def makeGenerator(self):
def genChars():
for s in self.charset:
yield s
return genChars
class OptionalEmitter(object):
def __init__(self,expr):
self.expr = expr
def makeGenerator(self):
def optionalGen():
yield ""
for s in self.expr.makeGenerator()():
yield s
return optionalGen
class DotEmitter(object):
def makeGenerator(self):
def dotGen():
for c in printables:
yield c
return dotGen
class GroupEmitter(object):
def __init__(self,exprs):
self.exprs = ParseResults(exprs)
def makeGenerator(self):
def groupGen():
def recurseList(elist):
if len(elist)==1:
for s in elist[0].makeGenerator()():
yield s
else:
for s in elist[0].makeGenerator()():
for s2 in recurseList(elist[1:]):
yield s + s2
if self.exprs:
for s in recurseList(self.exprs):
yield s
return groupGen
class AlternativeEmitter(object):
def __init__(self,exprs):
self.exprs = exprs
def makeGenerator(self):
def altGen():
for e in self.exprs:
for s in e.makeGenerator()():
yield s
return altGen
class LiteralEmitter(object):
def __init__(self,lit):
self.lit = lit
def __str__(self):
return "Lit:"+self.lit
def __repr__(self):
return "Lit:"+self.lit
def makeGenerator(self):
def litGen():
yield self.lit
return litGen
def handleRange(toks):
return CharacterRangeEmitter(srange(toks[0]))
def handleRepetition(toks):
toks=toks[0]
if toks[1] in "*+":
raise ParseFatalException("",0,"unbounded repetition operators not supported")
if toks[1] == "?":
return OptionalEmitter(toks[0])
if "count" in toks:
return GroupEmitter([toks[0]] * int(toks.count))
if "minCount" in toks:
mincount = int(toks.minCount)
maxcount = int(toks.maxCount)
optcount = maxcount - mincount
if optcount:
opt = OptionalEmitter(toks[0])
for i in range(1,optcount):
opt = OptionalEmitter(GroupEmitter([toks[0],opt]))
return GroupEmitter([toks[0]] * mincount + [opt])
else:
return [toks[0]] * mincount
def handleLiteral(toks):
lit = ""
for t in toks:
if t[0] == "\\":
if t[1] == "t":
lit += '\t'
else:
lit += t[1]
else:
lit += t
return LiteralEmitter(lit)
def handleMacro(toks):
macroChar = toks[0][1]
if macroChar == "d":
return CharacterRangeEmitter("0123456789")
elif macroChar == "w":
return CharacterRangeEmitter(srange("[A-Za-z0-9_]"))
elif macroChar == "s":
return LiteralEmitter(" ")
else:
raise ParseFatalException("",0,"unsupported macro character (" + macroChar + ")")
def handleSequence(toks):
return GroupEmitter(toks[0])
def handleDot():
return CharacterRangeEmitter(printables)
def handleAlternative(toks):
return AlternativeEmitter(toks[0])
_parser = None
def parser():
global _parser
if _parser is None:
ParserElement.setDefaultWhitespaceChars("")
lbrack,rbrack,lbrace,rbrace,lparen,rparen = map(Literal,"[]{}()")
reMacro = Combine("\\" + oneOf(list("dws")))
escapedChar = ~reMacro + Combine("\\" + oneOf(list(printables)))
reLiteralChar = "".join(c for c in printables if c not in r"\[]{}().*?+|") + " \t"
reRange = Combine(lbrack + SkipTo(rbrack,ignore=escapedChar) + rbrack)
reLiteral = ( escapedChar | oneOf(list(reLiteralChar)) )
reDot = Literal(".")
repetition = (
( lbrace + Word(nums).setResultsName("count") + rbrace ) |
( lbrace + Word(nums).setResultsName("minCount")+","+ Word(nums).setResultsName("maxCount") + rbrace ) |
oneOf(list("*+?"))
)
reRange.setParseAction(handleRange)
reLiteral.setParseAction(handleLiteral)
reMacro.setParseAction(handleMacro)
reDot.setParseAction(handleDot)
reTerm = ( reLiteral | reRange | reMacro | reDot )
reExpr = operatorPrecedence( reTerm,
[
(repetition, 1, opAssoc.LEFT, handleRepetition),
(None, 2, opAssoc.LEFT, handleSequence),
(Suppress('|'), 2, opAssoc.LEFT, handleAlternative),
]
)
_parser = reExpr
return _parser
def count(gen):
"""Simple function to count the number of elements returned by a generator."""
i = 0
for s in gen:
i += 1
return i
def invert(regex):
"""Call this routine as a generator to return all the strings that
match the input regular expression.
for s in invert("[A-Z]{3}\d{3}"):
print s
"""
invReGenerator = GroupEmitter(parser().parseString(regex)).makeGenerator()
return invReGenerator()
def main():
tests = r"""
[A-EA]
[A-D]*
[A-D]{3}
X[A-C]{3}Y
X[A-C]{3}\(
X\d
foobar\d\d
foobar{2}
foobar{2,9}
fooba[rz]{2}
(foobar){2}
([01]\d)|(2[0-5])
([01]\d\d)|(2[0-4]\d)|(25[0-5])
[A-C]{1,2}
[A-C]{0,3}
[A-C]\s[A-C]\s[A-C]
[A-C]\s?[A-C][A-C]
[A-C]\s([A-C][A-C])
[A-C]\s([A-C][A-C])?
[A-C]{2}\d{2}
@|TH[12]
@(@|TH[12])?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9]))?
@(@|TH[12]|AL[12]|SP[123]|TB(1[0-9]?|20?|[3-9])|OH(1[0-9]?|2[0-9]?|30?|[4-9]))?
(([ECMP]|HA|AK)[SD]|HS)T
[A-CV]{2}
A[cglmrstu]|B[aehikr]?|C[adeflmorsu]?|D[bsy]|E[rsu]|F[emr]?|G[ade]|H[efgos]?|I[nr]?|Kr?|L[airu]|M[dgnot]|N[abdeiop]?|Os?|P[abdmortu]?|R[abefghnu]|S[bcegimnr]?|T[abcehilm]|Uu[bhopqst]|U|V|W|Xe|Yb?|Z[nr]
(a|b)|(x|y)
(a|b) (x|y)
""".split('\n')
for t in tests:
t = t.strip()
if not t: continue
print '-'*50
print t
try:
print count(invert(t))
for s in invert(t):
print s
except ParseFatalException,pfe:
print pfe.msg
print
continue
print
if __name__ == "__main__":
main()
For those who are a bit lazy, I recommend running this as a bat file for when ever you want to enable it:
reg add "HKLM\Software\Microsoft\Fusion" /v EnableLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v ForceLog /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogFailures /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogResourceBinds /t REG_DWORD /d 1 /f
reg add "HKLM\Software\Microsoft\Fusion" /v LogPath /t REG_SZ /d C:\FusionLog\
if not exist "C:\FusionLog\" mkdir C:\FusionLog
Many excellent answers so far, and they do answer the question...But, if you don't want to have to deal with disabling graphics driver's settings, or creating new keyboard mappings, or are developing through a remote session (RDP) or within a VM that intercepts your keystrokes, good-old keyboard navigation still works. Just do Alt-N to bring up the Navigate
menu and then hit the B key.
Please note that you don't hit all keys at the same time. So:
Alt-N wait B
This is what I use all the time, for exactly the case that the OP asked about. Also, this will probably hold through any IntelliJ updates.
Please check if JIRA status in "In Development". For me , it was not , when i changed jira status to "In Development", it worked for me.
ZonedDateTime.parse(
"Jun 13 2003 23:11:52.454 UTC" ,
DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" )
)
.toInstant()
.toEpochMilli()
1055545912454
This Answer expands on the Answer by Lockni.
DateTimeFormatter
First define a formatting pattern to match your input string by creating a DateTimeFormatter
object.
String input = "Jun 13 2003 23:11:52.454 UTC";
DateTimeFormatter f = DateTimeFormatter.ofPattern ( "MMM d uuuu HH:mm:ss.SSS z" );
ZonedDateTime
Parse the string as a ZonedDateTime
. You can think of that class as: ( Instant
+ ZoneId
).
ZonedDateTime zdt = ZonedDateTime.parse ( "Jun 13 2003 23:11:52.454 UTC" , f );
zdt.toString(): 2003-06-13T23:11:52.454Z[UTC]
I do not recommend tracking date-time values as a count-from-epoch. Doing so makes debugging tricky as humans cannot discern a meaningful date-time from a number so invalid/unexpected values may slip by. Also such counts are ambiguous, in granularity (whole seconds, milli, micro, nano, etc.) and in epoch (at least two dozen in by various computer systems).
But if you insist you can get a count of milliseconds from the epoch of first moment of 1970 in UTC (1970-01-01T00:00:00
) through the Instant
class. Be aware this means data-loss as you are truncating any nanoseconds to milliseconds.
Instant instant = zdt.toInstant ();
instant.toString(): 2003-06-13T23:11:52.454Z
long millisSinceEpoch = instant.toEpochMilli() ;
1055545912454
The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date
, Calendar
, & SimpleDateFormat
.
To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.
The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.
You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.*
classes.
Where to obtain the java.time classes?
The ThreeTen-Extra project extends java.time with additional classes. This project is a proving ground for possible future additions to java.time. You may find some useful classes here such as Interval
, YearWeek
, YearQuarter
, and more.
SELECT word, COUNT(*) FROM words GROUP by word HAVING COUNT(*) > 1
Use docstrings.
This is the built-in suggested convention in PyCharm for describing function using docstring comments:
def test_function(p1, p2, p3):
"""
test_function does blah blah blah.
:param p1: describe about parameter p1
:param p2: describe about parameter p2
:param p3: describe about parameter p3
:return: describe what it returns
"""
pass
Suggest you not to use Count
because count always makes extra loads for db use SELECT 1
and it returns 1 if your record right there otherwise it returns null and you can handle it.
Please add reference of System.Web.Extensions and add this namespace using System.Web.Script.Serialization;
at top:
public static void EasyJson()
{
var jsonText = @"{
""some_number"": 108.541,
""date_time"": ""2011-04-13T15:34:09Z"",
""serial_number"": ""SN1234""
}";
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
Console.WriteLine(dict["some_number"]);
Console.ReadLine();
}
Please add reference of System.Web.Extensions and add this namespace using System.Web.Script.Serialization;
at top:
public static void ComplexJson()
{
var jsonText = @"{
""some_number"": 108.541,
""date_time"": ""2011-04-13T15:34:09Z"",
""serial_number"": ""SN1234"",
""more_data"": {
""field1"": 1.0,
""field2"": ""hello""
}
}";
var jss = new JavaScriptSerializer();
var dict = jss.Deserialize<dynamic>(jsonText);
Console.WriteLine(dict["some_number"]);
Console.WriteLine(dict["more_data"]["field2"]);
Console.ReadLine();
}
DataTable DT = ...
// Rename column to OLD:
DT.Columns["ID"].ColumnName = "ID_OLD";
// Add column with new type:
DT.Columns.Add( "ID", typeof(int) );
// copy data from old column to new column with new type:
foreach( DataRow DR in DT.Rows )
{ DR["ID"] = Convert.ToInt32( DR["ID_OLD"] ); }
// remove "OLD" column
DT.Columns.Remove( "ID_OLD" );
You should simply return your object, and shouldn't be concerned about whether its XML or JSON. It is the client responsibility to request JSON or XML from the web api. For example, If you make a call using Internet explorer then the default format requested will be Json and the Web API will return Json. But if you make the request through google chrome, the default request format is XML and you will get XML back.
If you make a request using Fiddler then you can specify the Accept header to be either Json or XML.
Accept: application/xml
You may wanna see this article: Content Negotiation in ASP.NET MVC4 Web API Beta – Part 1
EDIT: based on your edited question with code:
Simple return list of string, instead of converting it to XML. try it using Fiddler.
public List<string> Get(int tenantID, string dataType, string ActionName)
{
List<string> SQLResult = MyWebSite_DataProvidor.DB.spReturnXMLData("SELECT * FROM vwContactListing FOR XML AUTO, ELEMENTS").ToList();
return SQLResult;
}
For example if your list is like:
List<string> list = new List<string>();
list.Add("Test1");
list.Add("Test2");
list.Add("Test3");
return list;
and you specify Accept: application/xml
the output will be:
<ArrayOfstring xmlns:i="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://schemas.microsoft.com/2003/10/Serialization/Arrays">
<string>Test1</string>
<string>Test2</string>
<string>Test3</string>
</ArrayOfstring>
and if you specify 'Accept: application/json' in the request then the output will be:
[
"Test1",
"Test2",
"Test3"
]
So let the client request the content type, instead of you sending the customized xml.
You can use array_walk_recursive
:
array_walk_recursive($array, function ($item, $key) {
echo "$key holds $item\n";
});
As @Egon mentioned above, there is no real folder management in BLOB storage.
You can achieve some features of a file system using '/' in the file name, but this has many limitations (for example, what happen if you need to rename a "folder"?).
As a general rule, I would keep my files as flat as possible in a container, and have my application manage whatever structure I want to expose to the end users (for example manage a nested folder structure in my database, have a record for each file, referencing the BLOB using container-name and file-name).
I use NetBalancer on my Windows machine.
http://seriousbit.com/netbalancer/
Updates on 2017-10-07: The last free version of NetBalancer is 9.2.7. The program has a hard-coded expiration date. Before you start the NetBalancer service, you need to turn back the system clock before 2016-10-18. See this article for details.
try this.
filename = Path.ChangeExtension(".blah")
in you Case:
myfile= c:/my documents/my images/cars/a.jpg;
string extension = Path.GetExtension(myffile);
filename = Path.ChangeExtension(myfile,".blah")
You should look this post too:
http://msdn.microsoft.com/en-us/library/system.io.path.changeextension.aspx
Or if all borders have same style, just:
border:10px;
its even easier:
fileList.Where(item => filterList.Contains(item))
in case you want to filter not for an exact match but for a "contains" you can use this expression:
var t = fileList.Where(file => filterList.Any(folder => file.ToUpperInvariant().Contains(folder.ToUpperInvariant())));
You can use load_only function:
from sqlalchemy.orm import load_only
fields = ['name', 'addr', 'phone', 'url']
companies = session.query(SomeModel).options(load_only(*fields)).all()
You can also use the "Spring Boot App" run configuration. For that you'll need to install the Spring Tool Suite plug-in for Eclipse (STS).
Try adding "bDestroy": true to the options object literal, e.g.
$('#dataTable').dataTable({
...
....
"bDestroy": true
});
Source: iodocs.com
or Remove the first:
$(document).ready(function() {
$('#example').dataTable();
} );
In your case is the best option vjk.
Sure:
var query = grades.GroupBy(student => student.Name)
.Select(group =>
new { Name = group.Key,
Students = group.OrderByDescending(x => x.Grade) })
.OrderBy(group => group.Students.First().Grade);
Note that you can get away with just taking the first grade within each group after ordering, because you already know the first entry will be have the highest grade.
Then you could display them with:
foreach (var group in query)
{
Console.WriteLine("Group: {0}", group.Name);
foreach (var student in group.Students)
{
Console.WriteLine(" {0}", student.Grade);
}
}
This should work:
@interface MyClass
{
int _doubleDigits[10];
}
@property(readonly) int *doubleDigits;
@end
@implementation MyClass
- (int *)doubleDigits
{
return _doubleDigits;
}
@end
It doesn't work because it's syntactically nonsensical. You simply can't do that in JavaScript like that.
You can, however, use jQuery:
if ($(this).is('[href$=?]'))
You can also just look at the "href" value:
if (/\?$/.test(this.href))
It seems wrong to me to set up an if/else statement just to use the else portion...
Just negate your condition, and you'll get the else
logic inside the if
:
if (!(id in tutorTimes)) { ... }
Use GitZip online tool. It allows to download a sub-directory of a github repository as a zip file. No git commands needed!
I just wrote a recursive function to figure out if a class needed to be serialized using a DataContractSerializer. The big issue came with templates/generics where a class could contain other types that needed to be datacontract serialized... so it's go through each type, if it's not datacontractserializable check it's types.
You can do it using remote debugging, here is official documentation. Basic process:
*
from dev tools on pc/mac.*
This is now "Remote devices".
For anyone checking this using python 3:
If you want to print the following output "100% correct"
:
python 3.8: print("100% correct")
python 3.7 and less: print("100%% correct")
A neat programming workaround for compatibility across diff versions of python is shown below:
Note: If you have to use this, you're probably experiencing many other errors... I'd encourage you to upgrade / downgrade python in relevant machines so that they are all compatible.
DevOps is a notable exception to the above -- implementing the following code would indeed be appropriate for specific DevOps / Debugging scenarios.
import sys
if version_info.major==3:
if version_info.minor>=8:
my_string = "100% correct"
else:
my_string = "100%% correct"
# Finally
print(my_string)
To change the indentation based on programming language:
Open the Command Palette (CtrlShiftP | macOS: ??P)
Preferences: Configure language specific settings... (command id: workbench.action.configureLanguageBasedSettings
)
Select programming language (for example TypeScript)
Add this code:
"[typescript]": {
"editor.tabSize": 2
}
You can add virtual columns as
SELECT '1' as temp
But if you tries to put where condition to additionally generated column, it wont work and will show an error message as the column doesn't exist.
We can solve this issue by returning sql result as a table.ie,
SELECT tb.* from (SELECT 1 as temp) as tb WHERE tb.temp = 1
DATEDIFF() is designed to return the number boundaries crossed between the two dates for the span specified. To get it to do what you want, you need to make an additional adjustment to account for when the dates cross a boundary but don't complete the full span.
This is a security update. If an attacker can modify some file in the web server (the JS one, for example), he can make every loaded pages to download another script (for example to keylog your password or steal your SessionID and send it to his own server).
To avoid it, the browser check the Same-origin policy
Your problem is that the browser is trying to load something with your script (with an Ajax request) that is on another domain (or subdomain). To avoid it (if it is on your own website) you can:
Update in 2020. Here is another way if you prefer.
IdentityResult res = new IdentityResult();
var _role = new IdentityRole();
_role.Name = role.RoleName;
res = await _roleManager.CreateAsync(_role);
if (!res.Succeeded)
{
foreach (IdentityError er in res.Errors)
{
ModelState.AddModelError(string.Empty, er.Description);
}
ViewBag.UserMessage = "Error Adding Role";
return View();
}
else
{
ViewBag.UserMessage = "Role Added";
return View();
}
The Problem is the Container that gets the smallest possible size.
Just give a width:
to the Container (in red) and you are done.
width: MediaQuery.of(context).size.width
new Positioned(
bottom: 0.0,
child: new Container(
width: MediaQuery.of(context).size.width,
color: Colors.red,
margin: const EdgeInsets.all(0.0),
child: new Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new Align(
alignment: Alignment.bottomCenter,
child: new ButtonBar(
alignment: MainAxisAlignment.center,
children: <Widget>[
new OutlineButton(
onPressed: null,
child: new Text(
"Login",
style: new TextStyle(color: Colors.white),
),
),
new RaisedButton(
color: Colors.white,
onPressed: null,
child: new Text(
"Register",
style: new TextStyle(color: Colors.black),
),
)
],
),
)
],
),
),
),
It is 2019 and I need to sign APK with V1 (jar signature) or V2 (full APK signature). I googled "generate signed apk gradle" and it brought me here. So I am adding my original solution here.
signingConfigs {
release {
...
v1SigningEnabled true
v2SigningEnabled true
}
}
My original question: How to use V1 (Jar signature) or V2 (Full APK signature) from build.gradle file
As I have already explained the reasons behind this issue and also how to handle it in a different answer thread Here. Still i am sharing the solution summary here.
One of the main reasons notifyDataSetChanged()
won't work for you - is,
Your adapter loses reference to your list.
When creating and adding a new list to the Adapter
. Always follow these guidelines:
arrayList
while declaring it globally.arrayList
it will take care of it, but never loose the
reference.adapter.clear()
and arrayList.clear()
before
actually adding data to the list) but don't set the adapter i.e If
the new data is populated in the arrayList
than just
adapter.notifyDataSetChanged()
Hope this helps.
You can add "_CRT_SECURE_NO_WARNINGS" in Preprocessor Definitions.
Right-click your project->Properties->Configuration Properties->C/C++ ->Preprocessor->Preprocessor Definitions.
To get the selected value of a spinner you can follow this example.
Create a nested class that implements AdapterView.OnItemSelectedListener. This will provide a callback method that will notify your application when an item has been selected from the Spinner.
Within "onItemSelected" method of that class, you can get the selected item:
public class YourItemSelectedListener implements OnItemSelectedListener {
public void onItemSelected(AdapterView<?> parent, View view, int pos, long id) {
String selected = parent.getItemAtPosition(pos).toString();
}
public void onNothingSelected(AdapterView parent) {
// Do nothing.
}
}
Finally, your ItemSelectedListener needs to be registered in the Spinner:
spinner.setOnItemSelectedListener(new MyOnItemSelectedListener());
This also works:
this.getCurrentFocus()
It gets the view so I can use it.
Use NuGet (VS 2013+):
The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)
Right-click on "References" and choose "Manage NuGet Packages...", then just search for Excel.
VS 2012:
Older versions of VS didn't have access to NuGet.
Microsoft.Office.Interop.Excel
.VS 2008 / 2010:
Microsoft.Office.Interop.Excel
.TL;DR:
The ActionListener
s (there can be multiple) execute in the order they were registered BEFORE the action
Long Answer:
A business action
typically invokes an EJB service and if necessary also sets the final result and/or navigates to a different view
if that is not what you are doing an actionListener
is more appropriate i.e. for when the user interacts with the components, such as h:commandButton
or h:link
they can be handled by passing the name of the managed bean method in actionListener
attribute of a UI Component or to implement an ActionListener
interface and pass the implementation class name to actionListener
attribute of a UI Component.
This is probably considered dirty by some, but a very practical solution in case of github repositories is just to make a script, e.g. "git-ls":
#!/bin/sh
remote_url=${1:? "$0 requires URL as argument"}
curl -s $remote_url | grep js-directory-link | sed "s/.* title=\"\(.*\)\".*/\1/"
Make it executable and reachable of course: chmod a+x git-ls; sudo cp git-ls /usr/local/bin
. Now, you just run it as you wish:
git-ls https://github.com/mrquincle/aim-bzr
git-ls https://github.com/mrquincle/aim-bzr/tree/master/aim_modules
Also know that there is a git instaweb
utility for your local files. To have the ability to show files and have a server like that does in my opinion not destroy any of the inherent decentralized characteristics of git.
Custom Buttons appear in their respective image colors. Setting the button type to "System" in the storyboard (or to UIButtonTypeSystem
in code), will render the button's image with the default tint color.
(tested on iOS9, Xcode 7.3)
I'm using the following piece of code for my friendly urls:
from unicodedata import normalize
from re import sub
def slugify(title):
name = normalize('NFKD', title).encode('ascii', 'ignore').replace(' ', '-').lower()
#remove `other` characters
name = sub('[^a-zA-Z0-9_-]', '', name)
#nomalize dashes
name = sub('-+', '-', name)
return name
It works fine with unicode characters as well.
The dataset:
dat <- read.table(text = "A B C D E F G
1 480 780 431 295 670 360 190
2 720 350 377 255 340 615 345
3 460 480 179 560 60 735 1260
4 220 240 876 789 820 100 75", header = TRUE)
Now you can convert the data frame into a matrix and use the barplot
function.
barplot(as.matrix(dat))
On some servers and web hosts, it's possible to disable ModSecurity via .htaccess
, but be aware that you can only switch it on or off, you can't disable individual rules.
But a good practice that still keeps your site secure is to disable it only on specific URLs, rather than your entire site. You can specify which URLs to match via the regex in the <If>
statement below...
### DISABLE mod_security firewall
### Some rules are currently too strict and are blocking legitimate users
### We only disable it for URLs that contain the regex below
### The regex below should be placed between "m#" and "#"
### (this syntax is required when the string contains forward slashes)
<IfModule mod_security.c>
<If "%{REQUEST_URI} =~ m#/admin/#">
SecFilterEngine Off
SecFilterScanPOST Off
</If>
</IfModule>
You want "rbind".
b$b <- NA
new <- rbind(a, b)
rbind requires the data frames to have the same columns.
The first line adds column b to data frame b.
Results
> a <- data.frame(a=c(0,1,2), b=c(3,4,5), c=c(6,7,8))
> a
a b c
1 0 3 6
2 1 4 7
3 2 5 8
> b <- data.frame(a=c(9,10,11), c=c(12,13,14))
> b
a c
1 9 12
2 10 13
3 11 14
> b$b <- NA
> b
a c b
1 9 12 NA
2 10 13 NA
3 11 14 NA
> new <- rbind(a,b)
> new
a b c
1 0 3 6
2 1 4 7
3 2 5 8
4 9 NA 12
5 10 NA 13
6 11 NA 14
Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)
Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:
Range("B5") = "=SUM(B10:B100)"
or
X = "=SUM(B10:B100)
There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.
It will not matter if some cells are empty, it will simply see them as containing zeros!
This should do it for you!
I think we can access the socket object from the server, and you can assign the nickname, and point its socket id,
io.sockets.on('connection',function(socket){
io.sockets.sockets['nickname'] = socket.id;
client.on("chat", function(data) {
var sock_id = io.sockets.sockets['nickname']
io.sockets.sockets[sock_id].emit("private", "message");
});
});
On disconnect
please remove the nickname from io.sockets.sockets
.
As other answers pointed out, it is most likely generated by some tool.
But if I were the original author of the file, my answer would be: Consistency.
If I am not allowed to put double quotes in my attributes, why put them in the element's content ? Why do these specs always have these exceptional cases ..
If I had to write the HTML spec, I would say All double quotes need to be encoded
. Done.
Today it is like In attribute values we need to encode double quotes, except when the attribute value itself is defined by single quotes. In the content of elements, double quotes can be, but are not required to be, encoded.
(And I am surely forgetting some cases here).
Double quotes are a keyword of the spec, encode them. Lesser/greater than are a keyword of the spec, encode them. etc..
You should access frames from window
and not document
window.frames['myIFrame'].document.getElementById('myIFrameElemId')
Late answer, but two things to add:
'ColorOrder'
property and how to set a global default with 'DefaultAxesColorOrder'
, see the "Appendix" at the bottom of this post.The ColorOrder
axes
property allows MATLAB to automatically cycle through a list of colors when using hold on/all
(again, see Appendix below for how to set
/get
the ColorOrder
for a specific axis or globally via DefaultAxesColorOrder
). However, by default MATLAB only specifies a short list of colors (just 7 as of R2013b) to cycle through, and on the other hand it can be problematic to find a good set of colors for more data series. For 10 plots, you obviously cannot rely on the default ColorOrder
.
A great way to define N visually distinct colors is with the "Generate Maximally Perceptually-Distinct Colors" (GMPDC) submission on the MATLAB Central File File Exchange. It is best described in the author's own words:
This function generates a set of colors which are distinguishable by reference to the "Lab" color space, which more closely matches human color perception than RGB. Given an initial large list of possible colors, it iteratively chooses the entry in the list that is farthest (in Lab space) from all previously-chosen entries.
For example, when 25 colors are requested:
The GMPDC submission was chosen on MathWorks' official blog as Pick of the Week in 2010 in part because of the ability to request an arbitrary number of colors (in contrast to MATLAB's built in 7 default colors). They even made the excellent suggestion to set MATLAB's ColorOrder
on startup to,
distinguishable_colors(20)
Of course, you can set the ColorOrder
for a single axis or simply generate a list of colors to use in any way you like. For example, to generate 10 "maximally perceptually-distinct colors" and use them for 10 plots on the same axis (but not using ColorOrder
, thus requiring a loop):
% Starting with X of size N-by-P-by-2, where P is number of plots
mpdc10 = distinguishable_colors(10) % 10x3 color list
hold on
for ii=1:size(X,2),
plot(X(:,ii,1),X(:,ii,2),'.','Color',mpdc10(ii,:));
end
The process is simplified, requiring no for
loop, with the ColorOrder
axis property:
% X of size N-by-P-by-2 mpdc10 = distinguishable_colors(10) ha = axes; hold(ha,'on') set(ha,'ColorOrder',mpdc10) % --- set ColorOrder HERE --- plot(X(:,:,1),X(:,:,2),'-.') % loop NOT needed, 'Color' NOT needed. Yay!
APPENDIX
To get the ColorOrder
RGB array used for the current axis,
get(gca,'ColorOrder')
To get the default ColorOrder
for new axes,
get(0,'DefaultAxesColorOrder')
Example of setting new global ColorOrder
with 10 colors on MATLAB start, in startup.m
:
set(0,'DefaultAxesColorOrder',distinguishable_colors(10))
The following is the fastest way to solve this . Space complexity O(1) , Time complexity O(n). If
If a node has both left and right value as not null, then that node is your answer(3rd 'if' from top). While iterating if a value is found, as all the values are uniques and must be present, we don't need to search its descendants. so just return the found node that matched. if a node's both left and right branch contents null propagate null upwards. when reached top-level recursion, if one branch returned value, others do not keep propagating that value, when both returned not null return current node. If it reaches root level recursion with one null and another not null, return not null value, as the question, promises the value exists, it must be in the children tree of the found node which we never traversed.
class Solution {
public TreeNode lowestCommonAncestor(TreeNode root, TreeNode p, TreeNode q) {
if(root == null) return null;
if(root.val == p.val || root.val == q.val) return root;
TreeNode left = lowestCommonAncestor(root.left, p, q);
TreeNode right = lowestCommonAncestor(root.right, p, q);
if (left != null && right !=null) return root;
if (left == null && right ==null) return null;
return (left != null ? left : right);
}
}
Thanks to @sehe for the one-line escape:
var escaped = new System.Xml.Linq.XText(unescaped).ToString();
I add to it the one-line un-escape:
var unescapedAgain = System.Xml.XmlReader.Create(new StringReader("<r>" + escaped + "</r>")).ReadElementString();
it means 'nothing for the first argument, nothing for the second, and jump by three'. It gets every third item of the sequence sliced. Extended slices is what you want. New in Python 2.3
WebSocket is just another application level protocol over TCP protocol, just like HTTP.
Some snippets < Spring in Action 4> quoted below, hope it can help you understand WebSocket better.
In its simplest form, a WebSocket is just a communication channel between two applications (not necessarily a browser is involved)...WebSocket communication can be used between any kinds of applications, but the most common use of WebSocket is to facilitate communication between a server application and a browser-based application.
In my case setting Java Max Heap Size from 2g to 1g worked.
Add following to application module's build.gradle file
android {
dexOptions {
javaMaxHeapSize "1g"
}
}
This worked for me
setInterval(ajax_query, 10000);
function ajax_query(){
//Call ajax here
}
Make sure the value for target (which tells the target android version) in project.properties file of both your project folder and appcompat_v7 folder is same (preferably the latest).
: inside 'your_project'/project.properties
target=android-21
android.library.reference.1=../appcompat_v7
and
: inside appcompat_v7/project.properties
target=android-21
android.library=true
and after this don't forget to clean your project .
If you want a relative link to your wiki page on GitHub, use this:
Read here: [Some other wiki page](path/to/some-other-wiki-page)
If you want a link to a file in the repository, let us say, to reference some header file, and the wiki page is at the root of the wiki, use this:
Read here: [myheader.h](../tree/master/path/to/myheader.h)
The rationale for the last is to skip the "/wiki" path with "../", and go to the master branch in the repository tree without specifying the repository name, that may change in the future.
You can use COUNT(DISTINCT ...)
:
SELECT COUNT(DISTINCT town)
FROM user
for listener support no services you can use the following command to set local_listener paramter in your spfile use your listener port and server ip address
alter system set local_listener='(DESCRIPTION=(ADDRESS=(PROTOCOL=tcp)(HOST=192.168.1.101)(PORT=1520)))' sid='testdb' scope=spfile;
Use this - "require command here" > log_file_name 2>&1
Detail description of redirection operator in Unix/Linux.
The > operator redirects the output usually to a file but it can be to a device. You can also use >> to append.
If you don't specify a number then the standard output stream is assumed but you can also redirect errors
> file redirects stdout to file
1> file redirects stdout to file
2> file redirects stderr to file
&> file redirects stdout and stderr to file
/dev/null is the null device it takes any input you want and throws it away. It can be used to suppress any output.
Indeed, you don't need to drop a @local_variable
.
But if you use #local_table
, it can be done, e.g. it's convenient to be able to re-execute a query several times.
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
/*
can DROP here, otherwise will fail with the following error
on re-execution in the same window (I use SSMS DB client):
Msg 2714, Level ..., State ..., Line ...
There is already an object named '#recent_records' in the database.
*/
DROP TABLE #recent_records
;
You can also put your SELECT statement in a TRANSACTION to be able to re-execute without an explicit DROP:
BEGIN TRANSACTION
SELECT *
INTO #recent_records
FROM dbo.my_table t
WHERE t.CreatedOn > '2021-01-01'
;
SELECT *
FROM #recent_records
;
ROLLBACK
The mPDF docs state that the first argument of Output()
is the file path, second is the saving mode - you need to set it to 'F'
.
$mpdf->Output('filename.pdf','F');
I think you need to make the .holder
position:relative;
and .popup
position:absolute;
As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.
If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").
But this function is not intended to reload the browser.
All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.
Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).
For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.
Hence the need for the function
history.pushState({},"Results for `Cats`",'url.html?s=cats');
It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.
When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.
If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.
As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.
See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.
Nice answers here. I encountered the same problem, but I tried <script src="script.js" defer></script>
but I didn't work quite well. I had all the code and links set up fine. The problem is I had put the js file link in the head of the page, so it was loaded before the DOM was loaded. There are 2 solutions to this.
window.onload = () => { //write your code here }
<script src="script.js"></script>
to the bottom of the html file so that it loads last.If we follow the w3 org table reference ,and follow the Permitted Contents section, we can see that the table
tags takes tbody
(optional) and tr
as the only permitted contents.
So i reckon it is safe to say we cannot add a div
tag which is a flow content as a direct child of the table
which i understand is what you meant when you had said above a tr
.
Having said that , as we follow the above link , you will find that it is safe to use div
s inside the td
element as seen here
You have to make one ajax call to get the required result, in this case you can use Google API to get the same
http://maps.googleapis.com/maps/api/geocode/json?latlng=40.714224,-73.961452&sensor=true/false
Build this kind of url and replace the lat long with the one you want to. do the call and response will be in JSON, parse the JSON and you will get the complete address up to street level
From this document, this DTU percent is determined by this query:
SELECT end_time,
(SELECT Max(v)
FROM (VALUES (avg_cpu_percent), (avg_data_io_percent),
(avg_log_write_percent)) AS
value(v)) AS [avg_DTU_percent]
FROM sys.dm_db_resource_stats;
looks like the max of avg_cpu_percent
, avg_data_io_percent
and avg_log_write_percent
Reference:
I had this problem, and the cause was that I had not added the Microsoft.Owin.Host.SystemWeb NuGet package to my project. Although the code in my startup class was correct, it was not being executed.
So if you're trying to solve this problem, put a breakpoint in the code where you do the Unity registrations. If you don't hit it, your dependency injection isn't going to work.
Calendar cal = Calendar.getInstance();
datePickerDialog.getDatePicker().setMinDate(cal.getTimeInMillis());
//To set make max 7days date selection on current year and month
datePickerDialog.getDatePicker().setMaxDate((cal.getTimeInMillis())+(1000*60*60*24*6));
datePickerDialog.setTitle("Select Date");
datePickerDialog.show();
My solution :
select h.hostid, sum(ifnull(h.A,0)) as A, sum(ifnull(h.B,0)) as B, sum(ifnull(h.C,0)) as C from (
select
hostid,
case when itemName = 'A' then itemvalue end as A,
case when itemName = 'B' then itemvalue end as B,
case when itemName = 'C' then itemvalue end as C
from history
) h group by hostid
It produces the expected results in the submitted case.
My way is simple like this:
static id instanceOfXXX = nil;
+ (id) sharedXXX
{
static volatile BOOL initialized = NO;
if (!initialized)
{
@synchronized([XXX class])
{
if (!initialized)
{
instanceOfXXX = [[XXX alloc] init];
initialized = YES;
}
}
}
return instanceOfXXX;
}
If the singleton is initialized already, the LOCK block will not be entered. The second check if(!initialized) is to make sure it is not initialized yet when the current thread acquires the LOCK.
Cors change the request method before it's done, from POST to OPTIONS, so, your post data will not be sent. The way that worked to handle this cors issue, is performing the request with ajax, which does not support the OPTIONS method. example code:
$.ajax({
type: "POST",
crossdomain: true,
url: "http://localhost:1415/anything",
dataType: "json",
data: JSON.stringify({
anydata1: "any1",
anydata2: "any2",
}),
success: function (result) {
console.log(result)
},
error: function (xhr, status, err) {
console.error(xhr, status, err);
}
});
with this headers on c# server:
if (request.HttpMethod == "OPTIONS")
{
response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept, X-Requested-With");
response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
response.AddHeader("Access-Control-Max-Age", "1728000");
}
response.AppendHeader("Access-Control-Allow-Origin", "*");
Thanks to Gruff Bunny and Louis' comments, I found the source of the issue.
As I use Backbone.js too, I loaded a special build of Lodash compatible with Backbone and Underscore that disables some features. In this example:
var clone = _.clone(data, true);
data[1].values.d = 'x';
_.isEqual(data, clone) === false
_.isEqual(data, clone) === true
I just replaced the Underscore build with the Normal build in my Backbone application and the application is still working. So I can now use the Lodash .clone with the expected behaviour.
Edit 2018: the Underscore build doesn't seem to exist anymore. If you are reading this in 2018, you could be interested by this documentation (Backbone and Lodash).
If you set up your project with the default gradle package structure, i.e.:
src/main/java
src/main/resources
src/test/java
src/test/resources
then you won't need to modify sourceSets to run your tests. Gradle will figure out that your test classes and resources are in src/test. You can then run as Oliver says above. One thing to note: Be careful when setting property files and running your test classes with both gradle and you IDE. I use Eclipse, and when running JUnit from it, Eclipse chooses one classpath (the bin directory) whereas gradle chooses another (the build directory). This can lead to confusion if you edit a resource file, and don't see your change reflected at test runtime.
If you decide to go for a minimal approach, without libpng/libjpeg dependencies, I suggest using stb_image
and stb_image_write
, found here.
It's as simple as it gets, you just need to place the header files stb_image.h
and stb_image_write.h
in your folder.
Here's the code that you need to read images:
#include <stdint.h>
#define STB_IMAGE_IMPLEMENTATION
#include "stb_image.h"
int main() {
int width, height, bpp;
uint8_t* rgb_image = stbi_load("image.png", &width, &height, &bpp, 3);
stbi_image_free(rgb_image);
return 0;
}
And here's the code to write an image:
#include <stdint.h>
#define STB_IMAGE_WRITE_IMPLEMENTATION
#include "stb_image_write.h"
#define CHANNEL_NUM 3
int main() {
int width = 800;
int height = 800;
uint8_t* rgb_image;
rgb_image = malloc(width*height*CHANNEL_NUM);
// Write your code to populate rgb_image here
stbi_write_png("image.png", width, height, CHANNEL_NUM, rgb_image, width*CHANNEL_NUM);
return 0;
}
You can compile without flags or dependencies:
g++ main.cpp
Other lightweight alternatives include:
After the long time research i have found the solution for above:
Firstly you change the wp-config.php> Database DB_CHARSET default to "utf8"
Click the "Export" tab for the database
Click the "Custom" radio button
Go the section titled "Format-specific options" and change the dropdown for "Database system or older MySQL server to maximize output compatibility with:" from NONE to MYSQL40.
Scroll to the bottom and click go
Then you are on.
The specificity is calculated based on the amount of id, class and tag selectors in your rule. Id has the highest specificity, then class, then tag. Your first rule is now more specific than the second one, since they both have a class selector, but the first one also has two tag selectors.
To make the second one override the first one, you can make more specific by adding information of it's parents:
table.rule1 tr td.rule2 {
background-color: #ffff00;
}
Here is a nice article for more information on selector precedence.
If you are in a transaction you can use SELECT lastval()
after an insert to get the last generated id.
I had a much stranger solution. In case anyone runs into this, it's worth double checking your gradle file. It turns out that as I was cloning this git and gradle was runnning, it deleted one line from my build.gradle (app) file.
dependencies {
provided files(providedFiles)
Obviously the problem here was to just add it back and re-sync with gradle.
The problem is that if you try to write a <table>
or a <tr>
or <td>
tag using JS every time you insert a new tag the browser will try to close it as it will think that there is an error on the code.
Instead of writing your table line by line, concatenate your table into a variable and insert it once created:
<script language="javascript" type="text/javascript">
<!--
var myArray = new Array();
myArray[0] = 1;
myArray[1] = 2.218;
myArray[2] = 33;
myArray[3] = 114.94;
myArray[4] = 5;
myArray[5] = 33;
myArray[6] = 114.980;
myArray[7] = 5;
var myTable= "<table><tr><td style='width: 100px; color: red;'>Col Head 1</td>";
myTable+= "<td style='width: 100px; color: red; text-align: right;'>Col Head 2</td>";
myTable+="<td style='width: 100px; color: red; text-align: right;'>Col Head 3</td></tr>";
myTable+="<tr><td style='width: 100px; '>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td>";
myTable+="<td style='width: 100px; text-align: right;'>---------------</td></tr>";
for (var i=0; i<8; i++) {
myTable+="<tr><td style='width: 100px;'>Number " + i + " is:</td>";
myArray[i] = myArray[i].toFixed(3);
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td>";
myTable+="<td style='width: 100px; text-align: right;'>" + myArray[i] + "</td></tr>";
}
myTable+="</table>";
document.write( myTable);
//-->
</script>
If your code is in an external JS file, in HTML create an element with an ID where you want your table to appear:
<div id="tablePrint"> </div>
And in JS instead of document.write(myTable)
use the following code:
document.getElementById('tablePrint').innerHTML = myTable;
For the correct solution after many hours:
<add name="umbracoDbDSN" connectionString="data source=YOUR_SERVER_NAME;database=nrc;Integrated Security=SSPI;persist security info=True;" providerName="System.Data.SqlClient" />
Hope this will help.
You can stop a query which is being processed by this
Find the Id of the query process by => show processlist;
Then => kill id;
You should be able to control all your headers by skipping loadUrl and writing your own loadPage using Java's HttpURLConnection. Then use the webview's loadData to display the response.
There is no access to the headers which Google provides. They are in a JNI call, deep in the WebView source.
I noticed following line from error.
exact fetch returns more than requested number of rows
That means Oracle was expecting one row but It was getting multiple rows. And, only dual table has that characteristic, which returns only one row.
Later I recall, I have done few changes in dual table and when I executed dual table. Then found multiple rows.
So, I truncated dual
table and inserted only row which X
value. And, everything working fine.
React Portals can let you render to elements outside the root React node (such at <title>
), as if they were actual React nodes. So now you can set the title cleanly and without any additional dependencies:
Here's an example:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class Title extends Component {
constructor(props) {
super(props);
this.titleEl = document.getElementsByTagName("title")[0];
}
render() {
let fullTitle;
if(this.props.pageTitle) {
fullTitle = this.props.pageTitle + " - " + this.props.siteTitle;
} else {
fullTitle = this.props.siteTitle;
}
return ReactDOM.createPortal(
fullTitle || "",
this.titleEl
);
}
}
Title.defaultProps = {
pageTitle: null,
siteTitle: "Your Site Name Here",
};
export default Title;
Just put the component in the page and set pageTitle
:
<Title pageTitle="Dashboard" />
<Title pageTitle={item.name} />
I am explaining, How to get current location and Directly move to the camera to current location with assuming that you have implemented map-v2. For more details, You can refer official doc.
Add location service in gradle
implementation "com.google.android.gms:play-services-location:11.0.1"
Add location permission in manifest file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
Make sure you ask for RunTimePermission. I am using Ask-Permission for that. Its easy to use.
Now refer below code to get the current location and display it on a map.
private FusedLocationProviderClient mFusedLocationProviderClient;
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mFusedLocationProviderClient = LocationServices
.getFusedLocationProviderClient(getActivity());
}
private void getDeviceLocation() {
try {
if (mLocationPermissionGranted) {
Task<Location> locationResult = mFusedLocationProviderClient.getLastLocation();
locationResult.addOnCompleteListener(new OnCompleteListener<Location>() {
@Override
public void onComplete(@NonNull Task<Location> task) {
if (task.isSuccessful()) {
// Set the map's camera position to the current location of the device.
Location location = task.getResult();
LatLng currentLatLng = new LatLng(location.getLatitude(),
location.getLongitude());
CameraUpdate update = CameraUpdateFactory.newLatLngZoom(currentLatLng,
DEFAULT_ZOOM);
googleMap.moveCamera(update);
}
}
});
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
When user granted location permission call above getDeviceLocation()
method
private void updateLocationUI() {
if (googleMap == null) {
return;
}
try {
if (mLocationPermissionGranted) {
googleMap.setMyLocationEnabled(true);
googleMap.getUiSettings().setMyLocationButtonEnabled(true);
getDeviceLocation();
} else {
googleMap.setMyLocationEnabled(false);
googleMap.getUiSettings().setMyLocationButtonEnabled(false);
}
} catch (SecurityException e) {
Log.e("Exception: %s", e.getMessage());
}
}
Annotation which indicates that a method parameter should be bound to a URI template variable. Supported for RequestMapping annotated handler methods.
@RequestMapping(value = "/download/{documentId}", method = RequestMethod.GET)
public ModelAndView download(@PathVariable int documentId) {
ModelAndView mav = new ModelAndView();
Document document = documentService.fileDownload(documentId);
mav.addObject("downloadDocument", document);
mav.setViewName("download");
return mav;
}
The (^) XOR operator generates 1 when it is applied on two different bits (0 and 1). It generates 0 when it is applied on two same bits (0 and 0 or 1 and 1).
You'll need to use UNION
to combine the results of two queries. In your case:
SELECT ChargeNum, CategoryID, SUM(Hours)
FROM KnownHours
GROUP BY ChargeNum, CategoryID
UNION ALL
SELECT ChargeNum, 'Unknown' AS CategoryID, SUM(Hours)
FROM UnknownHours
GROUP BY ChargeNum
Note - If you use UNION ALL
as in above, it's no slower than running the two queries separately as it does no duplicate-checking.
Using Stream
private static void copyFileUsingStream(File source, File dest) throws IOException {
InputStream is = null;
OutputStream os = null;
try {
is = new FileInputStream(source);
os = new FileOutputStream(dest);
byte[] buffer = new byte[1024];
int length;
while ((length = is.read(buffer)) > 0) {
os.write(buffer, 0, length);
}
} finally {
is.close();
os.close();
}
}
Using Channel
private static void copyFileUsingChannel(File source, File dest) throws IOException {
FileChannel sourceChannel = null;
FileChannel destChannel = null;
try {
sourceChannel = new FileInputStream(source).getChannel();
destChannel = new FileOutputStream(dest).getChannel();
destChannel.transferFrom(sourceChannel, 0, sourceChannel.size());
}finally{
sourceChannel.close();
destChannel.close();
}
}
Using Apache Commons IO lib:
private static void copyFileUsingApacheCommonsIO(File source, File dest) throws IOException {
FileUtils.copyFile(source, dest);
}
Using Java SE 7 Files class:
private static void copyFileUsingJava7Files(File source, File dest) throws IOException {
Files.copy(source.toPath(), dest.toPath());
}
Or try Googles Guava :
https://github.com/google/guava
docs: https://guava.dev/releases/snapshot-jre/api/docs/com/google/common/io/Files.html
Compare time:
File source = new File("/Users/sidikov/tmp/source.avi");
File dest = new File("/Users/sidikov/tmp/dest.avi");
//copy file conventional way using Stream
long start = System.nanoTime();
copyFileUsingStream(source, dest);
System.out.println("Time taken by Stream Copy = "+(System.nanoTime()-start));
//copy files using java.nio FileChannel
source = new File("/Users/sidikov/tmp/sourceChannel.avi");
dest = new File("/Users/sidikov/tmp/destChannel.avi");
start = System.nanoTime();
copyFileUsingChannel(source, dest);
System.out.println("Time taken by Channel Copy = "+(System.nanoTime()-start));
//copy files using apache commons io
source = new File("/Users/sidikov/tmp/sourceApache.avi");
dest = new File("/Users/sidikov/tmp/destApache.avi");
start = System.nanoTime();
copyFileUsingApacheCommonsIO(source, dest);
System.out.println("Time taken by Apache Commons IO Copy = "+(System.nanoTime()-start));
//using Java 7 Files class
source = new File("/Users/sidikov/tmp/sourceJava7.avi");
dest = new File("/Users/sidikov/tmp/destJava7.avi");
start = System.nanoTime();
copyFileUsingJava7Files(source, dest);
System.out.println("Time taken by Java7 Files Copy = "+(System.nanoTime()-start));
Not exactly what the OP asked, but lots of folks are coming here looking for ways to flatten real-world nested JSON data which can have nested key-value json objects and arrays and json objects inside the arrays and so on. JSON doesn't include tuples, so we don't have to fret over those.
I found an implementation of the list-inclusion comment by @roneo to the answer posted by @Imran :
https://github.com/ScriptSmith/socialreaper/blob/master/socialreaper/tools.py#L8
import collections
def flatten(dictionary, parent_key=False, separator='.'):
"""
Turn a nested dictionary into a flattened dictionary
:param dictionary: The dictionary to flatten
:param parent_key: The string to prepend to dictionary's keys
:param separator: The string used to separate flattened keys
:return: A flattened dictionary
"""
items = []
for key, value in dictionary.items():
new_key = str(parent_key) + separator + key if parent_key else key
if isinstance(value, collections.MutableMapping):
items.extend(flatten(value, new_key, separator).items())
elif isinstance(value, list):
for k, v in enumerate(value):
items.extend(flatten({str(k): v}, new_key).items())
else:
items.append((new_key, value))
return dict(items)
Test it:
flatten({'a': 1, 'c': {'a': 2, 'b': {'x': 5, 'y' : 10}}, 'd': [1, 2, 3] })
>> {'a': 1, 'c.a': 2, 'c.b.x': 5, 'c.b.y': 10, 'd.0': 1, 'd.1': 2, 'd.2': 3}
Annd that does the job I need done: I throw any complicated json at this and it flattens it out for me.
All credits to https://github.com/ScriptSmith .
Currently EF 7 or EF Core does not support the old method of importing Stored procedures in designer and calling them directly. You can have a look at the roadmap to see what is going to be supported in the future: EF core roadmap.
So for now it is better to use SqlConnection to call stored procedures or any raw query, since you do not need the entire EF for this job. Here are two examples:
Call stored procedure that return single value. String in this case.
CREATE PROCEDURE [dbo].[Test]
@UserName nvarchar(50)
AS
BEGIN
SELECT 'Name is: '+@UserName;
END
Call stored procedure that return a list.
CREATE PROCEDURE [dbo].[TestList]
AS
BEGIN
SELECT [UserName], [Id] FROM [dbo].[AspNetUsers]
END
To call these stored procedure it is better to create static class that holds all of these functions, for example, I called it DataAccess class, as follows:
public static class DataAccess
{
private static string connectionString = ""; //Your connection string
public static string Test(String userName)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("dbo.Test", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// 3. add parameter to command, which will be passed to the stored procedure
cmd.Parameters.Add(new SqlParameter("@UserName", userName));
// execute the command
using (var rdr = cmd.ExecuteReader())
{
if (rdr.Read())
{
return rdr[0].ToString();
}
else
{
return null;
}
}
}
}
public static IList<Users> TestList()
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
// 1. create a command object identifying the stored procedure
SqlCommand cmd = new SqlCommand("dbo.TestList", conn);
// 2. set the command object so it knows to execute a stored procedure
cmd.CommandType = CommandType.StoredProcedure;
// execute the command
using (var rdr = cmd.ExecuteReader())
{
IList<Users> result = new List<Users>();
//3. Loop through rows
while (rdr.Read())
{
//Get each column
result.Add(new Users() { UserName = (string)rdr.GetString(0), Id = rdr.GetString(1) });
}
return result;
}
}
}
}
And Users class is like this:
public class Users
{
public string UserName { set; get; }
public string Id { set; get; }
}
By the way you do not need to worry about the performance of opening and closing a connection for every request to sql as the asp.net is taking care of managing these for you. And I hope this was helpful.
Here is an example of a parent List react component and whos props contain a react element. In this case, just a single Link react component is passed in (as seen in the dom render).
class Link extends React.Component {
constructor(props){
super(props);
}
render(){
return (
<div>
<p>{this.props.name}</p>
</div>
);
}
}
class List extends React.Component {
render(){
return(
<div>
{this.props.element}
{this.props.element}
</div>
);
}
}
ReactDOM.render(
<List element = {<Link name = "working"/>}/>,
document.getElementById('root')
);
i had this problem yesterday. can you folow the local path in windows explorer?
(C:\users\..\AndroidStudioProjects\SharedPreferencesDemoProject\SharedPreferencesDemo\build\apk\)
i had to manually create the 'apk' directory in '\build', then the problem was fixed
Use the "form" attribute, if you want to save your markup:
<form method="GET" id="my_form"></form>
<table>
<tr>
<td>
<input type="text" name="company" form="my_form" />
<button type="button" form="my_form">ok</button>
</td>
</tr>
</table>
(*Form fields outside of the < form > tag)
The Dim keyword is optional, when we are using it with modifiers- Public, Protected, Friend, Protected Friend,Private,Shared,Shadows,Static,ReadOnly etc.
e.g. - Static nTotal As Integer
For reference type, we have to use new keyword to create the new instance of the class or structure. e.g. Dim lblTop As New System.Windows.Forms.Label
.
Dim statement can be used with out a datatype when you set Option Infer to On. In that case the compiler infers the data type of a variable from the type of its initialization expression. Example :
Option Infer On
Module SampleMod
Sub Main()
Dim nExpVar = 5
The above statement is equivalent to- Dim nExpVar As Integer