I had this line in my code
weakSelf?.notifications = weakSelf?.notifications ?? [] + weakSelf?.chatNotificationDataSource ?? []
this cause Segmentation fault. But then i changed it in this way:
weakSelf?.notifications = (weakSelf?.notifications ?? []) + (weakSelf?.chatNotificationDataSource ?? [])
and app started working.
Google deprecated the Android AsyncTask API in Android 11, even if you create a thread class outside the main activity, just by calling it in main you will get the same error, the calls must be inside a runnable thread, but if you need some asynchronous code to execute on the background or some on post afterwards here you can check out some alternatives for both Kotlin and Java
https://stackoverflow.com/questions/58767733/android-asynctask-api-deprecating-in-android-11-what-are-the-alternatives
the one that worked for me specifically was an answer by mayank1513 for a java 8 implementation of runnable thread found on the above link, code is as follows
new Thread(() -> {
// do background stuff here
runOnUiThread(()->{
// OnPostExecute stuff here
});
}).start();
However you can define the thread first in some part of your code and start it somewhere else like this
thread definition
Thread thread = new Thread(() -> {
// do background stuff here
runOnUiThread(()->{
// OnPostExecute stuff here
});
});
thread call
thread.start();
hope this saves someone the headache of seeing deprecated AsyncTask
There is another scenario where this issue reproduces (as in my case). When THE CLIENT REQUEST doesn't contain the right extension on the url, the controller can't identify the desired result format.
For example: the controller is set to respond_to :json
(as a single option, without a HTML response)- while the client call is set to /reservations
instead of /reservations.json
.
Bottom line, change the client call to /reservations.json
.
The solution that work for me is the following:
$("#spanId").text("text to show");
In your pom.xml you should add distributionManagement configuration to where to deploy.
In the following example I have used file system as the locations.
<distributionManagement>
<repository>
<id>internal.repo</id>
<name>Internal repo</name>
<url>file:///home/thara/testesb/in</url>
</repository>
</distributionManagement>
you can add another location while deployment by using the following command (but to avoid above error you should have at least 1 repository configured) :
mvn deploy -DaltDeploymentRepository=internal.repo::default::file:///home/thara/testesb/in
I found the better control would be using scalefnt package:
\usepackage{scalefnt}
...
{\scalefont{0.5}
\begin{tikzpicture}
...
\end{tikzpicture}
}
There's an amazing type test operator in XPath 2.0 you can use:
<xsl:if test="$number castable as xs:double">
<!-- implementation -->
</xsl:if>
Let me add an example here:
I'm trying to build Alluxio
on windows platform and got the same issue, it's because the pom.xml
contains below step:
<plugin>
<artifactId>exec-maven-plugin</artifactId>
<groupId>org.codehaus.mojo</groupId>
<inherited>false</inherited>
<executions>
<execution>
<id>Check that there are no Windows line endings</id>
<phase>compile</phase>
<goals>
<goal>exec</goal>
</goals>
<configuration>
<executable>${build.path}/style/check_no_windows_line_endings.sh</executable>
</configuration>
</execution>
</executions>
</plugin>
The .sh
file is not executable on windows so the error throws.
Comment it out if you do want build Alluxio
on windows.
React Router V5
If you want the pathName as a string ('/' or 'users'), you can use the following:
// React Hooks: React Router DOM
let history = useHistory();
const location = useLocation();
const pathName = location.pathname;
You can do it. That is what big guys do as well.
First query:
» host google.com
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
Next query:
» host google.com
google.com has address 74.125.232.224
google.com has address 74.125.232.225
google.com has address 74.125.232.226
google.com has address 74.125.232.227
google.com has address 74.125.232.228
google.com has address 74.125.232.229
google.com has address 74.125.232.230
google.com has address 74.125.232.231
google.com has address 74.125.232.232
google.com has address 74.125.232.233
google.com has address 74.125.232.238
As you see, the list of IPs rotated around, but the relative order between two IPs stayed the same.
Update: I see several comments bragging about how DNS round-robin is not convenient for fail-over, so here is the summary: DNS is not for fail-over. So it is obviously not good for fail-over. It was never designed to be a solution for fail-over.
You can just rewrite it as:
int qempty(){ return(f==r);}
Which does the same thing as said in the other answers.
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>3.0.0.RELEASE</version>
</dependency>
The photos
property is an optional array and must be unwrapped before accessing its elements (the same as you do to get the count
property of the array):
for var i = 0; i < userPhotos!.count ; ++i {
let url = userPhotos![i].url
}
function GetDays($sStartDate, $sEndDate){
// Firstly, format the provided dates.
// This function works best with YYYY-MM-DD
// but other date formats will work thanks
// to strtotime().
$sStartDate = gmdate("Y-m-d", strtotime($sStartDate));
$sEndDate = gmdate("Y-m-d", strtotime($sEndDate));
// Start the variable off with the start date
$aDays[] = $sStartDate;
// Set a 'temp' variable, sCurrentDate, with
// the start date - before beginning the loop
$sCurrentDate = $sStartDate;
// While the current date is less than the end date
while($sCurrentDate < $sEndDate){
// Add a day to the current date
$sCurrentDate = gmdate("Y-m-d", strtotime("+1 day", strtotime($sCurrentDate)));
// Add this new day to the aDays array
$aDays[] = $sCurrentDate;
}
// Once the loop has finished, return the
// array of days.
return $aDays;
}
use like
GetDays('2007-01-01', '2007-01-31');
In addition to the other answers here showing you how to git checkout <the-hash-you-want>
it's worth knowing you can switch back to where you were using:
git checkout @{-1}
This is often more convenient than:
git checkout what-was-that-original-branch-called-again-question-mark
As you might anticipate, git checkout @{-2}
will take you back to the branch you were at two git checkout
s ago, and similarly for other numbers. If you can remember where you were for bigger numbers, you should get some kind of medal for that.
Sadly for productivity, git checkout @{1}
does not take you to the branch you will be on in future, which is a shame.
Yes, it is possible as follows. These colours can be used in a console application to view some errors in red, etc.
Console.BackgroundColor = ConsoleColor.Blue;
Console.ForegroundColor = ConsoleColor.White;//after this line every text will be white on blue background
Console.WriteLine("White on blue.");
Console.WriteLine("Another line.");
Console.ResetColor();//reset to the defoult colour
The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest
rather than NSURLRequest
. In its current form, I couldn't get it to respond to the setHTTPMethod
call. Changing the type fixed things right up.
As an addition to mklement0's excellent answer:
Almost all executables accept \"
as an escaped "
. Safe usage in cmd however is almost only possible using DELAYEDEXPANSION.
To explicitely send a literal "
to some process, assign \"
to an environment variable, and then use that variable, whenever you need to pass a quote. Example:
SETLOCAL ENABLEDELAYEDEXPANSION
set q=\"
child "malicious argument!q!&whoami"
Note SETLOCAL ENABLEDELAYEDEXPANSION
seems to work only within batch files. To get DELAYEDEXPANSION in an interactive session, start cmd /V:ON
.
If your batchfile does't work with DELAYEDEXPANSION, you can enable it temporarily:
::region without DELAYEDEXPANSION
SETLOCAL ENABLEDELAYEDEXPANSION
::region with DELAYEDEXPANSION
set q=\"
echoarg.exe "ab !q! & echo danger"
ENDLOCAL
::region without DELAYEDEXPANSION
If you want to pass dynamic content from a variable that contains quotes that are escaped as ""
you can replace ""
with \"
on expansion:
SETLOCAL ENABLEDELAYEDEXPANSION
foo.exe "danger & bar=region with !dynamic_content:""=\"! & danger"
ENDLOCAL
This replacement is not safe with %...%
style expansion!
In case of OP bash -c "g++-linux-4.1 !v_params:"=\"!"
is the safe version.
If for some reason even temporarily enabling DELAYEDEXPANSION is not an option, read on:
Using \"
from within cmd is a little bit safer if one always needs to escape special characters, instead of just sometimes. (It's less likely to forget a caret, if it's consistent...)
To achieve this, one precedes any quote with a caret (^"
), quotes that should reach the child process as literals must additionally be escaped with a backlash (\^"
). ALL shell meta characters must be escaped with ^
as well, e.g. &
=> ^&
; |
=> ^|
; >
=> ^>
; etc.
Example:
child ^"malicious argument\^"^&whoami^"
Source: Everyone quotes command line arguments the wrong way, see "A better method of quoting"
To pass dynamic content, one needs to ensure the following:
The part of the command that contains the variable must be considered "quoted" by cmd.exe
(This is impossible if the variable can contain quotes - don't write %var:""=\"%
). To achieve this, the last "
before the variable and the first "
after the variable are not ^
-escaped. cmd-metacharacters between those two "
must not be escaped. Example:
foo.exe ^"danger ^& bar=\"region with %dynamic_content% & danger\"^"
This isn't safe, if %dynamic_content%
can contain unmatched quotes.
Updated answer for ES6+ is here.
arr = [1, 2, 3];
arr.forEach(function(i, idx, array){
if (idx === array.length - 1){
console.log("Last callback call at index " + idx + " with value " + i );
}
});
would output:
Last callback call at index 2 with value 3
The way this works is testing arr.length
against the current index of the array, passed to the callback function.
The way I achieve this is with the object.assign
function
const defaultProperties = { 'foo': 'bar', 'bar': 'foo' };
const overwriteProperties = { 'foo': 'foo' };
const newObj = Object.assign({}, defaultProperties, overwriteProperties);
console.log(defaultProperties); // {"foo": "bar", "bar": "foo"}
console.log(overwriteProperties); // { "foo": "foo" };
console.log(newObj); // { "foo": "foo", "bar": "foo" }
Seems like I can just set the CSS for the select
in Chrome directly. CSS and HTML code provided below :
.boldoption {_x000D_
font-weight: bold;_x000D_
}
_x000D_
<select>_x000D_
<option>Some normal-font option</option>_x000D_
<option>Another normal-font option</option>_x000D_
<option class="boldoption">Some bold option</option>_x000D_
</select>
_x000D_
SELECT id, GROUP_CONCAT(CAST(name as CHAR)) FROM table GROUP BY id
Will give you a comma-delimited string
If you want to call a function from another go file and you are using Goland, then find the option 'Edit configuration' from the Run menu and change the run kind from File to Directory. It clears all the errors and allows you to call functions from other go files.
This is an IndexError
in python, which means that we're trying to access an index which isn't there in the tensor. Below is a very simple example to understand this error.
# create an empty array of dimension `0`
In [14]: arr = np.array([], dtype=np.int64)
# check its shape
In [15]: arr.shape
Out[15]: (0,)
with this array arr
in place, if we now try to assign any value to some index, for example to the index 0
as in the case below
In [16]: arr[0] = 23
Then, we will get an IndexError
, as below:
IndexError Traceback (most recent call last) <ipython-input-16-0891244a3c59> in <module> ----> 1 arr[0] = 23 IndexError: index 0 is out of bounds for axis 0 with size 0
The reason is that we are trying to access an index (here at 0th position), which is not there (i.e. it doesn't exist because we have an array of size 0
).
In [19]: arr.size * arr.itemsize
Out[19]: 0
So, in essence, such an array is useless and cannot be used for storing anything. Thus, in your code, you've to follow the traceback and look for the place where you're creating an array/tensor of size 0
and fix that.
This probably isn't the most elegant way to do it, but it gets the job done.
In[1]: import numpy as np
In[2]: import pandas as pd
In[3]: df = pd.DataFrame(np.genfromtxt('/Users/spencerlyon2/Desktop/test.csv', dtype=str)[1:], columns=['ID'])
In[4]: df
Out[4]:
ID
0 00013007854817840016671868
1 00013007854817840016749251
2 00013007854817840016754630
3 00013007854817840016781876
4 00013007854817840017028824
5 00013007854817840017963235
6 00013007854817840018860166
Just replace '/Users/spencerlyon2/Desktop/test.csv'
with the path to your file
Instead of using a dot, like: 1.2, try to input like this: 1,2.
Something like this?
function delete_folder($folder) {
$glob = glob($folder);
foreach ($glob as $g) {
if (!is_dir($g)) {
unlink($g);
} else {
delete_folder("$g/*");
rmdir($g);
}
}
}
In Swift, I'm using:
In my Macros.swift I just added
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = __FUNCTION__, file: String = __FILE__, line: Int = __LINE__){
println("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
you can now just call anywhere
TICK()
// your code to be tracked
TOCK()
Swift 5.0
var startTime = NSDate()
func TICK(){ startTime = NSDate() }
func TOCK(function: String = #function, file: String = #file, line: Int = #line){
print("\(function) Time: \(startTime.timeIntervalSinceNow)\nLine:\(line) File: \(file)")
}
In Xcode 4.x press
(or click Menubar
> Product
> Scheme
> Edit Scheme
)
select the "Diagnostics" tab and click "Enable Zombie Objects":
This turns released objects into NSZombie instances that print console warnings when used again. This is a debugging aid that increases memory use (no object is really released) but improves error reporting.
A typical case is when you over-release an object and you don't know which one:
-[UITableView release]: message sent to deallocated instance
This Xcode setting is ignored when you archive the application for App Store submission. You don't need to touch anything before releasing your application.
Pressing ??R is the same as selecting Product > Run while keeping the Alt key pressed.
Clicking the "Enable Zombie Objects" checkbox is the same as manually adding "NSZombieEnabled = YES" in the section "Environment Variables" of the tab Arguments.
Github's libgit2 binding, pygit2 provides a one-liner cloning a remote directory:
clone_repository(url, path,
bare=False, repository=None, remote=None, checkout_branch=None, callbacks=None)
Array.forEach
is meant for computing stuff not waiting, and there is nothing to be gained making computations asynchronous in an event loop (webworkers add multiprocessing, if you need multi-core computation). If you want to wait for multiple tasks to end, use a counter, which you can wrap in a semaphore class.
The code for word-wrapping (breaking at spaces) provided by @Gaby Petrioli is very helpful.
I've extended his code to provide support for newline characters \n
. Also, often times it's useful to have the dimensions of the bounding box, so multiMeasureText()
returns both the width and the height.
You can see the code here: http://jsfiddle.net/jeffchan/WHgaY/76/
For Finding All the ChildNodes you can use the below Snippet
List<WebElement> childs = MyCurrentWebElement.findElements(By.xpath("./child::*"));
for (WebElement e : childs)
{
System.out.println(e.getTagName());
}
Note that this will give all the Child Nodes at same level -> Like if you have structure like this :
<Html>
<body>
<div> ---suppose this is current WebElement
<a>
<a>
<img>
<a>
<img>
<a>
It will give me tag names of 3 anchor tags here only . If you want all the child Elements recursively , you can replace the above code with MyCurrentWebElement.findElements(By.xpath(".//*"));
Hope That Helps !!
Try putting it inside a form tag and closing the input tag:
<form>
<input type = "text" class = "txtPost" placeholder = "Post a question?" required />
<button class = "btnPost btnBlue">Post</button>
</form>
It's O(V+E) because each visit to v of V must visit each e of E where |e| <= V-1. Since there are V visits to v of V then that is O(V). Now you have to add V * |e| = E => O(E). So total time complexity is O(V + E).
C99 is available online. Quoted from www.open-std.org:
The lastest publically available version of the standard is the combined C99 + TC1 + TC2 + TC3, WG14 N1256, dated 2007-09-07. This is a WG14 working paper, but it reflects the consolidated standard at the time of issue.
I found a pretty well put explanation of atomic and non-atomic properties here. Here's some relevant text from the same:
'atomic' means it cannot be broken down. In OS/programming terms an atomic function call is one that cannot be interrupted - the entire function must be executed, and not swapped out of the CPU by the OS's usual context switching until it's complete. Just in case you didn't know: since the CPU can only do one thing at a time, the OS rotates access to the CPU to all running processes in little time-slices, to give the illusion of multitasking. The CPU scheduler can (and does) interrupt a process at any point in its execution - even in mid function call. So for actions like updating shared counter variables where two processes could try to update the variable at the same time, they must be executed 'atomically', i.e., each update action has to finish in its entirety before any other process can be swapped onto the CPU.
So I'd be guessing that atomic in this case means the attribute reader methods cannot be interrupted - in effect meaning that the variable(s) being read by the method cannot change their value half way through because some other thread/call/function gets swapped onto the CPU.
Because the atomic
variables can not be interrupted, the value contained by them at any point is (thread-lock) guaranteed to be uncorrupted, although, ensuring this thread lock makes access to them slower. non-atomic
variables, on the other hand, make no such guarantee but do offer the luxury of quicker access. To sum it up, go with non-atomic
when you know your variables won't be accessed by multiple threads simultaneously and speed things up.
Have only tried this on Mac:
run this command:
mongod --dbpath ~/path/to/your/app/data
You should be good to go!
@JavisPerez -- Is there any way to compress that image to 150kb at least? Is that possible? What ImageMagick options can I use?
See the following links where there is an option in ImageMagick to specify the desired output file size for writing to JPG files.
http://www.imagemagick.org/Usage/formats/#jpg_write http://www.imagemagick.org/script/command-line-options.php#define
-define jpeg:extent={size}
As of IM v6.5.8-2 you can specify a maximum output filesize for the JPEG image. The size is specified with a suffix. For example "400kb".
convert image.jpg -define jpeg:extent=150kb result.jpg
You will lose some quality by decompressing and recompressing in addition to any loss due to lowering -quality value from the input.
As per CI Docs we can use the following,
$this->db->where('account_status', $i); // OTHER CONDITIONS IF ANY
$this->db->from('account_status'); //TABLE NAME
echo $this->db->count_all_results();
If we want to get total rows in the table without any condition, simple use
echo $this->db->count_all_results('table_name'); // returns total_rows presented in the table
Best way to pass data from child to parent component
child component
handleLanguageCode=()=>(langValue) {
this.props.sendDatatoParent(langValue)
}
Parent
<Parent sendDatatoParent={ data => this.setState({item: data}) } />;
Use:
setTimeout(startTimer,startInterval);
You're calling startTimer() and feed it's result (which is undefined) as an argument to setTimeout().
Write a script with two curl requests in desired order and run it by cron, like
#!/bin/bash
curl http://mysite.com/?update_=1
curl http://mysite.com/?the_other_thing
With data.table, the solutions is:
DT[, idnat2 := ifelse(idbp %in% "foreign", "foreign",
ifelse(idbp %in% c("colony", "overseas"), "overseas", "mainland" ))]
The ifelse
is vectorized. The if-else
is not. Here, DT is:
idnat idbp
1 french mainland
2 french colony
3 french overseas
4 foreign foreign
This gives:
idnat idbp idnat2
1: french mainland mainland
2: french colony overseas
3: french overseas overseas
4: foreign foreign foreign
SELECT DATEDIFF(NOW(),pickup_date) AS noofday
FROM cir_order
WHERE DATEDIFF(NOW(),pickup_date)>2;
or
SELECT *
FROM cir_order
WHERE cir_order.`cir_date` >= DATE_ADD( CURDATE(), INTERVAL -10 DAY )
I have had the same issue in Ubuntu 14.04.01 when I tried to install JDK 8 and Netbeans if I launch the script inside a Byobu terminal (maybe with Screens happens the same).
Just exit Byobu and (in a graphical terminal) run the script.
Try this. Don't forget using System.Reflection
.
string baseDir = System.IO.Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
Swift 4
func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
let delete = UIContextualAction(style: .destructive, title: "Delete") { (action, sourceView, completionHandler) in
print("index path of delete: \(indexPath)")
completionHandler(true)
}
let rename = UIContextualAction(style: .normal, title: "Edit") { (action, sourceView, completionHandler) in
print("index path of edit: \(indexPath)")
completionHandler(true)
}
let swipeActionConfig = UISwipeActionsConfiguration(actions: [rename, delete])
swipeActionConfig.performsFirstActionWithFullSwipe = false
return swipeActionConfig
}
It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:
axs.set_ylabel('mylabel',size=6)
you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.
def set_pubfig:
sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})
Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.
Note: If you specify these numbers, specifying font_scale
in sns.set_context
is ignored for all specified font elements, even if you set it.
It's like copy semantics, but instead of having to duplicate all of the data you get to steal the data from the object being "moved" from.
I suggest a LinkedHashMap
or a TreeMap
. A LinkedHashMap
keeps the keys in the order they were inserted, while a TreeMap
is kept sorted via a Comparator
or the natural Comparable
ordering of the elements.
Since it doesn't have to keep the elements sorted, LinkedHashMap
should be faster for most cases; TreeMap
has O(log n)
performance for containsKey
, get
, put
, and remove
, according to the Javadocs, while LinkedHashMap
is O(1)
for each.
If your API that only expects a predictable sort order, as opposed to a specific sort order, consider using the interfaces these two classes implement, NavigableMap
or SortedMap
. This will allow you not to leak specific implementations into your API and switch to either of those specific classes or a completely different implementation at will afterwards.
In Window->Preferences->General->Startup and Shutdown->Workspaces, make sure that 'Prompt for Workspace on startup' is checked.
Then close eclipse and reopen.
Then you'll be prompted for a workspace to open. You can create a new workspace from that dialogue.
Or File->Switch Workspace->Other...
I don't know if maybe it's a difference in Excel version but this question is 6 years old and the accepted answer didn't help me so this is what I figured out:
Under Conditional Formatting > Manage Rules:
$A2<$B2
$B$2:$B$100
(assuming you have 100 rows)This worked for me in Excel 2016.
Use the load
event:
img = new Image();
img.onload = function(){
// image has been loaded
};
img.src = image_url;
Also have a look at:
create table my_table (
column_a integer not null,
column_b integer not null,
column_c varchar(50),
primary key (column_a, column_b)
);
Step 1: open your mysql workbench application select table. choose image cell right click select "Open value in Editor"
Step 2: click on the load button and choose image file
Step 3:then click apply button
Step 4: Then apply the query to save the image .Don't forgot image data type is "BLOB". Step 5: You can can check uploaded image
This is my function. JavaScript must be under PHP otherwise use SESSION.
<?php
$phpArray=array(1,2,3,4,5,6);
?>
<div id="arrayCon" style="width:300px;"></div>
<script type="text/javascript">
var jsArray = new Array();
<?php
$numArray=count($phpArray);
for($i=0;$i<$numArray;$i++){
echo "jsArray[$i] = ". $phpArray[$i] . ";\n";
}
?>
$("#arrayCon").text(jsArray[1]);
</script>
Last row can be ....text(jsArray); and will be shown "1,2,3,4,5,6"
We can check error & 404 statusCode, and use try {} catch (err) {}
.
You can try this :
const req = new XMLHttpRequest();_x000D_
req.onreadystatechange = function() {_x000D_
if (req.status == 404) {_x000D_
console.log("404");_x000D_
return false;_x000D_
}_x000D_
_x000D_
if (!(req.readyState == 4 && req.status == 200))_x000D_
return false;_x000D_
_x000D_
const json = (function(raw) {_x000D_
try {_x000D_
return JSON.parse(raw);_x000D_
} catch (err) {_x000D_
return false;_x000D_
}_x000D_
})(req.responseText);_x000D_
_x000D_
if (!json)_x000D_
return false;_x000D_
_x000D_
document.body.innerHTML = "Your city : " + json.city + "<br>Your isp : " + json.org;_x000D_
};_x000D_
req.open("GET", "https://ipapi.co/json/", true);_x000D_
req.send();
_x000D_
Read more :
If anyone else runs into this, the issue we had was that we were making the ajax request from a link, and not preventing the link from being followed. So if you are doing this in an onclick
attribute, make sure to return false;
as well.
next
- it's like return
, but for blocks! (So you can use this in any proc
/lambda
too.)
That means you can also say next n
to "return" n
from the block. For instance:
puts [1, 2, 3].map do |e|
next 42 if e == 2
e
end.inject(&:+)
This will yield 46
.
Note that return
always returns from the closest def
, and never a block; if there's no surrounding def
, return
ing is an error.
Using return
from within a block intentionally can be confusing. For instance:
def my_fun
[1, 2, 3].map do |e|
return "Hello." if e == 2
e
end
end
my_fun
will result in "Hello."
, not [1, "Hello.", 2]
, because the return
keyword pertains to the outer def
, not the inner block.
If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user
, picked from your example), then the syntax is quite simple:
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin('a.user', 'u')
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
Since you are applying a condition on the joined result here, using a LEFT JOIN
or simply JOIN
is the same.
If no association is available, then the query looks like following
public function getHistory($users) {
$qb = $this->entityManager->createQueryBuilder();
$qb
->select('a', 'u')
->from('Credit\Entity\UserCreditHistory', 'a')
->leftJoin(
'User\Entity\User',
'u',
\Doctrine\ORM\Query\Expr\Join::WITH,
'a.user = u.id'
)
->where('u = :user')
->setParameter('user', $users)
->orderBy('a.created_at', 'DESC');
return $qb->getQuery()->getResult();
}
This will produce a resultset that looks like following:
array(
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
array(
0 => UserCreditHistory instance,
1 => Userinstance,
),
// ...
)
// Convert the float to a string
// We might use stringstream, but it looks like it truncates the float to only
//5 decimal points (maybe that's what you want anyway =P)
float MyFloat = 5.11133333311111333;
float NewConvertedFloat = 0.0;
string FirstString = " ";
string SecondString = " ";
stringstream ss (stringstream::in | stringstream::out);
ss << MyFloat;
FirstString = ss.str();
// Take out how ever many decimal places you want
// (this is a string it includes the point)
SecondString = FirstString.substr(0,5);
//whatever precision decimal place you want
// Convert it back to a float
stringstream(SecondString) >> NewConvertedFloat;
cout << NewConvertedFloat;
system("pause");
It might be an inefficient dirty way of conversion but heck, it works lol. And it's good, because it applies to the actual float. Not just affecting the output visually.
If you are using DataGrip you can do the following:
SELECT * FROM <your_table>;
*
and press Alt+Enter
Expand column list
option*
with full list of columnsNULL
is a value that is valid for any pointer type. It represents the absence of a value.
A void pointer is a type. Any pointer type is convertible to a void pointer hence it can point to any value. This makes it good for general storage but bad for use. By itself it cannot be used to access a value. The program must have extra context to understand the type of value the void pointer refers to before it can access the value.
For Chart.js 2.x refer to andyhasit's answer - https://stackoverflow.com/a/36954319/360067
For Chart.js 1.x, you can tweak the options and extend the chart type to do this, like so
Chart.types.Line.extend({
name: "LineAlt",
draw: function () {
Chart.types.Line.prototype.draw.apply(this, arguments);
var ctx = this.chart.ctx;
ctx.save();
// text alignment and color
ctx.textAlign = "center";
ctx.textBaseline = "bottom";
ctx.fillStyle = this.options.scaleFontColor;
// position
var x = this.scale.xScalePaddingLeft * 0.4;
var y = this.chart.height / 2;
// change origin
ctx.translate(x, y);
// rotate text
ctx.rotate(-90 * Math.PI / 180);
ctx.fillText(this.datasets[0].label, 0, 0);
ctx.restore();
}
});
calling it like this
var ctx = document.getElementById("myChart").getContext("2d");
var myLineChart = new Chart(ctx).LineAlt(data, {
// make enough space on the right side of the graph
scaleLabel: " <%=value%>"
});
Notice the space preceding the label value, this gives us space to write the y axis label without messing around with too much of Chart.js internals
Fiddle - http://jsfiddle.net/wyox23ga/
Java <= 6.x just allows you to catch one exception for each catch block:
try {
} catch (ExceptionType name) {
} catch (ExceptionType name) {
}
Documentation:
Each catch block is an exception handler and handles the type of exception indicated by its argument. The argument type, ExceptionType, declares the type of exception that the handler can handle and must be the name of a class that inherits from the Throwable class.
For Java 7 you can have multiple Exception caught on one catch block:
catch (IOException|SQLException ex) {
logger.log(ex);
throw ex;
}
Documentation:
In Java SE 7 and later, a single catch block can handle more than one type of exception. This feature can reduce code duplication and lessen the temptation to catch an overly broad exception.
Reference: http://docs.oracle.com/javase/tutorial/essential/exceptions/catch.html
<input type="password" autocomplete="off" />
I'd just like to add that as a user I think this is very annoying and a hassle to overcome. I strongly recommend against using this as it will more than likely aggravate your users.
Passwords are already not stored in the MRU, and correctly configured public machines will not even save the username.
In Xcode, select Target -> Capabilities, and check "Outgoing Connections (Client)" to enable App Sandbox.
Use a white space to match all descendants of an element:
div.dropdown * {
color: red;
}
x y
matches every element y that is inside x, however deeply nested it may be - children, grandchildren and so on.
The asterisk *
matches any element.
Official Specification: CSS 2.1: Chapter 5.5: Descendant Selectors
#include <iostream>
#include <string>
#include <vector>
#include <boost/assign/list_of.hpp>
int main()
{
const std::vector< std::string > v = boost::assign::list_of( "abc" )( "xyz" );
std::copy(
v.begin(),
v.end(),
std::ostream_iterator< std::string >( std::cout, "\n" ) );
}
On Arrays, look for:
JSONArray menuitemArray = popupObject.getJSONArray("menuitem");
You can add + behind the variable and it will force it to be an integer
var dots = 5
function increase(){
dots = +dots + 5;
}
Use this:
public void ShowAllPostBackData()
{
if (IsPostBack)
{
string[] keys = Request.Form.AllKeys;
Literal ctlAllPostbackData = new Literal();
ctlAllPostbackData.Text = "<div class='well well-lg' style='border:1px solid black;z-index:99999;position:absolute;'><h3>All postback data:</h3><br />";
for (int i = 0; i < keys.Length; i++)
{
ctlAllPostbackData.Text += "<b>" + keys[i] + "</b>: " + Request[keys[i]] + "<br />";
}
ctlAllPostbackData.Text += "</div>";
this.Controls.Add(ctlAllPostbackData);
}
}
Here's a script that will use the Google API to acquire the users postal code and populate an input field.
function postalCodeLookup(input) {
var head= document.getElementsByTagName('head')[0],
script= document.createElement('script');
script.src= '//maps.googleapis.com/maps/api/js?sensor=false';
head.appendChild(script);
script.onload = function() {
if (navigator.geolocation) {
var a = input,
fallback = setTimeout(function () {
fail('10 seconds expired');
}, 10000);
navigator.geolocation.getCurrentPosition(function (pos) {
clearTimeout(fallback);
var point = new google.maps.LatLng(pos.coords.latitude, pos.coords.longitude);
new google.maps.Geocoder().geocode({'latLng': point}, function (res, status) {
if (status == google.maps.GeocoderStatus.OK && typeof res[0] !== 'undefined') {
var zip = res[0].formatted_address.match(/,\s\w{2}\s(\d{5})/);
if (zip) {
a.value = zip[1];
} else fail('Unable to look-up postal code');
} else {
fail('Unable to look-up geolocation');
}
});
}, function (err) {
fail(err.message);
});
} else {
alert('Unable to find your location.');
}
function fail(err) {
console.log('err', err);
a.value('Try Again.');
}
};
}
You can adjust accordingly to acquire different information. For more info, check out the Google Maps API documentation.
git status #then file which you need to push git add example.FileExtension
git commit "message is example"
git push -u origin(or whatever name you used) master(or name of some branch where you want to push it)
bool in_array ( mixed $needle , array $haystack [, bool $strict = FALSE ] )
Another use of in_array in_array() with an array as needle
<?php
$a = array(array('p', 'h'), array('p', 'r'), 'o');
if (in_array(array('p', 'h'), $a)) {
echo "'ph' was found\n";
}
if (in_array(array('f', 'i'), $a)) {
echo "'fi' was found\n";
}
if (in_array('o', $a)) {
echo "'o' was found\n";
}
?>
With a default option having selected attribute
<select>
<option value="" selected>Choose your city</option>
<option value ="sydney">Sydney</option>
<option value ="melbourne">Melbourne</option>
<option value ="cromwell">Cromwell</option>
<option value ="queenstown">Queenstown</option>
</select>
I think you meant to do url[i] <- paste(...
instead of url[i] = paste(...
. If so replace =
with <-
.
Just for the record as it might help others who are on shared hosting (cPanel).
I had error on shared hosting php7.2: Module 'imagick' already loaded in Unknown on line 0
In the beginning hosting provider said it was my bad configuration (running Yii2.16). But after I showed them, that all Internet related this issue to server configuration -they started to listen to me. After I proved, that there was no error on php7.1 they started to search for the error.
As they told to me - the error was due to configuration in PERL modules or PEAR package, but they did not told me the real issue.
So, if you are on shared hosting - talk to you provider and experiment with PHP versions (if you can change them).
I spent the better part of a day struggling without success to get the simplest Spring.NET example working. Could never figure out how to get it to find my assembly from the XML file. In about 2 hours, on the other hand, I was able to get Ninject working, including testing integration with both NUnit and MSTest.
There are two answers above up-to-now and they are both long (and tl;dr too short IMHO), so I write summary from my experience starting to use new java.time library (applicable as noted in other answers to Java version 8+). ISO 8601 sets standard way to write dates: YYYY-MM-DD
so the format of date-time is only as below (could be 0, 3, 6 or 9 digits for milliseconds) and no formatting string necessary:
import java.time.Instant;
public static void main(String[] args) {
String date="2010-10-02T12:23:23Z";
try {
Instant myDate = Instant.parse(date);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
I did not need it, but as getting year is in code from the question, then:
it is trickier, cannot be done from Instant
directly, can be done via Calendar
in way of questions Get integer value of the current year in Java and Converting java.time to Calendar but IMHO as format is fixed substring is more simple to use:
myDate.toString().substring(0,4);
router.navigate
is just a convenience method that wraps router.navigateByUrl
, it boils down to:
navigate(commands: any[], extras) {
return router.navigateByUrl(router.createUrlTree(commands, extras), extras);
}
As mentioned in other answers router.navigateByUrl
will only accept absolute URLs:
// This will work
router.navigateByUrl("http://localhost/team/33/user/11")
// This WON'T work even though relativeTo parameter is in the signature
router.navigateByUrl("../22", {relativeTo: route})
All the relative calculations are done by router.createUrlTree
and router.navigate
. Array syntax is used to treat every array element as a URL modifying "command". E.g. ".."
- go up, "path"
- go down, {expand: true}
- add query param, etc.. You can use it like this:
// create /team/33/user/11
router.navigate(['/team', 33, 'user', 11]);
// assuming the current url is `/team/33/user/11` and the route points to `user/11`
// navigate to /team/33/user/11/details
router.navigate(['details'], {relativeTo: route});
// navigate to /team/33/user/22
router.navigate(['../22'], {relativeTo: route});
// navigate to /team/44/user/22
router.navigate(['../../team/44/user/22'], {relativeTo: route});
That {relativeTo: route}
parameter is important as that's what router will use as the root for relative operations.
Get it through your component's constructor:
// In my-awesome.component.ts:
constructor(private route: ActivatedRoute, private router: Router) {}
// Example call
onNavigateClick() {
// Navigates to a parent component
this.router.navigate([..], { relativeTo: this.route })
}
Nicest thing about this directive is that it will retrieve the ActivatedRoute
for you. Under the hood it's using already familiar:
router.navigateByUrl(router.createUrlTree(commands, { relativeTo: route }), { relativeTo: route });
Following variants will produce identical result:
[routerLink]="['../..']"
// if the string parameter is passed it will be wrapped into an array
routerLink="../.."
the documentation has this blurb https://requests.readthedocs.io/en/master/user/quickstart/#redirection-and-history
import requests
r = requests.get('http://www.github.com')
r.url
#returns https://www.github.com instead of the http page you asked for
This also works like a charm
<form>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio" checked>Option 1_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 2_x000D_
</label>_x000D_
<label class="radio-inline">_x000D_
<input type="radio" name="optradio">Option 3_x000D_
</label>_x000D_
</form>
_x000D_
some resources:
ELF format is generally the default output of compiling. if you use GNU tool chains, you can translate it to binary format by using objcopy, such as:
arm-elf-objcopy -O binary [elf-input-file] [binary-output-file]
or using fromELF utility(built in most IDEs such as ADS though):
fromelf -bin -o [binary-output-file] [elf-input-file]
This happens in the following scenario: When working on Windows, the IDE is more than likely configured to edit files in Cp1252, which is a Microsoft adaptation of latin-11. The developer checks in, and the Continuous Integration server (usually running on Linux, which nowadays is all utf8) picks up the file, and tries to compile as a UTF-8 file, hence the warning.
Try changing the encoding to cp1252. This works. To avoid future problems of this kind, use the same encoding on all the developer machines.
Good luck...
If you are in ES6 just use the "static" keyword on your method from your example would be the following: static alertMessage: function() {
...
},
Hope can help anyone out there :)
Yet another solution to selection highlight problems with first, and last items in the list:
Add padding to the top and bottom of your list background equal to or greater than the radius. This ensures the selection highlighting doesn't overlap with your corner curves.
This is the easiest solution when you need non-transparent selection highlighting.
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<solid android:color="@color/listbg" />
<stroke
android:width="2dip"
android:color="#D5D5D5" />
<corners android:radius="10dip" />
<!-- Make sure bottom and top padding match corner radius -->
<padding
android:bottom="10dip"
android:left="2dip"
android:right="2dip"
android:top="10dip" />
</shape>
Build lists of matched lines - several flavors:
def lines_that_equal(line_to_match, fp):
return [line for line in fp if line == line_to_match]
def lines_that_contain(string, fp):
return [line for line in fp if string in line]
def lines_that_start_with(string, fp):
return [line for line in fp if line.startswith(string)]
def lines_that_end_with(string, fp):
return [line for line in fp if line.endswith(string)]
Build generator of matched lines (memory efficient):
def generate_lines_that_equal(string, fp):
for line in fp:
if line == string:
yield line
Print all matching lines (find all matches first, then print them):
with open("file.txt", "r") as fp:
for line in lines_that_equal("my_string", fp):
print line
Print all matching lines (print them lazily, as we find them)
with open("file.txt", "r") as fp:
for line in generate_lines_that_equal("my_string", fp):
print line
Generators (produced by yield) are your friends, especially with large files that don't fit into memory.
$("#contactForm").submit(function() {
$.post(url, $.param($(this).serializeArray()), function(data) {
});
});
RanRag(accepted) answer will work fine but that's not optimized solution until and unless it is memorized as explained in Anil answer.
For recursive consider below approach, method calls of TestFibonacci
are minimum
public class TestFibonacci {
public static void main(String[] args) {
int n = 10;
if (n == 1) {
System.out.println(1);
} else if (n == 2) {
System.out.println(1);
System.out.println(1);
} else {
System.out.println(1);
System.out.println(1);
int currentNo = 3;
calFibRec(n, 1, 1, currentNo);
}
}
public static void calFibRec(int n, int secondLast, int last,
int currentNo) {
if (currentNo <= n) {
int sum = secondLast + last;
System.out.println(sum);
calFibRec(n, last, sum, ++currentNo);
}
}
}
I recently had a similar experience (sql server 2012). I did not have the luxury of controlling the input, I just had a requirement to report on it. Luckily the dates were entered with leading 3 character alpha month abbreviations, so this made it simple & quick:
TRY_CONVERT(DATETIME,REPLACE(obs.DateValueText,SUBSTRING(obs.DateValueText,1,3),CHARINDEX(SUBSTRING(obs.DateValueText,1,3),'...JAN,FEB,MAR,APR,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC')/4))
It worked for 12 hour:
Feb-14-2015 5:00:00 PM 2015-02-14 17:00:00.000
and 24 hour times:
Sep-27-2013 22:45 2013-09-27 22:45:00.000
(thanks ryanyuyu)
Use word: using
. A good habit of programming.
using (TcpClient tcpClient = new TcpClient())
{
//operations
tcpClient.Close();
}
If you are using microsoft query, you can add "?" to your query...
select name from user where id= ?
that will popup a small window asking for the cell/data/etc when you go back to excel.
In the popup window, you can also select "always use this cell as a parameter" eliminating the need to define that cell every time you refresh your data. This is the easiest option.
This is how I got it to finally go to the proper place when you click on the navigation. I added an event handler for the navigation clicks. Then you can just use "scrollBy" to move up on the offset.
var offset = 90;
$('.navbar li a').click(function(event) {
event.preventDefault();
$($(this).attr('href'))[0].scrollIntoView();
scrollBy(0, -offset);
});
Something like?
select t.*, round(dbms_random.value() * 8) + 1 from foo t;
Edit: David has pointed out this gives uneven distribution for 1 and 9.
As he points out, the following gives a better distribution:
select t.*, floor(dbms_random.value(1, 10)) from foo t;
For people looking for a quick solution, you can use the NetworkShareAccesser
I wrote recently (based on this answer (thanks so much!)):
Usage:
using (NetworkShareAccesser.Access(REMOTE_COMPUTER_NAME, DOMAIN, USER_NAME, PASSWORD))
{
File.Copy(@"C:\Some\File\To\copy.txt", @"\\REMOTE-COMPUTER\My\Shared\Target\file.txt");
}
WARNING: Please make absolutely sure, that Dispose
of the NetworkShareAccesser
is called (even if you app crashes!), otherwise an open connection will remain on Windows. You can see all open connections by opening the cmd
prompt and enter net use
.
The Code:
/// <summary>
/// Provides access to a network share.
/// </summary>
public class NetworkShareAccesser : IDisposable
{
private string _remoteUncName;
private string _remoteComputerName;
public string RemoteComputerName
{
get
{
return this._remoteComputerName;
}
set
{
this._remoteComputerName = value;
this._remoteUncName = @"\\" + this._remoteComputerName;
}
}
public string UserName
{
get;
set;
}
public string Password
{
get;
set;
}
#region Consts
private const int RESOURCE_CONNECTED = 0x00000001;
private const int RESOURCE_GLOBALNET = 0x00000002;
private const int RESOURCE_REMEMBERED = 0x00000003;
private const int RESOURCETYPE_ANY = 0x00000000;
private const int RESOURCETYPE_DISK = 0x00000001;
private const int RESOURCETYPE_PRINT = 0x00000002;
private const int RESOURCEDISPLAYTYPE_GENERIC = 0x00000000;
private const int RESOURCEDISPLAYTYPE_DOMAIN = 0x00000001;
private const int RESOURCEDISPLAYTYPE_SERVER = 0x00000002;
private const int RESOURCEDISPLAYTYPE_SHARE = 0x00000003;
private const int RESOURCEDISPLAYTYPE_FILE = 0x00000004;
private const int RESOURCEDISPLAYTYPE_GROUP = 0x00000005;
private const int RESOURCEUSAGE_CONNECTABLE = 0x00000001;
private const int RESOURCEUSAGE_CONTAINER = 0x00000002;
private const int CONNECT_INTERACTIVE = 0x00000008;
private const int CONNECT_PROMPT = 0x00000010;
private const int CONNECT_REDIRECT = 0x00000080;
private const int CONNECT_UPDATE_PROFILE = 0x00000001;
private const int CONNECT_COMMANDLINE = 0x00000800;
private const int CONNECT_CMD_SAVECRED = 0x00001000;
private const int CONNECT_LOCALDRIVE = 0x00000100;
#endregion
#region Errors
private const int NO_ERROR = 0;
private const int ERROR_ACCESS_DENIED = 5;
private const int ERROR_ALREADY_ASSIGNED = 85;
private const int ERROR_BAD_DEVICE = 1200;
private const int ERROR_BAD_NET_NAME = 67;
private const int ERROR_BAD_PROVIDER = 1204;
private const int ERROR_CANCELLED = 1223;
private const int ERROR_EXTENDED_ERROR = 1208;
private const int ERROR_INVALID_ADDRESS = 487;
private const int ERROR_INVALID_PARAMETER = 87;
private const int ERROR_INVALID_PASSWORD = 1216;
private const int ERROR_MORE_DATA = 234;
private const int ERROR_NO_MORE_ITEMS = 259;
private const int ERROR_NO_NET_OR_BAD_PATH = 1203;
private const int ERROR_NO_NETWORK = 1222;
private const int ERROR_BAD_PROFILE = 1206;
private const int ERROR_CANNOT_OPEN_PROFILE = 1205;
private const int ERROR_DEVICE_IN_USE = 2404;
private const int ERROR_NOT_CONNECTED = 2250;
private const int ERROR_OPEN_FILES = 2401;
#endregion
#region PInvoke Signatures
[DllImport("Mpr.dll")]
private static extern int WNetUseConnection(
IntPtr hwndOwner,
NETRESOURCE lpNetResource,
string lpPassword,
string lpUserID,
int dwFlags,
string lpAccessName,
string lpBufferSize,
string lpResult
);
[DllImport("Mpr.dll")]
private static extern int WNetCancelConnection2(
string lpName,
int dwFlags,
bool fForce
);
[StructLayout(LayoutKind.Sequential)]
private class NETRESOURCE
{
public int dwScope = 0;
public int dwType = 0;
public int dwDisplayType = 0;
public int dwUsage = 0;
public string lpLocalName = "";
public string lpRemoteName = "";
public string lpComment = "";
public string lpProvider = "";
}
#endregion
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name. The user will be promted to enter credentials
/// </summary>
/// <param name="remoteComputerName"></param>
/// <returns></returns>
public static NetworkShareAccesser Access(string remoteComputerName)
{
return new NetworkShareAccesser(remoteComputerName);
}
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name using the given domain/computer name, username and password
/// </summary>
/// <param name="remoteComputerName"></param>
/// <param name="domainOrComuterName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static NetworkShareAccesser Access(string remoteComputerName, string domainOrComuterName, string userName, string password)
{
return new NetworkShareAccesser(remoteComputerName,
domainOrComuterName + @"\" + userName,
password);
}
/// <summary>
/// Creates a NetworkShareAccesser for the given computer name using the given username (format: domainOrComputername\Username) and password
/// </summary>
/// <param name="remoteComputerName"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
public static NetworkShareAccesser Access(string remoteComputerName, string userName, string password)
{
return new NetworkShareAccesser(remoteComputerName,
userName,
password);
}
private NetworkShareAccesser(string remoteComputerName)
{
RemoteComputerName = remoteComputerName;
this.ConnectToShare(this._remoteUncName, null, null, true);
}
private NetworkShareAccesser(string remoteComputerName, string userName, string password)
{
RemoteComputerName = remoteComputerName;
UserName = userName;
Password = password;
this.ConnectToShare(this._remoteUncName, this.UserName, this.Password, false);
}
private void ConnectToShare(string remoteUnc, string username, string password, bool promptUser)
{
NETRESOURCE nr = new NETRESOURCE
{
dwType = RESOURCETYPE_DISK,
lpRemoteName = remoteUnc
};
int result;
if (promptUser)
{
result = WNetUseConnection(IntPtr.Zero, nr, "", "", CONNECT_INTERACTIVE | CONNECT_PROMPT, null, null, null);
}
else
{
result = WNetUseConnection(IntPtr.Zero, nr, password, username, 0, null, null, null);
}
if (result != NO_ERROR)
{
throw new Win32Exception(result);
}
}
private void DisconnectFromShare(string remoteUnc)
{
int result = WNetCancelConnection2(remoteUnc, CONNECT_UPDATE_PROFILE, false);
if (result != NO_ERROR)
{
throw new Win32Exception(result);
}
}
/// <summary>
/// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
/// </summary>
/// <filterpriority>2</filterpriority>
public void Dispose()
{
this.DisconnectFromShare(this._remoteUncName);
}
}
clear() will be much more efficient. It will simply remove each and every item. Using removeAll(arraylist) will take a lot more work because it will check every item in arraylist to see if it exists in arraylist before removing it.
Check your JAVA_HOME path. As systems looks for a java.policy file which is located in JAVA_HOME/jre/lib/security
. Your JAVA_HOME should always be ../JAVA/JDK
.
Using strtotime() function you can easily convert date to timestamp
<?php
// set default timezone
date_default_timezone_set('America/Los_Angeles');
//define date and time
$date = date("d M Y H:i:s");
// output
echo strtotime($date);
?>
More info: http://php.net/manual/en/function.strtotime.php
Online conversion tool: http://freeonlinetools24.com/
In Swift 2, you want to do something like this to properly show it on iPhone and iPad:
func confirmAndDelete(sender: AnyObject) {
guard let button = sender as? UIView else {
return
}
let alert = UIAlertController(title: NSLocalizedString("Delete Contact?", comment: ""), message: NSLocalizedString("This action will delete all downloaded audio files.", comment: ""), preferredStyle: .ActionSheet)
alert.modalPresentationStyle = .Popover
let action = UIAlertAction(title: NSLocalizedString("Delete", comment: ""), style: .Destructive) { action in
EarPlaySDK.deleteAllResources()
}
let cancel = UIAlertAction(title: NSLocalizedString("Cancel", comment: ""), style: .Cancel) { action in
}
alert.addAction(cancel)
alert.addAction(action)
if let presenter = alert.popoverPresentationController {
presenter.sourceView = button
presenter.sourceRect = button.bounds
}
presentViewController(alert, animated: true, completion: nil)
}
If you don't set the presenter, you will end up with an exception on iPad in -[UIPopoverPresentationController presentationTransitionWillBegin]
with the following message:
Fatal Exception: NSGenericException Your application has presented a UIAlertController (<UIAlertController: 0x17858a00>) of style UIAlertControllerStyleActionSheet. The modalPresentationStyle of a UIAlertController with this style is UIModalPresentationPopover. You must provide location information for this popover through the alert controller's popoverPresentationController. You must provide either a sourceView and sourceRect or a barButtonItem. If this information is not known when you present the alert controller, you may provide it in the UIPopoverPresentationControllerDelegate method -prepareForPopoverPresentation.
They are both instances of Context, but the application instance is tied to the lifecycle of the application, while the Activity instance is tied to the lifecycle of an Activity. Thus, they have access to different information about the application environment.
If you read the docs at getApplicationContext it notes that you should only use this if you need a context whose lifecycle is separate from the current context. This doesn't apply in either of your examples.
The Activity context presumably has some information about the current activity that is necessary to complete those calls. If you show the exact error message, might be able to point to what exactly it needs.
But in general, use the activity context unless you have a good reason not to.
You also can enable this import as automatic operation. In the properties dialog of your Java projects, enable organize imports
via Java Editor
- Save Action
. After saving your Java files, IDE will do organizing imports, formatting code and so on for you.
You could do this yourself by checking the output from pwd
when running it.
This will print the directory you are currently in. Not the script.
If your script does not switch directories, it'll print the directory you ran it from.
If you are using python2.7 or above you can use the ability of assertRaises to be use as a context manager and do:
with self.assertRaises(TypeError):
self.testListNone[:1]
If you are using python2.6 another way beside the one given until now is to use unittest2 which is a back port of unittest new feature to python2.6, and you can make it work using the code above.
N.B: I'm a big fan of the new feature (SkipTest, test discovery ...) of unittest so I intend to use unittest2 as much as I can. I advise to do the same because there is a lot more than what unittest come with in python2.6 <.
Visual Studio Package Manager Console > Install-Package Microsoft.AspNet.WebApi.Client
Try this
Scanner scanner = new Scanner(System.in);
int amountOfPlayers;
do {
System.out.print("Select the amount of players (1/2): ");
while (!scanner.hasNextInt()) {
System.out.println("That's not a number!");
scanner.next(); // this is important!
}
amountOfPlayers = scanner.nextInt();
} while ((amountOfPlayers <= 0) || (amountOfPlayers > 2));
if(scanner != null) {
scanner.close();
}
System.out.println("You've selected " + amountOfPlayers+" player(s).");
In the terminal just write : $ mongod --version
#!/bin/sh
sed '1,2d' "$0"|$(which groovy) /dev/stdin; exit;
println("hello");
You can explicitly define the width
and height
of images, but the results may not be the best looking.
.food1 img {
width:100%;
height: 230px;
}
...per your comment, you could also just block any overflow
- see this example to see an image restricted by height and cut off because it's too wide.
.top1 {
height:390px;
background-color:#FFFFFF;
margin-top:10px;
overflow: hidden;
}
.top1 img {
height:100%;
}
Flexbox works.
.box{_x000D_
display: flex;_x000D_
flex-flow: row nowrap;_x000D_
justify-content: center;_x000D_
align-content: center;_x000D_
align-items:center;_x000D_
border:1px solid #e3f2fd;_x000D_
}_x000D_
.item{_x000D_
flex: 1 1 auto;_x000D_
border:1px solid #ffebee;_x000D_
}
_x000D_
<div class="box">_x000D_
<p class="item">A</p>_x000D_
<p class="item">B</p>_x000D_
<p class="item">C</p>_x000D_
</div>
_x000D_
Here's a function eachWithIndex
that works with anything iterable.
You could also write a similar function eachWithKey
that works with objets using for...in
.
// example generator (returns an iterator that can only be iterated once)
function* eachFromTo(start, end) { for (let i = start; i <= end; i++) yield i }
// convers an iterable to an array (potential infinite loop)
function eachToArray(iterable) {
const result = []
for (const val of iterable) result.push(val)
return result
}
// yields every value and index of an iterable (array, generator, ...)
function* eachWithIndex(iterable) {
const shared = new Array(2)
shared[1] = 0
for (shared[0] of iterable) {
yield shared
shared[1]++
}
}
console.log('iterate values and indexes from a generator')
for (const [val, i] of eachWithIndex(eachFromTo(10, 13))) console.log(val, i)
console.log('create an array')
const anArray = eachToArray(eachFromTo(10, 13))
console.log(anArray)
console.log('iterate values and indexes from an array')
for (const [val, i] of eachWithIndex(anArray)) console.log(val, i)
The good thing with generators is that they are lazy and can take another generator's result as an argument.
If you mean you want them back as a string, in that format;
SELECT
CONVERT(CHAR(4), date_of_birth, 100) + CONVERT(CHAR(4), date_of_birth, 120)
FROM customers
On Ubuntu, 'permission denied' may appear when browser is installed as a 'snap'. I had this problem. I edited config file to open a regular browser and it worked.
How to change the default browser used by the ipython/jupyter notebook in Linux?
Do a search foR Lucene, im not sure if theres a PHP port but i do know Lucene is available for many platforms. Lucene is an OSS (from Apache) indexing and search library. Naturally it and community extras might have something interesting to look at. At the very least you can learn how its done in one language so you can translate the "idea" into PHP
Please check below javascript in IE. Don't know if other modern browser will work or not.
<html>
<head>
<script type="text/javascript">
function OpenOutlookDoc(){
try {
var outlookApp = new ActiveXObject("Outlook.Application");
var nameSpace = outlookApp.getNameSpace("MAPI");
mailFolder = nameSpace.getDefaultFolder(6);
mailItem = mailFolder.Items.add('IPM.Note.FormA');
mailItem.Subject="a subject test";
mailItem.To = "[email protected]";
mailItem.HTMLBody = "<b>bold</b>";
mailItem.display (0);
}
catch(e){
alert(e);
// act on any error that you get
}
}
</script>
</head>
<body>
<a href="javascript:OpenOutlookDoc()">Click</a>
</body>
</html>
something along this?
function dump(x, indent) {
var indent = indent || '';
var s = '';
if (Array.isArray(x)) {
s += '[';
for (var i=0; i<x.length; i++) {
s += dump(x[i], indent)
if (i < x.length-1) s += ', ';
}
s +=']';
} else if (x === null) {
s = 'NULL';
} else switch(typeof x) {
case 'undefined':
s += 'UNDEFINED';
break;
case 'object':
s += "{ ";
var first = true;
for (var p in x) {
if (!first) s += indent + ' ';
s += p + ': ';
s += dump(x[p], indent + ' ');
s += "\n"
first = false;
}
s += '}';
break;
case 'boolean':
s += (x) ? 'TRUE' : 'FALSE';
break;
case 'number':
s += x;
break;
case 'string':
s += '"' + x + '"';
break;
case 'function':
s += '<FUNCTION>';
break;
default:
s += x;
break;
}
return s;
}
On Ubuntu, you would need to install a package called python-dev
. Since this package doesn't seem to be installed (locate Python.h
didn't find anything) and you can't install it system-wide yourself, we need a different solution.
You can install Python in your home directory -- you don't need any special permissions to do this. If you are allowed to use a web browser and run a gcc, this should work for you. To this end
Download the source tarball.
Unzip with
tar xjf Python-2.7.2.tar.bz2
Build and install with
cd Python-2.7.2
./configure --prefix=/home/username/python --enable-unicode=ucs4
make
make install
Now, you have a complete Python installation in your home directory. Pass -I /home/username/python/include
to gcc when compiling to make it aware of Python.h
. Pass -L /home/username/python/lib
and -lpython2.7
when linking.
Simply put, you cannot before C++11.
C++11 introduces delegating constructors:
Delegating constructor
If the name of the class itself appears as class-or-identifier in the member initializer list, then the list must consist of that one member initializer only; such constructor is known as the delegating constructor, and the constructor selected by the only member of the initializer list is the target constructor
In this case, the target constructor is selected by overload resolution and executed first, then the control returns to the delegating constructor and its body is executed.
Delegating constructors cannot be recursive.
class Foo { public: Foo(char x, int y) {} Foo(int y) : Foo('a', y) {} // Foo(int) delegates to Foo(char,int) };
Note that a delegating constructor is an all-or-nothing proposal; if a constructor delegates to another constructor, the calling constructor isn't allowed to have any other members in its initialization list. This makes sense if you think about initializing const/reference members once, and only once.
Finally I solved this problem by changing compile 'com.google.guava:guava:18.0 ' to compile 'com.google.guava:guava-jdk5:17.0'
I edited your plunker to include ABOS's solution.
<body ng-controller="MainCtrl">
<ul ng-repeat='item in items'>
<li ng-if='item.color'>The color is {{item.color}}</li>
<li ng-if='item.shipping !== undefined'>The shipping cost is {{item.shipping}}</li>
</ul>
</body>
This is probably system-dependent, but this is the simplest way I've found.
if [ -e /var/run/nginx.pid ]; then echo "nginx is running"; fi
That's the best solution for scripting.
You can use:
a.slice!(0)
slice! generalizes to any index or range.
You can try using Scanner if you are using JDK5 or higher.
Scanner scan = new Scanner(file);
scan.useDelimiter("\\Z");
String content = scan.next();
Or you can also use Guava
String data = Files.toString(new File("path.txt"), Charsets.UTF8);
your code is correct because in some cases it does not work, I also do not know where the error comes from but this can help you solve the problem, move the code in the head of the view like this:
index.cshtml:
@using expert.Models;
@{
ViewBag.Title = "Create";
Layout = "~/Views/Shared/_Layout.cshtml";
Manager db = new Manager();
ViewBag.FORM_PRESTATION = new SelectList(db.T_BDE_PRESTATION_PRES.OrderBy(p => p.PRES_INTITULE).Where(p => p.T_B_PRES_ID == null), "PRES_ID", "PRES_INTITULE");
}
<div class="form-group">
<label class = "w3-blue" style ="text-shadow:1px 1px 0 #444">Domaine:</label>
<div class="col-md-10">
@Html.DropDownList("FORM_PRESTATION", null, htmlAttributes: new { @class = "w3-select ", @required = "true" })
</div>
</div>
There's always the HTML5 download
attribute :
This attribute, if present, indicates that the author intends the hyperlink to be used for downloading a resource so that when the user clicks on the link they will be prompted to save it as a local file.
If the attribute has a value, the value will be used as the pre-filled file name in the Save prompt that opens when the user clicks on the link.
var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
Tested in Chrome and Firefox, works fine in the newest versions (as of July 2013).
Works in Opera as well, but does not set the filename (as of July 2013).
Does not seem to work in IE9 (big suprise) (as of July 2013).
An overview over what browsers support the download attribute can be found Here
For non-supporting browsers, one has to set the appropriate headers on the serverside.
Apparently there is a hack for IE10 and IE11, which doesn't support the download
attribute (Edge does however).
var A = [['n','sqrt(n)']];
for(var j=1; j<10; ++j){
A.push([j, Math.sqrt(j)]);
}
var csvRows = [];
for(var i=0, l=A.length; i<l; ++i){
csvRows.push(A[i].join(','));
}
var csvString = csvRows.join("%0A");
if (window.navigator.msSaveOrOpenBlob) {
var blob = new Blob([csvString]);
window.navigator.msSaveOrOpenBlob(blob, 'myFile.csv');
} else {
var a = document.createElement('a');
a.href = 'data:attachment/csv,' + encodeURIComponent(csvString);
a.target = '_blank';
a.download = 'myFile.csv';
document.body.appendChild(a);
a.click();
}
TL;DR Use Activity.startActivityForResult
Long answer:
You should start by reading the Android developer documentation. Specifically the topic of your question is covered in the Starting Activities and Getting Results
section of the Activity
documentation.
As for example code, the Android SDK provides good examples. Also, other answers here give you short snippets of sample code to use.
However, if you are looking for alternatives, read this SO question. This is a good discussion on how to use startActivityForResults
with fragments, as well as couple othe approaches for passing data between activities.
As +Volatility and yourself pointed out, sets are unordered. If you need the elements to be in order, just call sorted
on the set:
>>> y = [1, 1, 6, 6, 6, 6, 6, 8, 8]
>>> sorted(set(y))
[1, 6, 8]
Change the .find
to .filter
...
It could be as simple as a stale PID file. It could be failing silently because your computer didn't complete the shutdown process completely which means postgres didn't delete the PID (process id) file.
The PID file is used by postgres to make sure only one instance of the server is running at a time. So when it goes to start again, it fails because there is already a PID file which tells postgres that another instance of the server was started (even though it isn't running, it just didn't get to shutdown and delete the PID).
/usr/local/var/postgres/
,
or /usr/local/var/log/
other systems it might be /usr/var/postgres/
.server.log
). On the last lines you will see: FATAL: lock file "postmaster.pid" already exists
HINT: Is another postmaster (PID 347) running in data directory "/usr/local/var/postgres"?
rm postmaster.pid
Restart your server. On a mac using launchctl (with homebrew) the following commands will restart the server.
launchctl unload homebrew.mxcl.postgresql.plist
launchctl load -w homebrew.mxcl.postgresql.plist
OR on newer versions of Brew
brew services restart postgresql
If you're working with actual files (as opposed to some sort of string data), how about the following?
$files | % { "$($_.BaseName -replace '_[^_]+$','')$($_.Extension)" }
(or use _.+$
if you want to cut everything from the first underscore.)
What worked for me is moving my project as it was on the desktop (C:\Users\lachezar.l\Desktop\MyFolder) to (C:\0\MyFolder) which as you can see uses shorter path and reducing it solved the problem.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
This is the simple way. As basic I took it from http://codepen.io/rpdasilva/pen/DpbFf, and done some changes. For now code is more simply. And you can get: in controller - "4124561232", in view "(412) 456-1232"
Filter:
myApp.filter 'tel', ->
(tel) ->
if !tel
return ''
value = tel.toString().trim().replace(/^\+/, '')
city = undefined
number = undefined
res = null
switch value.length
when 1, 2, 3
city = value
else
city = value.slice(0, 3)
number = value.slice(3)
if number
if number.length > 3
number = number.slice(0, 3) + '-' + number.slice(3, 7)
else
number = number
res = ('(' + city + ') ' + number).trim()
else
res = '(' + city
return res
And directive:
myApp.directive 'phoneInput', ($filter, $browser) ->
require: 'ngModel'
scope:
phone: '=ngModel'
link: ($scope, $element, $attrs) ->
$scope.$watch "phone", (newVal, oldVal) ->
value = newVal.toString().replace(/[^0-9]/g, '').slice 0, 10
$scope.phone = value
$element.val $filter('tel')(value, false)
return
return
It's really incredible ... All are proposing some special package for playing an animated GIF, at the moment that it can be done with Tkinter and the classic PIL module!
Here is my own GIF animation method (I created a while ago). Very simple:
from Tkinter import *
from PIL import Image, ImageTk
from time import sleep
def stop(event):
global play
play = False
exit()
root = Tk()
root.bind("<Key>", stop) # Press any key to stop
GIFfile = {path_to_your_GIF_file}
im = Image.open(GIFfile); img = ImageTk.PhotoImage(im)
delay = float(im.info['duration'])/1000; # Delay used in the GIF file
lbl = Label(image=img); lbl.pack() # Create a label where to display images
play = True; frame = 0
while play:
sleep(delay);
frame += 1
try:
im.seek(frame); img = ImageTk.PhotoImage(im)
lbl.config(image=img); root.update() # Show the new frame/image
except EOFError:
frame = 0 # Restart
root.mainloop()
You can set your own means to stop the animation. Let me know if you like to get the full version with play/pause/quit buttons.
Note: I am not sure if the consecutive frames are read from memory or from the file (disk). In the second case it would be more efficient if they all read at once and saved into an array (list). (I'm not so interested to find out! :)
Here's what works directly with Vue custom components.
<MyCustomComponent nativeOnScroll={this.handleScroll}>
or
<my-component v-on:scroll.native="handleScroll">
and define a method for handleScroll. Simple!
Enqueue means to add an element, dequeue to remove an element.
var stackInput= []; // First stack
var stackOutput= []; // Second stack
// For enqueue, just push the item into the first stack
function enqueue(stackInput, item) {
return stackInput.push(item);
}
function dequeue(stackInput, stackOutput) {
// Reverse the stack such that the first element of the output stack is the
// last element of the input stack. After that, pop the top of the output to
// get the first element that was ever pushed into the input stack
if (stackOutput.length <= 0) {
while(stackInput.length > 0) {
var elementToOutput = stackInput.pop();
stackOutput.push(elementToOutput);
}
}
return stackOutput.pop();
}
You can do it the DOM way as well:
var div = document.getElementById('cart_item');
while(div.firstChild){
div.removeChild(div.firstChild);
}
Simply you can follow the link. its very simple and very easy to use. I am using this. Its working fine.
use like this
//include the file
require_once 'Mobile_Detect.php';
$detect = new Mobile_Detect;
// Any mobile device (phones or tablets).
if ( $detect->isMobile() ) {
//do some code
}
// Any tablet device.
if( $detect->isTablet() ){
//do some code
}
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
You can see the overview and ranking for yourself here. Hibernate is an ORM, so you can use either struts+Hiberante or spring+hibernate to build a web app. Different web frameworks and many are alternatives to each other.
Use the variables "$1"
, "$2"
, "$3"
and so on to access arguments. To access all of them you can use "$@"
, or to get the count of arguments $#
(might be useful to check for too few or too many arguments).
You can't. Take the characters before and after the position and concat into a new string:
var s = "Hello world";
var index = 3;
s = s.substring(0, index) + 'x' + s.substring(index + 1);
I use getActionCommand() to hear buttons. I apply the setActionCommand() to each button so that I can hear whenever an event is execute with event.getActionCommand("The setActionCommand() value of the button").
I use getSource() for JRadioButtons for example. I write methods that returns each JRadioButton so in my Listener Class I can specify an action each time a new JRadioButton is pressed. So for example:
public class SeleccionListener implements ActionListener, FocusListener {}
So with this I can hear button events and radioButtons events. The following are examples of how I listen each one:
public void actionPerformed(ActionEvent event) {
if (event.getActionCommand().equals(GUISeleccion.BOTON_ACEPTAR)) {
System.out.println("Aceptar pressed");
}
In this case GUISeleccion.BOTON_ACEPTAR is a "public static final String" which is used in JButtonAceptar.setActionCommand(BOTON_ACEPTAR).
public void focusGained(FocusEvent focusEvent) {
if (focusEvent.getSource().equals(guiSeleccion.getJrbDat())){
System.out.println("Data radio button");
}
In this one, I get the source of any JRadioButton that is focused when the user hits it. guiSeleccion.getJrbDat() returns the reference to the JRadioButton that is in the class GUISeleccion (this is a Frame)
I want to explain the answer/solution to this like I am explaining to a 5-year-old , so everyone can understand .
I have an app.I want people to register with their email,password and phone number . In my MongoDB database , I want to identify people uniquely based on both their phone numbers and email - so this means that both the phone number and the email must be unique for every person.
However , there is a problem : I have realized that everyone has a phonenumber but not everyone has an email address .
Those that don`t have an email address have promised me that they will have an email address by next week. But I want them registered anyway - so I tell them to proceed registering their phonenumbers as they leave the email-input-field empty .
They do so .
My database NEEDS an unique email address field - but I have a lot of people with 'null' as their email address . So I go to my code and tell my database schema to allow empty/null email address fields which I will later fill in with email unique addresses when the people who promised to add their emails to their profiles next week .
So its now a win-win for everyone (but you ;-] ): the people register, I am happy to have their data ...and my database is happy because it is being used nicely ...but what about you ? I am yet to give you the code that made the schema .
Here is the code : NOTE : The sparse property in email , is what tells my database to allow null values which will later be filled with unique values .
var userSchema = new mongoose.Schema({_x000D_
local: {_x000D_
name: { type: String },_x000D_
email : { type: String, require: true, index:true, unique:true,sparse:true},_x000D_
password: { type: String, require:true },_x000D_
},_x000D_
facebook: {_x000D_
id : { type: String },_x000D_
token : { type: String },_x000D_
email : { type: String },_x000D_
name : { type: String }_x000D_
}_x000D_
});_x000D_
_x000D_
var User = mongoose.model('User',userSchema);_x000D_
_x000D_
module.exports = User;
_x000D_
I hope I have explained it nicely . Happy NodeJS coding / hacking!
I was facing the same problem for a long time but I solved it by adjusting the settings in gradle.
Step 1:In Module app add dependency in BuildScript
buildscript {
dependencies {
classpath 'com.android.tools.build:gradle:2.0.0-alpha9'
}
}
Step 2: Add dexOption and give the following heapSize
dexOptions {
incremental = true;
preDexLibraries = false
javaMaxHeapSize "4g"
}
Step 3: Add productFlavors
productFlavors {
dev {
minSdkVersion 23
applicationId = "com.Reading.home"
}
prod {
minSdkVersion 15
applicationId = "com.Reading.home" // you don't need it, but can be useful
}
}
This should reduce your build time.
This is a prompt to create a bunch of object, such as sp_help_diagram (?), that do not exist.
This should have nothing to do with the owner of the db.
I also came across this issue while using the Quarkus microservice framework:
public class SomeResource {
@GET
@RolesAllowed({"basic"})
public Response doSomething(@Context SecurityContext context) {
// ...
}
}
// this will generate an QuerySyntax exception, as the authorization module
// will ignore the Entity annotation and use the class name instead.
@Entity(name = "users")
@UserDefinition
public class User {
// ...
}
// do this instead
@Entity
@Table(name = "users")
@UserDefinition
public class User {
// ...
}
In my case I didn't run this command
sudo apt-get install php7.4-fpm
In addition to the other answers, the following directory contains deletable system images on a Mac for Android Studio 2.3.3. I was able to delete the android-16 and android-17 directories without any problem because I didn't have any emulators which used them. (I kept the android-24 which was in use.)
$ pwd
/Users/gareth/Library/Android/sdk/system-images
$ du -h
2.5G ./android-16/default/x86
2.5G ./android-16/default
2.5G ./android-16/google_apis/x86
2.5G ./android-16/google_apis
5.1G ./android-16
2.5G ./android-17/default/x86
2.5G ./android-17/default
2.5G ./android-17
3.0G ./android-24/default/x86_64
3.0G ./android-24/default
3.0G ./android-24
11G .
Answers above have clarified ways to set margin handling GridLayoutManager and LinearLayoutManager.
But for StaggeredGridLayoutManager, Pirdad Sakhizada's answer says: "It might not work very well with StaggeredGridLayoutManager". It should be the problem about IndexOfSpan.
You can get it by this way:
private static class MyItemDecoration extends RecyclerView.ItemDecoration {
@Override
public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
super.getItemOffsets(outRect, view, parent, state);
int index = ((StaggeredGridLayoutManager.LayoutParams) view.getLayoutParams()).getSpanIndex();
}
}
You can use Linq
var files = Directory.GetFiles(@"C:\", "*").OrderByDescending(d => new FileInfo(d).CreationTime);
Two simple solutions:
Execute your code once before the while loop
actions() {
check_if_file_present
# Do other stuff
}
actions #1st execution
while [ current_time <= $cutoff ]; do
actions # Loop execution
done
Or:
while : ; do
actions
[[ current_time <= $cutoff ]] || break
done
If you're trying to disable the field (without actually disabling it), try setting the onfocus
event to this.blur();
. This way, whenever the field gets focus, it automatically loses it.
This is how you do it
SELECT ID,NAME, (C_COUNTS+F_COUNTS) AS SUM_COUNTS
FROM TABLE
ORDER BY SUM_COUNTS LIMIT 20
The SUM function will add up all rows, so the order by
clause is useless, instead you will have to use the group by
clause.
nop... just open the four dateis: content.xml; server.xml; tomcat-users.xml and web.xml in the tap servers. There are some text. Change the number of port 8080 to 8081
userType = (user.Type == 0) ? "Admin" : (user.type == 1) ? "User" : "Admin";
should do the trick.
This will work, but the i -> i
is doing some automatic unboxing which is why it "feels" strange. Either of the following will work and better explain what the compiler is doing under the hood with your original syntax:
integers.values().stream().mapToInt(i -> i.intValue()).sum();
integers.values().stream().mapToInt(Integer::intValue).sum();
I am getting this same error, but only on a specific view, when I touch the first textfield, and then the next textfield down.
I am writing in SwiftUI for iOS 13.4
Unable to simultaneously satisfy constraints.
Probably at least one of the constraints in the following list is one you don't want.
Try this:
(1) look at each constraint and try to figure out which you don't expect;
(2) find the code that added the unwanted constraint or constraints and fix it.
(
"<NSLayoutConstraint:0x2809b6760 'assistantHeight' TUISystemInputAssistantView:0x105710da0.height == 44 (active)>",
"<NSLayoutConstraint:0x2809ccff0 'assistantView.bottom' TUISystemInputAssistantView:0x105710da0.bottom == _UIKBCompatInputView:0x10525ae10.top (active)>",
"<NSLayoutConstraint:0x2809cccd0 'assistantView.top' V:|-(0)-[TUISystemInputAssistantView:0x105710da0] (active, names: '|':UIInputSetHostView:0x105215010 )>",
"<NSLayoutConstraint:0x2809ca300 'inputView.top' V:|-(0)-[_UIKBCompatInputView:0x10525ae10] (active, names: '|':UIInputSetHostView:0x105215010 )>"
)
Will attempt to recover by breaking constraint
<NSLayoutConstraint:0x2809ccff0 'assistantView.bottom' TUISystemInputAssistantView:0x105710da0.bottom == _UIKBCompatInputView:0x10525ae10.top (active)>
Make a symbolic breakpoint at UIViewAlertForUnsatisfiableConstraints to catch this in the debugger.
The methods in the UIConstraintBasedLayoutDebugging category on UIView listed in <UIKitCore/UIView.h> may also be helpful.
Modifying each element while iterating a list is fine, as long as you do not change add/remove elements to list.
You can use list comprehension:
l = ['a', ' list', 'of ', ' string ']
l = [item.strip() for item in l]
or just do the C-style
for loop:
for index, item in enumerate(l):
l[index] = item.strip()
this solved my issue, it was working fine with
var value = item[index].id;
$("#select2").val(value);
but not showing selected value, so
$("#select2").val(value).change();
works fine for me.
The \
on it's own is used to escape special characters, such as \n
(new line), \t
(tabulation), \"
(quotes) when typing these specific values in a System.out.println()
statement.
Thus, if you want to print a backslash, \
, you can't have it on it's own since the compiler will be expecting a special character (such as the ones above). Thus, to print a backslash you need to escape it, since itself is also one of these special characters, thus, \\
yields \
.
Although I am very late to this but after seeing some legitimate questions for those who wanted to use INSERT-SELECT
query with GROUP BY
clause, I came up with the work around for this.
Taking further the answer of Marcus Adams and accounting GROUP BY
in it, this is how I would solve the problem by using Subqueries in the FROM Clause
INSERT INTO lee(exp_id, created_by, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur)
SELECT sb.id, uid, sb.location, sb.animal, sb.starttime, sb.endtime, sb.entct,
sb.inact, sb.inadur, sb.inadist,
sb.smlct, sb.smldur, sb.smldist,
sb.larct, sb.lardur, sb.lardist,
sb.emptyct, sb.emptydur
FROM
(SELECT id, uid, location, animal, starttime, endtime, entct,
inact, inadur, inadist,
smlct, smldur, smldist,
larct, lardur, lardist,
emptyct, emptydur
FROM tmp WHERE uid=x
GROUP BY location) as sb
ON DUPLICATE KEY UPDATE entct=sb.entct, inact=sb.inact, ...
It boils down to whether the CPU in your machine has the the VT bit (Virtualization), and the BIOS enables you to turn it on. For instance, my laptop is a Core 2 Duo which is capable of using this. However, my BIOS doesn't enable me to turn it on.
Note that I've read that turning on this feature can slow normal operations down by 10-12%, which is why it's normally turned off.
If you want to select the type of console, you can write this in the file "keybinding.json" (this file can be found in the following path "File-> Preferences-> Keyboard Shortcuts") `
//with this you can select what type of console you want
{
"key": "ctrl+shift+t",
"command": "shellLauncher.launch"
},
//and this will help you quickly change console
{
"key": "ctrl+shift+j",
"command": "workbench.action.terminal.focusNext"
},
{
"key": "ctrl+shift+k",
"command": "workbench.action.terminal.focusPrevious"
}`
For me I was working under Ubuntu
The error disappeared if I use sudo with ng
sudo ng build
sudo ng serve
Just for completeness - in SQL 2008 you would use the plus +
operator to perform string concatenation.
Take a look at the MSDN reference with sample code. Starting with SQL 2012, you may wish to use the new CONCAT function.
According to Angular Doc:
Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading... it's the main difference...
Basically until every dom elements not loaded, we can not see them and because ngBind is attribute on the element, it waits until the doms come into play... more info below
ngBind
- directive in module ng
The ngBind attribute tells AngularJS to replace the text content of the specified HTML element with the value of a given expression, and to update the text content when the value of that expression changes.
Typically, you don't use ngBind directly, but instead you use the double curly markup like {{ expression }} which is similar but less verbose.
It is preferable to use ngBind instead of {{ expression }} if a template is momentarily displayed by the browser in its raw state before AngularJS compiles it. Since ngBind is an element attribute, it makes the bindings invisible to the user while the page is loading.
An alternative solution to this problem would be using the ngCloak directive. visit here
for more info about the ngbind visit this page: https://docs.angularjs.org/api/ng/directive/ngBind
You could do something like this as attribute, ng-bind:
<div ng-bind="my.name"></div>
or do interpolation as below:
<div>{{my.name}}</div>
or this way with ng-cloak attributes in AngularJs:
<div id="my-name" ng-cloak>{{my.name}}</div>
ng-cloak avoid flashing on the dom and wait until all be ready! this is equal to ng-bind attribute...
You can do this with the "rebase" command. Let's call the branches "main" and "feature":
git checkout feature
git rebase main
The rebase command will replay all of the commits on "feature" as one commit with a parent equal to "main".
You might want to run git merge main
before git rebase main
if "main" has changed since "feature" was created (or since the most recent merge). That way, you still have your full history in case you had a merge conflict.
After the rebase, you can merge your branch to main, which should result in a fast-forward merge:
git checkout main
git merge feature
See the rebase page of Understanding Git Conceptually for a good overview
In IntelliJ Idea,
Check the following things are configured properly,
Step 1:
File -> Setting -> Plugins -> search javafx and make sure its enabled.
Step 2: Project Structure (Ctrl+Shift+Alt+s)
Platform Settings -> SDKs -> 1.8 -> Make sure Classpath should have "jre\lib\ext\jfxrt.jar"
Step 3:
Project Settings -> Project -> Project SDK - should be selected 1.8
Project Settings -> Project -> Project language level - configured as 8
Ubuntu: If not found jfxrt.jar in your SDKs then install sudo apt-get install openjfx
Try this to your .htaccess file:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php?/$1 [L]
</IfModule >
How about something like this: http://jsfiddle.net/EgLKV/3/
Its done by using position:absolute
and z-index
to place the text over the image.
#container {_x000D_
height: 400px;_x000D_
width: 400px;_x000D_
position: relative;_x000D_
}_x000D_
#image {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
}_x000D_
#text {_x000D_
z-index: 100;_x000D_
position: absolute;_x000D_
color: white;_x000D_
font-size: 24px;_x000D_
font-weight: bold;_x000D_
left: 150px;_x000D_
top: 350px;_x000D_
}
_x000D_
<div id="container">_x000D_
<img id="image" src="http://www.noao.edu/image_gallery/images/d4/androa.jpg" />_x000D_
<p id="text">_x000D_
Hello World!_x000D_
</p>_x000D_
</div>
_x000D_
So, what's wrong with checking each element iteratively?
function arraysEqual(arr1, arr2) {
if(arr1.length !== arr2.length)
return false;
for(var i = arr1.length; i--;) {
if(arr1[i] !== arr2[i])
return false;
}
return true;
}
The idea that you need to get the reference to the object that is contained inside a Set object is common. It can be archived by 2 ways:
Use HashSet as you wanted, then:
public Object getObjectReference(HashSet<Xobject> set, Xobject obj) {
if (set.contains(obj)) {
for (Xobject o : set) {
if (obj.equals(o))
return o;
}
}
return null;
}
For this approach to work, you need to override both hashCode() and equals(Object o) methods In the worst scenario we have O(n)
Second approach is to use TreeSet
public Object getObjectReference(TreeSet<Xobject> set, Xobject obj) {
if (set.contains(obj)) {
return set.floor(obj);
}
return null;
}
This approach gives O(log(n)), more efficient. You don't need to override hashCode for this approach but you have to implement Comparable interface. ( define function compareTo(Object o)).
The fetch mode will only work when selecting the object by id i.e. using entityManager.find()
. Since Spring Data will always create a query, the fetch mode configuration will have no use to you. You can either use dedicated queries with fetch joins or use entity graphs.
When you want best performance, you should select only the subset of the data you really need. To do this, it is generally recommended to use a DTO approach to avoid unnecessary data to be fetched, but that usually results in quite a lot of error prone boilerplate code, since you need define a dedicated query that constructs your DTO model via a JPQL constructor expression.
Spring Data projections can help here, but at some point you will need a solution like Blaze-Persistence Entity Views which makes this pretty easy and has a lot more features in it's sleeve that will come in handy! You just create a DTO interface per entity where the getters represent the subset of data you need. A solution to your problem could look like this
@EntityView(Identified.class)
public interface IdentifiedView {
@IdMapping
Integer getId();
}
@EntityView(Identified.class)
public interface UserView extends IdentifiedView {
String getName();
}
@EntityView(Identified.class)
public interface StateView extends IdentifiedView {
String getName();
}
@EntityView(Place.class)
public interface PlaceView extends IdentifiedView {
UserView getAuthor();
CityView getCity();
}
@EntityView(City.class)
public interface CityView extends IdentifiedView {
StateView getState();
}
public interface PlaceRepository extends JpaRepository<Place, Long>, PlaceRepositoryCustom {
PlaceView findById(int id);
}
public interface UserRepository extends JpaRepository<User, Long> {
List<UserView> findAllByOrderByIdAsc();
UserView findById(int id);
}
public interface CityRepository extends JpaRepository<City, Long>, CityRepositoryCustom {
CityView findById(int id);
}
Disclaimer, I'm the author of Blaze-Persistence, so I might be biased.
Replace the earlier function with the provided one. The simplest solution is:
def __unicode__(self):
return unicode(self.nom_du_site)
You can first make a conditional selection, and sum up the results of the selection using the sum
function.
>> df = pd.DataFrame({'a': [1, 2, 3]})
>> df[df.a > 1].sum()
a 5
dtype: int64
Having more than one condition:
>> df[(df.a > 1) & (df.a < 3)].sum()
a 2
dtype: int64
Just to give an update, there are minor changes for Visual Studio 2015 users.
To use or install package manually, go to Tools -> Options -> NuGet Package Manager -> Package Sources
Click the Add button, choose the Source, and don't forget to click "Update" as it will update the folder location for your packages, edit your desired Name of your package source if you want:
To choose your added package, right click your solution and select "Manage Nuget Packages"
The drop down list is on the right and choose Browse to browse your packages that you specified on your folder source. If there is no nuget package on that folder source, this will be empty:
Amortized Big-O for hashtables:
Note that there is a constant factor for the hashing algorithm, and the amortization means that actual measured performance may vary dramatically.
I noticed that postgres 9.2 now calls the column pid rather than procpid.
I tend to call it from the shell:
#!/usr/bin/env bash
# kill all connections to the postgres server
if [ -n "$1" ] ; then
where="where pg_stat_activity.datname = '$1'"
echo "killing all connections to database '$1'"
else
echo "killing all connections to database"
fi
cat <<-EOF | psql -U postgres -d postgres
SELECT pg_terminate_backend(pg_stat_activity.pid)
FROM pg_stat_activity
${where}
EOF
Hope that is helpful. Thanks to @JustBob for the sql.
Why would you want to do this?
IMHO you should store the date as default type and if needed fetch it transforming to desired format.
You could get away with specifying column's format but with a view. I don't know other methods.
Edited:
Seriously, in my opinion, you should create a view on that a table with date type. I'm talking about something like this:
create table sample_table ( id serial primary key, timestamp date);
and than
create view v_example_table as select id, to_char(date, 'yyyymmmm');
And use v_example_table in your application.
You can write like this:
CSS
span{
background: none repeat scroll 0 0 #F8F8F8;
border: 5px solid #DFDFDF;
color: #717171;
font-size: 13px;
height: 30px;
letter-spacing: 1px;
line-height: 30px;
margin: 0 auto;
position: relative;
text-align: center;
text-transform: uppercase;
top: -80px;
left:-30px;
display:none;
padding:0 20px;
}
span:after{
content:'';
position:absolute;
bottom:-10px;
width:10px;
height:10px;
border-bottom:5px solid #dfdfdf;
border-right:5px solid #dfdfdf;
background:#f8f8f8;
left:50%;
margin-left:-5px;
-moz-transform:rotate(45deg);
-webkit-transform:rotate(45deg);
transform:rotate(45deg);
}
p{
margin:100px;
float:left;
position:relative;
cursor:pointer;
}
p:hover span{
display:block;
}
HTML
<p>Hover here<span>some text here ?</span></p>
Check this http://jsfiddle.net/UNs9J/1/
This is because you have wrong selector. According to your markup, .ui-icon
and .ui-icon-circle-triangle-w"
should point to the same <span>
element. So you should use:
$(".ui-icon.ui-icon-circle-triangle-w").html("<<");
or
$(".ui-datepicker-prev .ui-icon").html("<<");
or
$(".ui-datepicker-prev span").html("<<");
One option is you can wrap it into another array:
Foo(new object[]{ new object[]{ (object)"1", (object)"2" } });
Kind of ugly, but since each item is an array, you can't just cast it to make the problem go away... such as if it were Foo(params object items), then you could just do:
Foo((object) new object[]{ (object)"1", (object)"2" });
Alternatively, you could try defining another overloaded instance of Foo which takes just a single array:
void Foo(object[] item)
{
// Somehow don't duplicate Foo(object[]) and
// Foo(params object[]) without making an infinite
// recursive call... maybe something like
// FooImpl(params object[] items) and then this
// could invoke it via:
// FooImpl(new object[] { item });
}
Using solve
with a single parameter is a request to invert a matrix. The error message is telling you that your matrix is singular and cannot be inverted.
new docs says use {{ mydata|json_script:"mydata" }}
to prevent code injection.
a good exmple is given here:
{{ mydata|json_script:"mydata" }}
<script>
const mydata = JSON.parse(document.getElementById('mydata').textContent);
</script>
Just check if response[0]
is undefined:
if(response[0] !== undefined) { ... }
If you still need to explicitly check the title, do so after the initial check:
if(response[0] !== undefined && response[0].title !== undefined){ ... }
One needs to be somewhat careful, since the Windows batch command:
for /f "delims=" %%a in ('command') do @set theValue=%%a
does not have the same semantics as the Unix shell statement:
theValue=`command`
Consider the case where the command fails, causing an error.
In the Unix shell version, the assignment to "theValue" still occurs, any previous value being replaced with an empty value.
In the Windows batch version, it's the "for" command which handles the error, and the "do" clause is never reached -- so any previous value of "theValue" will be retained.
To get more Unix-like semantics in Windows batch script, you must ensure that assignment takes place:
set theValue=
for /f "delims=" %%a in ('command') do @set theValue=%%a
Failing to clear the variable's value when converting a Unix script to Windows batch can be a cause of subtle errors.
Visual Studio 2013 now supports setup projects. Microsoft have shipped a Visual Studio extension to produce setup projects.
Using TextWatcher in Android
Here is a sample code. Try using addTextChangedListener
method of TextView
addTextChangedListener(new TextWatcher() {
BigDecimal previousValue;
BigDecimal currentValue;
@Override
public void onTextChanged(CharSequence s, int start, int before, int
count) {
if (isFirstTimeChange) {
return;
}
if (s.toString().length() > 0) {
try {
currentValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
} catch (Exception e) {
currentValue = new BigDecimal(0);
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
if (isFirstTimeChange) {
return;
}
if (s.toString().length() > 0) {
try {
previousValue = new BigDecimal(s.toString().replace(".", "").replace(',', '.'));
} catch (Exception e) {
previousValue = new BigDecimal(0);
}
}
}
@Override
public void afterTextChanged(Editable editable) {
if (isFirstTimeChange) {
isFirstTimeChange = false;
return;
}
if (currentValue != null && previousValue != null) {
if ((currentValue.compareTo(previousValue) > 0)) {
//setBackgroundResource(R.color.devises_overview_color_green);
setBackgroundColor(flashOnColor);
} else if ((currentValue.compareTo(previousValue) < 0)) {
//setBackgroundResource(R.color.devises_overview_color_red);
setBackgroundColor(flashOffColor);
} else {
//setBackgroundColor(textColor);
}
handler.removeCallbacks(runnable);
handler.postDelayed(runnable, 1000);
}
}
});
Here author performed tests showed that integer unix timestamp is better than DateTime. Note, he used MySql. But I feel no matter what DB engine you use comparing integers are slightly faster than comparing dates so int index is better than DateTime index. Take T1 - time of comparing 2 dates, T2 - time of comparing 2 integers. Search on indexed field takes approximately O(log(rows)) time because index based on some balanced tree - it may be different for different DB engines but anyway Log(rows) is common estimation. (if you not use bitmask or r-tree based index). So difference is (T2-T1)*Log(rows) - may play role if you perform your query oftenly.
In Mastering Web Application Development with AngularJS book p.19, it is written that
Avoid direct bindings to scope's properties. Two-way data binding to object's properties (exposed on a scope) is a preferred approach. As a rule of thumb, you should have a dot in an expression provided to the ng-model directive (for example, ng-model="thing.name").
Scopes are just JavaScript objects, and they mimic dom hierarchy. According to JavaScript Prototype Inheritance, scopes properties are separated through scopes. To avoid this, dot notation should use to bind ng-models.
Gosha Arinich is right, you should return your <li>
element.
But, nevertheless, you should get nasty red warning in the browser console in this case
Each child in an array or iterator should have a unique "key" prop.
so, you need to add "key" to your list:
this.state.data.map(function(item, i){
console.log('test');
return <li key={i}>Test</li>
})
or drop the console.log()
and do a beautiful oneliner, using es6 arrow functions:
this.state.data.map((item,i) => <li key={i}>Test</li>)
IMPORTANT UPDATE:
The answer above is solving the current problem, but as Sergey mentioned in the comments: using the key depending on the map index is BAD if you want to do some filtering and sorting. In that case use the item.id
if id
already there, or just generate unique ids for it.
EDIT: as of Java8 you'd better use Files
class:
Path resultingPath = Files.createDirectories('A/B');
I don't know if this ultimately fixes your problem but class File
has method mkdirs()
which fully creates the path specified by the file.
File f = new File("/A/B/");
f.mkdirs();
You can do an enhanced for loop (for java 5 and higher) for iteration on array's elements:
String[] elements = {"a", "a", "a", "a"};
for (String s: elements) {
//Do your stuff here
System.out.println(s);
}
Install .NET framework as below, it will work .NET version 4.5 as well.
%windir%\Microsoft.NET\Framework\v4.0.30319\aspnet_regiis.exe -ir
Some time only give aspnet_regiis.exe -i
don't work so give aspnet_regiis.exe -ir
in above path.