Each time you do e.nextElement()
you skip one. So you skip two elements in each iteration of your loop.
In my case I was trying to create my dialog like this:
new Dialog(getApplicationContext());
So I had to change for:
new Dialog(this);
And it works fine for me ;)
if i understood you can do the following
Right Click on View Name in SQL Server Management Studio -> Script View As ->CREATE To ->New Query Window
If you want to dynamically change it, I prefer using SqlConnectionStringBuilder .
It allows you to convert ConnectionString i.e. a string into class Object, All the connection string properties will become its Member.
In this case the real advantage would be that you don't have to worry about If the ConnectionTimeout string part is already exists in the connection string or not?
Also as it creates an Object and its always good to assign value in object rather than manipulating string.
Here is the code sample:
var sscsb = new SqlConnectionStringBuilder(_dbFactory.Database.ConnectionString);
sscsb.ConnectTimeout = 30;
var conn = new SqlConnection(sscsb.ConnectionString);
In Spring Boot 2, the easiest way is to declare in your application.properties:
spring.jackson.serialization.WRITE_ENUMS_USING_TO_STRING=true
spring.jackson.deserialization.READ_ENUMS_USING_TO_STRING=true
and define the toString() method of your enums.
The Random
class of Java located in the java.util
package will serve your purpose better. It has some nextInt()
methods that return an integer. The one taking an int argument will generate a number between 0 and that int, the latter not inclusive.
When using qt (Qt 4.3+), one can use QPolygon's function containsPoint
You can combine strings using stream string like that:
#include <iostream>
#include <sstream>
using namespace std;
int main()
{
string name = "Bill";
stringstream ss;
ss << "Your name is: " << name;
string info = ss.str();
cout << info << endl;
return 0;
}
You could do this:
String json = new ObjectMapper().writeValueAsString(yourObjectHere);
To use AUTO_INCREMENT
you need to deifne column as INT
or floating-point types, not CHAR
.
AUTO_INCREMENT
use only unsigned value, so it's good to use UNSIGNED
as well;
CREATE TABLE discussion_topics (
topic_id INT NOT NULL unsigned AUTO_INCREMENT,
project_id char(36) NOT NULL,
topic_subject VARCHAR(255) NOT NULL,
topic_content TEXT default NULL,
date_created DATETIME NOT NULL,
date_last_post DATETIME NOT NULL,
created_by_user_id char(36) NOT NULL,
last_post_user_id char(36) NOT NULL,
posts_count char(36) default NULL,
PRIMARY KEY (topic_id)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=1;
Another solution is .die() for events who that attached with .live().
Ex.:
// attach click event for <a> tags
$('a').live('click', function(){});
// deattach click event from <a> tags
$('a').die('click');
You can find a good refference here: Exploring jQuery .live() and .die()
( Sorry for my english :"> )
It says that the file C:\wamp\www\mysite\php\includes\dbconn.inc
doesn't exist, so the error is, you're missing the file.
Only changing the settings with the following command did not work in my environment:
curl -XPUT -H "Content-Type: application/json" http://localhost:9200/_all/_settings -d '{"index.blocks.read_only_allow_delete": null}'
I had to also ran the Force Merge API command:
curl -X POST "localhost:9200/my-index-000001/_forcemerge?pretty"
ref: Force Merge API
For the instance of
render :json => @projects, :include => :tasks
You are stating that you want to render @projects
as JSON, and include the association tasks
on the Project model in the exported data.
For the instance of
render :json => @projects, :callback => 'updateRecordDisplay'
You are stating that you want to render @projects
as JSON, and wrap that data in a javascript call that will render somewhat like:
updateRecordDisplay({'projects' => []})
This allows the data to be sent to the parent window and bypass cross-site forgery issues.
Your question is about the operator precedences in mysql and Alex has shown you how to "override" the precedence with parentheses.
But on a side note, if your column date
is of the type Date
you can use MySQL's date and time functions to fetch the records of the last seven days, like e.g.
SELECT
*
FROM
Drinks
WHERE
email='$Email'
AND date >= Now()-Interval 7 day
(or maybe Curdate() instead of Now())
You can override drawPlaceholderInRect:(CGRect)rect
as such to manually render the placeholder text:
- (void) drawPlaceholderInRect:(CGRect)rect {
[[UIColor blueColor] setFill];
[[self placeholder] drawInRect:rect withFont:[UIFont systemFontOfSize:16]];
}
Based on @Shimmy's response, I created an extension method that is the solution that everyone wants. It is simple, easy to use, and only loops through the collection once.
internal static class EnumerableExtensions
{
public static void ForEachLast<T>(this IEnumerable<T> collection, Action<T>? actionExceptLast = null, Action<T>? actionOnLast = null)
{
using var enumerator = collection.GetEnumerator();
var isNotLast = enumerator.MoveNext();
while (isNotLast)
{
var current = enumerator.Current;
isNotLast = enumerator.MoveNext();
var action = isNotLast ? actionExceptLast : actionOnLast;
action?.Invoke(current);
}
}
}
This works on any IEnumerable<T>
. Usage looks like this:
var items = new[] {1, 2, 3, 4, 5};
items.ForEachLast(i => Console.WriteLine($"{i},"), i => Console.WriteLine(i));
Output looks like:
1,
2,
3,
4,
5
Additionally, you can make this into a Select
style method. Then, reuse that extension in the ForEach
. That code looks like this:
internal static class EnumerableExtensions
{
public static void ForEachLast<T>(this IEnumerable<T> collection, Action<T>? actionExceptLast = null, Action<T>? actionOnLast = null) =>
// ReSharper disable once IteratorMethodResultIsIgnored
collection.SelectLast(i => { actionExceptLast?.Invoke(i); return true; }, i => { actionOnLast?.Invoke(i); return true; }).ToArray();
public static IEnumerable<TResult> SelectLast<T, TResult>(this IEnumerable<T> collection, Func<T, TResult>? selectorExceptLast = null, Func<T, TResult>? selectorOnLast = null)
{
using var enumerator = collection.GetEnumerator();
var isNotLast = enumerator.MoveNext();
while (isNotLast)
{
var current = enumerator.Current;
isNotLast = enumerator.MoveNext();
var selector = isNotLast ? selectorExceptLast : selectorOnLast;
//https://stackoverflow.com/a/32580613/294804
if (selector != null)
{
yield return selector.Invoke(current);
}
}
}
}
first open the docker image for the postgres
docker exec -it <container_name>
then u will get the root --root@868594e88b53:/#
it need the database connection
psql postgresql://<username>:<databasepassword>@postgres:5432/<database>
All the answers here discuss about onclick method, however you can also use addEventListener().
Syntax of addEventListener()
document.getElementById('button').addEventListener("click",{function defination});
The function defination above is known as anonymous function.
If you don't want to use anonymous functions you can also use function refrence.
function functionName(){
//function defination
}
document.getElementById('button').addEventListener("click",functionName);
You can check the detail differences between onclick() and addEventListener() in this answer here.
Unfortunately you're probably done with the animation and presentation already. In the hopes this answer can help future questioners, however, this blog post has a walkthrough of steps that can loop a single slide as a sort of sub-presentation.
First, click Slide Show > Set Up Show.
Put a checkmark to Loop continuously until 'Esc'.
Click Ok. Now, Click Slide Show > Custom Shows. Click New.
Select the slide you are looping, click Add. Click Ok and Close.
Click on the slide you are looping. Click Slide Show > Slide Transition. Under Advance slide, put a checkmark to Automatically After. This will allow the slide to loop automatically. Do NOT Apply to all slides.
Right click on the thumbnail of the current slide, select Hide Slide.
Now, you will need to insert a new slide just before the slide you are looping. On the new slide, insert an action button. Set the hyperlink to the custom show you have created. Put a checkmark on "Show and Return"
This has worked for me.
Android Studio setup wizard will appear and perform the needed installation.
http://greptweet.com/ is an attempt to surpass the 3200 limit by backing up tweets, and besides that is useful for simple searches.
Find a note here: https://code.visualstudio.com/docs/python/environments#_conda-environments
As noted earlier, the Python extension automatically detects existing conda environments provided that the environment contains a Python interpreter. For example, the following command creates a conda environment with the Python 3.4 interpreter and several libraries, which VS Code then shows in the list of available interpreters:
conda create -n env-01 python=3.4 scipy=0.15.0 astroid babel
In contrast, if you fail to specify an interpreter, as with conda create --name env-00, the environment won't appear in the list.
Note: This solution works well on Ubuntu 16.04
, Ubuntu 17.04
and Ubuntu 18.04
.
Try to remove the existing cmdtest and yarn (which is the module of legacy black box command line tool of *nix systems) :
sudo apt remove cmdtest sudo apt remove yarn
Install it simple via npm
npm install -g yarn
OR
sudo npm install -g yarn
Now yarn is installed. Run your command.
yarn install sylius
I hope this will work. Cheers!
Edit:
Do remember to re-open the terminal
for changes to take effect.
I faced the same problem, and I used --allow-empty
:
$ git commit -m "initial commit" --allow-empty
...
$ git push
...
One of main reasons of this problem is that some Git servers, such as BitBucket, don't have their master
branch initialized when a fresh repository is cloned.
The accepted answer in 2008 recommended SIGAR. However, as a comment from 2014 (@Alvaro) says:
Be careful when using Sigar, there are problems on x64 machines... Sigar 1.6.4 is crashing: EXCEPTION_ACCESS_VIOLATION and it seems the library doesn't get updated since 2010
My recommendation is to use https://github.com/oshi/oshi
Or the answer mentioned above.
If you're on OSX you can also find it your keychain. Your developer and distribution certificates have your Team ID in them.
Applications -> Utilities -> Keychain Access.
Under the 'login' Keychain, go into the 'Certificates' category.
Scroll to find your development or distribution certificate. They will read:
iPhone Distribution: Team Name (certificate id)
or
iPhone Developer: Team Name (certificate id)
Simply double-click on the item, and the
is the "Team ID"
Note that this is the only way to find your
You can not find the "Personal team" ID on the Apple web interface.
For example, if you are automating a build from say Unity, during development you'll want it to appear in Xcode as your "Personal team" - this is the only way to get that value.
Use body-parser Parse the body with what it will be:
app.use(bodyParser.text());
app.use(bodyParser.urlencoded());
app.use(bodyParser.raw());
app.use(bodyParser.json());
ie. If you are supposed to get raw text file, run .text()
.
Thats what body-parser currently supports
$new_website = substr($str, ($pos = strrpos($str, '//')) !== false ? $pos + 2 : 0);
This would remove everything before the '//'.
EDIT
This one is tested. Using strrpos()
instead or strpos()
.
Just pass your regression model into the following function:
plot_coeffs <- function(mlr_model) {
coeffs <- coefficients(mlr_model)
mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
lablist <- names(coeffs)
text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
Use as follows:
model <- lm(Petal.Width ~ ., data = iris)
plot_coeffs(model)
This one is just extension of article you found.
public class WebClientEx : WebClient
{
public WebClientEx(CookieContainer container)
{
this.container = container;
}
public CookieContainer CookieContainer
{
get { return container; }
set { container= value; }
}
private CookieContainer container = new CookieContainer();
protected override WebRequest GetWebRequest(Uri address)
{
WebRequest r = base.GetWebRequest(address);
var request = r as HttpWebRequest;
if (request != null)
{
request.CookieContainer = container;
}
return r;
}
protected override WebResponse GetWebResponse(WebRequest request, IAsyncResult result)
{
WebResponse response = base.GetWebResponse(request, result);
ReadCookies(response);
return response;
}
protected override WebResponse GetWebResponse(WebRequest request)
{
WebResponse response = base.GetWebResponse(request);
ReadCookies(response);
return response;
}
private void ReadCookies(WebResponse r)
{
var response = r as HttpWebResponse;
if (response != null)
{
CookieCollection cookies = response.Cookies;
container.Add(cookies);
}
}
}
Why to complicate a situation if you can just write like it? (yes -> low cohesion, hardcoded -> but it is a example and unfortunately with imperative way). For additional info read code example at below ;))
package timer.test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.util.concurrent.*;
public class TestKitTimerWithExecuterService {
private static final Logger log = LoggerFactory.getLogger(TestKitTimerWithExecuterService.class);
private static final ScheduledExecutorService executorService
= Executors.newSingleThreadScheduledExecutor();// equal to => newScheduledThreadPool(1)/ Executor service with one Thread
private static ScheduledFuture<?> future; // why? because scheduleAtFixedRate will return you it and you can act how you like ;)
public static void main(String args[]){
log.info("main thread start");
Runnable task = () -> log.info("******** Task running ********");
LocalDateTime now = LocalDateTime.now();
LocalDateTime whenToStart = LocalDate.now().atTime(20, 11); // hour, minute
Duration duration = Duration.between(now, whenToStart);
log.info("WhenToStart : {}, Now : {}, Duration/difference in second : {}",whenToStart, now, duration.getSeconds());
future = executorService.scheduleAtFixedRate(task
, duration.getSeconds() // difference in second - when to start a job
,2 // period
, TimeUnit.SECONDS);
try {
TimeUnit.MINUTES.sleep(2); // DanDig imitation of reality
cancelExecutor(); // after canceling Executor it will never run your job again
} catch (InterruptedException e) {
e.printStackTrace();
}
log.info("main thread end");
}
public static void cancelExecutor(){
future.cancel(true);
executorService.shutdown();
log.info("Executor service goes to shut down");
}
}
Follow this link for new updates. Use Java 8 language features
Old Answer
As of Android N preview release Android support limited features of Java 8 see Java 8 Language Features
To start using these features, you need to download and set up Android Studio 2.1 and the Android N Preview SDK, which includes the required Jack toolchain and updated Android Plugin for Gradle. If you haven't yet installed the Android N Preview SDK, see Set Up to Develop for Android N.
Supported Java 8 Language Features and APIs
Android does not currently support all Java 8 language features. However, the following features are now available when developing apps targeting the Android N Preview:
Default and static interface methods
Lambda expressions (also available on API level 23 and lower)
Method References (also available on API level 23 and lower)
There are some additional Java 8 features which Android support, you can see complete detail from Java 8 Language Features
Update
Note: The Android N bases its implementation of lambda expressions on anonymous classes. This approach allows them to be backwards compatible and executable on earlier versions of Android. To test lambda expressions on earlier versions, remember to go to your build.gradle file, and set compileSdkVersion and targetSdkVersion to 23 or lower.
Update 2
Now Android studio 3.0 stable release support Java 8 libraries and Java 8 language features (without the Jack compiler).
There are no values that will cause the checkbox to be unchecked. If the checked
attribute exists, the checkbox will be checked regardless of what value you set it to.
<input type="checkbox" checked />_x000D_
<input type="checkbox" checked="" />_x000D_
<input type="checkbox" checked="checked" />_x000D_
<input type="checkbox" checked="unchecked" />_x000D_
<input type="checkbox" checked="true" />_x000D_
<input type="checkbox" checked="false" />_x000D_
<input type="checkbox" checked="on" />_x000D_
<input type="checkbox" checked="off" />_x000D_
<input type="checkbox" checked="1" />_x000D_
<input type="checkbox" checked="0" />_x000D_
<input type="checkbox" checked="yes" />_x000D_
<input type="checkbox" checked="no" />_x000D_
<input type="checkbox" checked="y" />_x000D_
<input type="checkbox" checked="n" />
_x000D_
Renders everything checked in all modern browsers (FF3.6, Chrome 10, IE8).
If there is a reason you can't use the simple solution provided by ennuikiller above, then you will have to use Typeglobs to manipulate file handles. This is way more work. This example copies from the file in $ARGV[0]
to that in $ARGV[1]
. It defaults to STDIN
and STDOUT
respectively if files are not specified.
use English;
my $in;
my $out;
if ($#ARGV >= 0){
unless (open($in, "<", $ARGV[0])){
die "could not open $ARGV[0] for reading.";
}
}
else {
$in = *STDIN;
}
if ($#ARGV >= 1){
unless (open($out, ">", $ARGV[1])){
die "could not open $ARGV[1] for writing.";
}
}
else {
$out = *STDOUT;
}
while ($_ = <$in>){
$out->print($_);
}
T
and TRUE
are True, F
and FALSE
are False. T
and F
can be redefined, however, so you should only rely upon TRUE
and FALSE
. If you compare 0 to FALSE and 1 to TRUE, you will find that they are equal as well, so you might consider them to be True and False as well.
SELECT company
, workflow
, MIN(date)
FROM workflowTable
GROUP BY company
, workflow
/System/Library
and /usr/bin
, as this may break your whole operating system.NOTE: The steps listed below do not affect the Apple-supplied system Python 2.7; they only remove a third-party Python framework, like those installed by python.org installers.
The complete list is documented here. Basically, all you need to do is the following:
Remove the third-party Python 2.7 framework
sudo rm -rf /Library/Frameworks/Python.framework/Versions/2.7
Remove the Python 2.7 applications directory
sudo rm -rf "/Applications/Python 2.7"
Remove the symbolic links, in /usr/local/bin
, that point to this Python version. See them using
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7'
and then run the following command to remove all the links:
cd /usr/local/bin/
ls -l /usr/local/bin | grep '../Library/Frameworks/Python.framework/Versions/2.7' | awk '{print $9}' | tr -d @ | xargs rm
If necessary, edit your shell profile file(s) to remove adding /Library/Frameworks/Python.framework/Versions/2.7
to your PATH
environment file. Depending on which shell you use, any of the following files may have been modified:
~/.bash_login
, ~/.bash_profile
, ~/.cshrc
, ~/.profile
, ~/.tcshrc
, and/or ~/.zprofile
.
Arrays (called list
in python) use the []
notation. {}
is for dict
(also called hash tables, associated arrays, etc in other languages) so you won't have 'append' for a dict.
If you actually want an array (list), use:
array = []
array.append(valueToBeInserted)
input_str = "ABC"
[bin(byte) for byte in bytes(input_str, "utf-8")]
Will give:
['0b1000001', '0b1000010', '0b1000011']
As long as you aren't using the NDK you can just ignore that warning.
By the way: This warning has nothing to do with parallel installations.
I was missing C headers solution was to download it for Xcode, this is the best way.
xcode-select --install
Hope it helps.
You can also use the didSet
to set the variable to a different value. This does not cause the observer to be called again as stated in Properties guide. For example, it is useful when you want to limit the value as below:
let minValue = 1
var value = 1 {
didSet {
if value < minValue {
value = minValue
}
}
}
value = -10 // value is minValue now.
Usually, the following command does the trick:
sudo service docker restart
This, instead of docker start
for the cases where Docker seems to already be running.
If that works then, as suggested and in another answer and on this GitHub issue, if you haven't added yourself in the docker group do it by running:
sudo usermod -aG docker <your-username>
And you're most likely good to go.
As for anybody else bumping into this, in some OS's docker doesn't start right after you install it and, as a result, the same can't connect to daemon message
appears. In this case you can first verify that Docker is indeed not running by checking the status of your docker service by executing:
sudo service docker status
If the output looks something like: docker stop/waiting
instead of docker start/running, process 15378
then it obviously means Docker is not active. In this case make sure you start it with:
sudo service docker start
And, as before, you'll most likely be good to go.
Here is an example for those who want to Test Spring MockMvc Security Config using Base64 basic authentication.
String basicDigestHeaderValue = "Basic " + new String(Base64.encodeBase64(("<username>:<password>").getBytes()));
this.mockMvc.perform(get("</get/url>").header("Authorization", basicDigestHeaderValue).accept(MediaType.APPLICATION_JSON)).andExpect(status().isOk());
Maven Dependency
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.3</version>
</dependency>
.md is markdown
. README.md
is used to generate the html
summary you see at the bottom of projects. Github has their own flavor of Markdown.
Order of Preference: If you have two files named README
and README.md
, the file named README.md
is preferred, and it will be used to generate github's html
summary.
FWIW, Stack Overflow uses local Markdown modifications as well (also see Stack Overflow's C# Markdown Processor)
Where I work we have 2 Sprints to an Iteration. The Iteration demo is before the business stakeholders that don't want to meet after every Sprint, but that is our interpretation of the terminology. Some places may have the terms having equally meaning, I'm just pointing out that where I work they aren't the same thing.
No, sprints can have varying lengths. Where I work we had a half a Sprint to align our Sprints with the Iterations that others in the project from another department were using.
This works for me
if (isset($_SERVER['HTTPS']) &&
($_SERVER['HTTPS'] == 'on' || $_SERVER['HTTPS'] == 1) ||
isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
$_SERVER['HTTP_X_FORWARDED_PROTO'] == 'https') {
$protocol = 'https://';
}
else {
$protocol = 'http://';
}
Follow the below steps:
1.Goto Help -> Install new Software
2.Give address http://download.eclipse.org/releases/oxygen and name as your choice.
3.Search for Java EE and choose 1.Eclipse Java EE Developer Tools
4.Search for JST and choose 2.JST Server Adapters 3.JST Server Adapters
5.Click next and accept the license agreement.
Find the server option in the window-->preferences and add server as you need
Go to your Target or Project settings, click the Gear icon at the bottom left, and select "Add User-Defined Setting". The new setting name should be GCC_PREPROCESSOR_DEFINITIONS
, and you can type your definitions in the right-hand field.
Per Steph's comments, the full syntax is:
constant_1=VALUE constant_2=VALUE
Note that you don't need the '='s if you just want to #define a symbol, rather than giving it a value (for #ifdef
statements)
#False positive cases
train = pd.merge(X_train, y_train,left_index=True, right_index=True)
y_train_pred = pd.DataFrame(y_train_pred)
y_train_pred.rename(columns={0 :'Predicted'}, inplace=True )
train = train.reset_index(drop=True).merge(y_train_pred.reset_index(drop=True),
left_index=True,right_index=True)
train['FP'] = np.where((train['Banknote']=="Forged") & (train['Predicted']=="Genuine"),1,0)
train[train.FP != 0]
Every derived table (AKA sub-query) must indeed have an alias. I.e. each query in brackets must be given an alias (AS whatever
), which can the be used to refer to it in the rest of the outer query.
SELECT ID FROM (
SELECT ID, msisdn FROM (
SELECT * FROM TT2
) AS T
) AS T
In your case, of course, the entire query could be replaced with:
SELECT ID FROM TT2
Apparently now when you run a rolling-update with the --image
argument the same as the existing container image, you must also specify an --image-pull-policy
. The following command should force a pull of the image when it is the same as the container image:
kubectl rolling-update myapp --image=us.gcr.io/project-107012/myapp:5c3dda6b --image-pull-policy Always
You'll need to open the workbook to refer to it.
Sub Setwbk()
Dim wbk As Workbook
Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
Master Benchmark Data Sheet.xlsx")
End Sub
* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:
Why do I have to "set" it?
Set
is how VBA assigns object variables. Since a Range
and a Workbook
/Worksheet
are objects, you must use Set
with these.
add disable="true" to html field Example :disable
<amexio-text-input formControlName="LastName" disable="true" [(ngModel)]="emplpoyeeRegistration.lastName" [field-label]="'Last Name'" [place-holder]="'Please enter last name'" [allow-blank]="true" [error-msg]="'errorMsg'" [enable-popover]="true" [min-length]="2"
[min-error-msg]="'Minimum 2 char allowed'" [max-error-msg]="'Maximum 20 char allowed'" name="xyz" [max-length]="20">
[icon-feedback]="true">
</amexio-text-input>
Zoom is not included in the CSS specification, but it is supported in IE, Safari 4, Chrome (and you can get a somewhat similar effect in Firefox with -moz-transform: scale(x)
since 3.5). See here.
So, all browsers
zoom: 2;
zoom: 200%;
will zoom your object in by 2, so it's like doubling the size. Which means if you have
a:hover {
zoom: 2;
}
On hover, the <a>
tag will zoom by 200%.
Like I say, in FireFox 3.5+ use -moz-transform: scale(x)
, it does much the same thing.
Edit: In response to the comment from thirtydot
, I will say that scale()
is not a complete replacement. It does not expand in line like zoom
does, rather it will expand out of the box and over content, not forcing other content out of the way. See this in action here. Furthermore, it seems that zoom
is not supported in Opera.
This post gives a useful insight into ways to work around incompatibilities with scale
and workarounds for it using jQuery.
When you want a flex item to occupy an entire row, set it to width: 100%
or flex-basis: 100%
, and enable wrap
on the container.
The item now consumes all available space. Siblings are forced on to other rows.
.parent {
display: flex;
flex-wrap: wrap;
}
#range, #text {
flex: 1;
}
.error {
flex: 0 0 100%; /* flex-grow, flex-shrink, flex-basis */
border: 1px dashed black;
}
_x000D_
<div class="parent">
<input type="range" id="range">
<input type="text" id="text">
<label class="error">Error message (takes full width)</label>
</div>
_x000D_
More info: The initial value of the flex-wrap
property is nowrap
, which means that all items will line up in a row. MDN
HTTP sends bytes. If the resource in question is text, the character encoding is normally specified, either by the Content-Type HTTP header or by another mechanism (an RFC, HTML meta http-equiv
,...).
urllib
should know how to encode the bytes to a string, but it's too naïve—it's a horribly underpowered and un-Pythonic library.
Dive Into Python 3 provides an overview about the situation.
Your "work-around" is fine—although it feels wrong, it's the correct way to do it.
The suggestion by hjpotter92 does not work in safari! I have made a small adjustment to the script so it now works in Safari as well.
Only change made is resetting height to 0 on every load in order to enable some browsers to decrease height.
Add this to <head>
tag:
<script type="text/javascript">
function resizeIframe(obj){
obj.style.height = 0;
obj.style.height = obj.contentWindow.document.body.scrollHeight + 'px';
}
</script>
And add the following onload
attribute to your iframe, like so
<iframe onload='resizeIframe(this)'></iframe>
Because the bootstrap-select is a bootstrap component and therefore you need to include it in your code as you did for your V3
NOTE: this component only works in boostrap-4 since version 1.13.0
$('select').selectpicker();
_x000D_
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">_x000D_
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>_x000D_
_x000D_
_x000D_
_x000D_
<select class="selectpicker" multiple data-live-search="true">_x000D_
<option>Mustard</option>_x000D_
<option>Ketchup</option>_x000D_
<option>Relish</option>_x000D_
</select>
_x000D_
I have experienced same problem with System.Data.SQLite. The source of the problem is the dll you have used should have same .NET version with your project.
For example if you have used (in my case) SQLite for .NET 4.5, your platform target should be .NET 4.5 too.
You can find platform target by: Project > (project name) Properties > Build.
I just read the answers and this appears to be a very hot topic. I'm currently using .NET 3.5 SP1 and Windows Forms.
The well-known formula greatly described in the previous answers that makes use of the InvokeRequired property covers most of the cases, but not the entire pool.
What if the Handle has not been created yet?
The InvokeRequired property, as described here (Control.InvokeRequired Property reference to MSDN) returns true if the call was made from a thread that is not the GUI thread, false either if the call was made from the GUI thread, or if the Handle was not created yet.
You can come across an exception if you want to have a modal form shown and updated by another thread. Because you want that form shown modally, you could do the following:
private MyForm _gui;
public void StartToDoThings()
{
_gui = new MyForm();
Thread thread = new Thread(SomeDelegate);
thread.Start();
_gui.ShowDialog();
}
And the delegate can update a Label on the GUI:
private void SomeDelegate()
{
// Operations that can take a variable amount of time, even no time
//... then you update the GUI
if(_gui.InvokeRequired)
_gui.Invoke((Action)delegate { _gui.Label1.Text = "Done!"; });
else
_gui.Label1.Text = "Done!";
}
This can cause an InvalidOperationException if the operations before the label's update "take less time" (read it and interpret it as a simplification) than the time it takes for the GUI thread to create the Form's Handle. This happens within the ShowDialog() method.
You should also check for the Handle like this:
private void SomeDelegate()
{
// Operations that can take a variable amount of time, even no time
//... then you update the GUI
if(_gui.IsHandleCreated) // <---- ADDED
if(_gui.InvokeRequired)
_gui.Invoke((Action)delegate { _gui.Label1.Text = "Done!"; });
else
_gui.Label1.Text = "Done!";
}
You can handle the operation to perform if the Handle has not been created yet: You can just ignore the GUI update (like shown in the code above) or you can wait (more risky). This should answer the question.
Optional stuff: Personally I came up coding the following:
public class ThreadSafeGuiCommand
{
private const int SLEEPING_STEP = 100;
private readonly int _totalTimeout;
private int _timeout;
public ThreadSafeGuiCommand(int totalTimeout)
{
_totalTimeout = totalTimeout;
}
public void Execute(Form form, Action guiCommand)
{
_timeout = _totalTimeout;
while (!form.IsHandleCreated)
{
if (_timeout <= 0) return;
Thread.Sleep(SLEEPING_STEP);
_timeout -= SLEEPING_STEP;
}
if (form.InvokeRequired)
form.Invoke(guiCommand);
else
guiCommand();
}
}
I feed my forms that get updated by another thread with an instance of this ThreadSafeGuiCommand, and I define methods that update the GUI (in my Form) like this:
public void SetLabeTextTo(string value)
{
_threadSafeGuiCommand.Execute(this, delegate { Label1.Text = value; });
}
In this way I'm quite sure that I will have my GUI updated whatever thread will make the call, optionally waiting for a well-defined amount of time (the timeout).
It working 100% in safari..i tried
@media screen and (-webkit-min-device-pixel-ratio:0)
{
::i-block-chrome, Class Name {your styles}
}
It's working for me in TypeScript
and JavaScript
:
let lst = [_x000D_
{ description:'Senior', price: 10},_x000D_
{ description:'Adult', price: 20},_x000D_
{ description:'Child', price: 30}_x000D_
];_x000D_
let sum = lst.map(o => o.price).reduce((a, c) => { return a + c });_x000D_
console.log(sum);
_x000D_
I hope is useful.
If you are open to vtd-xml, which excels at both performance and memory efficiency, below is the code to do what you are looking for...in both XPath and manual navigation... the overall code is much concise and easier to understand ...
import com.ximpleware.*;
public class queryText {
public static void main(String[] s) throws VTDException{
VTDGen vg = new VTDGen();
if (!vg.parseFile("input.xml", true))
return;
VTDNav vn = vg.getNav();
AutoPilot ap = new AutoPilot(vn);
// first manually navigate
if(vn.toElement(VTDNav.FC,"tag")){
int i= vn.getText();
if (i!=-1){
System.out.println("text ===>"+vn.toString(i));
}
if (vn.toElement(VTDNav.NS,"tag")){
i=vn.getText();
System.out.println("text ===>"+vn.toString(i));
}
}
// second version use XPath
ap.selectXPath("/add/tag/text()");
int i=0;
while((i=ap.evalXPath())!= -1){
System.out.println("text node ====>"+vn.toString(i));
}
}
}
There is an option IdentityFile
which you can use in your ~/.ssh/config
file and specify key file for each host.
Host host_with_key1.net
IdentityFile ~/.ssh/id_rsa
Host host_with_key2.net
IdentityFile ~/.ssh/id_rsa_test
More info: http://linux.die.net/man/5/ssh_config
Also look at http://nerderati.com/2011/03/17/simplify-your-life-with-an-ssh-config-file/
The solution Bobince posted works perfectly for me. I wanted to offer an alternative method as well for future visitors:
if (typeof(jQuery) == 'undefined') {
(function() {
var sct = document.createElement('script');
sct.src = ('https:' == document.location.protocol ? 'https' : 'http') +
'://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js';
sct.type = 'text/javascript';
sct.async = 'true';
var domel = document.getElementsByTagName('script')[0];
domel.parentNode.insertBefore(sct, domel);
})();
}
In this example, I've included a conditional load for jQuery to demonstrate use case. Hope that's useful for someone!
For Eloquent you can just do:
$result->getQuery()->toSql();
But you need to remove the "->get()" part from your query.
I was able to solve this by removing extra folder that Eclipse had created in my eclipse installation folder. I didn't install and I was using Eclilpse Neon 3 with Spring Tool suite also installed. But, when I looked into extracted eclipse installation, I had C: folder which had some folder structure. It was mirror image of my Downloads folder. I removed it and restarted.
It worked for me!
This answer is based on Yann's answer. It will set the aspect ratio for linear or log-log plots. I've used additional information from https://stackoverflow.com/a/16290035/2966723 to test if the axes are log-scale.
def forceAspect(ax,aspect=1):
#aspect is width/height
scale_str = ax.get_yaxis().get_scale()
xmin,xmax = ax.get_xlim()
ymin,ymax = ax.get_ylim()
if scale_str=='linear':
asp = abs((xmax-xmin)/(ymax-ymin))/aspect
elif scale_str=='log':
asp = abs((scipy.log(xmax)-scipy.log(xmin))/(scipy.log(ymax)-scipy.log(ymin)))/aspect
ax.set_aspect(asp)
Obviously you can use any version of log
you want, I've used scipy
, but numpy
or math
should be fine.
When you pass a string to the filter
function, the string is interpreted as SQL. Count is a SQL keyword and using count
as a variable confuses the parser. This is a small bug (you can file a JIRA ticket if you want to).
You can easily avoid this by using a column expression instead of a String:
df.groupBy("x").count()
.filter($"count" >= 2)
.show()
Just use var = var1 var2
and it will automatically concatenate the vars var1
and var2
:
awk '{new_var=$1$2; print new_var}' file
You can put an space in between with:
awk '{new_var=$1" "$2; print new_var}' file
Which in fact is the same as using FS
, because it defaults to the space:
awk '{new_var=$1 FS $2; print new_var}' file
$ cat file
hello how are you
i am fine
$ awk '{new_var=$1$2; print new_var}' file
hellohow
iam
$ awk '{new_var=$1 FS $2; print new_var}' file
hello how
i am
You can play around with it in ideone: http://ideone.com/4u2Aip
In case anyone has the same problem in the future:
$ adb shell
$ su
# mount -o rw,remount /system
Both adb remount
and adb root
don't work on a production build without altering ro.secure, but you can still remount /system by opening a shell, asking for root permissions and typing the mount command.
Assign the second variable for the $.each function()
as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).
$.each(json, function(arrayID,group) {
console.log('<a href="'+group.GROUP_ID+'">');
$.each(group.EVENTS, function(eventID,eventData) {
console.log('<p>'+eventData.SHORT_DESC+'</p>');
});
});
Should print out everything you were trying in your question.
http://jsfiddle.net/niklasvh/hZsQS/
edit renamed the variables to make it bit easier to understand what is what.
Just leave out the "dot-slash" ./
:
D:\Gesture Recognition\Gesture Recognition\Debug>"Gesture Recognition.exe"
Though, if you wanted to, you could use .\
and it would work.
D:\Gesture Recognition\Gesture Recognition\Debug>.\"Gesture Recognition.exe"
In your git dir, suppose you have sync all changes.
rm -rf .git
rm -rf .gitmodules
Then do:
git init
git submodule add url_to_repo projectfolder
If you are on OSX, then it's ~/.profile
It depends on what do you mean by python functions? if they were written in cpython you can not directly call them you will have to use JNI, but if they were written in Jython you can easily call them from java, as jython ultimately generates java byte code.
Now when I say written in cpython or jython it doesn't make much sense because python is python and most code will run on both implementations unless you are using specific libraries which relies on cpython or java.
This will add an image to another.
using (Graphics grfx = Graphics.FromImage(image))
{
grfx.DrawImage(newImage, x, y)
}
Graphics is in the namespace System.Drawing
What I did not like with many answers is that it makes way too many system calls by writing to the file line per line. Imho it is best to join list with '\n' (line return) and then write it only once to the file:
mylist = ["abc", "def", "ghi"]
myfile = "file.txt"
with open(myfile, 'w') as f:
f.write("\n".join(mylist))
and then to open it and get your list again:
with open(myfile, 'r') as f:
mystring = f.read()
my_list = mystring.split("\n")
public class DateTimeFilter : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
if (filterContext.HttpContext.Request.RequestType == "GET")
{
foreach (var parameter in filterContext.ActionParameters)
{
var properties = parameter.Value.GetType().GetProperties();
foreach (var property in properties)
{
Type type = Nullable.GetUnderlyingType(property.PropertyType) ?? property.PropertyType;
if (property.PropertyType == typeof(System.DateTime) || property.PropertyType == typeof(DateTime?))
{
DateTime dateTime;
if (DateTime.TryParse(filterContext.HttpContext.Request.QueryString[property.Name], CultureInfo.CurrentUICulture, DateTimeStyles.None, out dateTime))
property.SetValue(parameter.Value, dateTime,null);
}
}
}
}
}
}
select * from tab1 where (col1,col2) in (select col1,col2 from tab2)
Note:
Oracle ignores rows where one or more of the selected columns is NULL. In these cases you probably want to make use of the NVL-Funktion to map NULL to a special value (that should not be in the values);
select * from tab1
where (col1, NVL(col2, '---') in (select col1, NVL(col2, '---') from tab2)
In vim column visual mode is Ctrl + v. If that is what you meant?
You can push with using different account. For example, if your account is A which is stored in .gitconfig and you want to use account B which is the owner of the repo you want to push.
Account B: B_user_name, B_password
Example of SSH link: https://github.com/B_user_name/project.git
The push with B account is:
$ git push https://'B_user_name':'B_password'@github.com/B_user_name/project.git
To see the account in .gitconfig
$git config --global --list
$git config --global -e
(to change account also)Look into twitter cards.
The trick is not in the button but rather the page you are sharing. Twitter Cards pull the image from the meta tags similar to facebook
sharing.
Example:
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:site" content="@site_username">
<meta name="twitter:title" content="Top 10 Things Ever">
<meta name="twitter:description" content="Up than 200 characters.">
<meta name="twitter:creator" content="@creator_username">
<meta name="twitter:image" content="http://placekitten.com/250/250">
<meta name="twitter:domain" content="YourDomain.com">
You seem to have used some [Authorize]
attribute on your Web API controller action and I don't see how this is relevant to your question.
So, let's get into practice. Here's a how a trivial Web API controller might look like:
public class TestController : ApiController
{
public string Post([FromBody] string value)
{
return value;
}
}
and a consumer for that matter:
class Program
{
static void Main()
{
using (var client = new WebClient())
{
client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
var data = "=Short test...";
var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
Console.WriteLine(result);
}
}
}
You will undoubtedly notice the [FromBody]
decoration of the Web API controller attribute as well as the =
prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.
As far as the [Authorize]
attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post
that I wrote on this topic interesting to get you started.
And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.
Not sure the key combination that gets you there to the > prompt but it is not a bash prompt that I know. I usually get it by accident. Ctrl+C (or D) gets me back to the $ prompt.
.image_block {
width: 175px;
height: 175px;
position: relative;
}
.image_block a {
width: 100%;
text-align: center;
position: absolute;
bottom: 0px;
}
.image_block img {
/* nothing specific */
}
explanation: an element positioned absolutely will be relative to the closest parent which has a non-static positioning. i'm assuming you're happy with how your .image_block
displays, so we can leave the relative positioning there.
as such, the <a>
element will be positioned relative to the .image_block
, which will give us the bottom alignment. then, we text-align: center
the <a>
element, and give it a 100% width so that it is the size of .image_block
.
the <img>
within <a>
will then center appropriately.
Here's a reusable solution: http://jsfiddle.net/flobar/r28b0gmq/
function accessScope(node, func) {
var scope = angular.element(document.querySelector(node)).scope();
scope.$apply(func);
}
window.onload = function () {
accessScope('#outer', function (scope) {
// change any property inside the scope
scope.name = 'John';
scope.sname = 'Doe';
scope.msg = 'Superhero';
});
};
you can use lst.pop()
or del lst[-1]
pop()
removes and returns the item, in case you don't want have a return use del
I was looking to do the same thing, but to preserve the list as a just an array of strings so I wrote a new code, which from what I've been reading may not be the most efficient but worked for what i needed to do:
combineListsAsOne <-function(list1, list2){
n <- c()
for(x in list1){
n<-c(n, x)
}
for(y in list2){
n<-c(n, y)
}
return(n)
}
It just creates a new list and adds items from two supplied lists to create one.
There are several tools which can import Excel to SQL Server.
I am using DbTransfer (http://www.dbtransfer.com/Products/DbTransfer) to do the job. It's primarily focused on transfering data between databases and excel, xml, etc...
I have tried the openrowset method and the SQL Server Import / Export Assitant before. But I found these methods to be unnecessary complicated and error prone in constrast to doing it with one of the available dedicated tools.
Although John Leidegren keeps shooting down the idea, Brian is correct. I've just got it working in Visual Studio.
To be clear a WPF application does not create a Console window by default.
You have to create a WPF Application and then change the OutputType to "Console Application". When you run the project you will see a console window with your WPF window in front of it.
It doesn't look very pretty, but I found it helpful as I wanted my app to be run from the command line with feedback in there, and then for certain command options I would display the WPF window.
c = np.array([[1,2,3],[4,5,6]])
list(c.flatten())
This is how you get unique from an array with two or more properties. The sort is vital and the key to getting it to work correctly. Otherwise you just get one item returned.
PowerShell Script:
$objects = @(
[PSCustomObject] @{ Message = "1"; MachineName = "1" }
[PSCustomObject] @{ Message = "2"; MachineName = "1" }
[PSCustomObject] @{ Message = "3"; MachineName = "1" }
[PSCustomObject] @{ Message = "4"; MachineName = "1" }
[PSCustomObject] @{ Message = "5"; MachineName = "1" }
[PSCustomObject] @{ Message = "1"; MachineName = "2" }
[PSCustomObject] @{ Message = "2"; MachineName = "2" }
[PSCustomObject] @{ Message = "3"; MachineName = "2" }
[PSCustomObject] @{ Message = "4"; MachineName = "2" }
[PSCustomObject] @{ Message = "5"; MachineName = "2" }
[PSCustomObject] @{ Message = "1"; MachineName = "1" }
[PSCustomObject] @{ Message = "2"; MachineName = "1" }
[PSCustomObject] @{ Message = "3"; MachineName = "1" }
[PSCustomObject] @{ Message = "4"; MachineName = "1" }
[PSCustomObject] @{ Message = "5"; MachineName = "1" }
[PSCustomObject] @{ Message = "1"; MachineName = "2" }
[PSCustomObject] @{ Message = "2"; MachineName = "2" }
[PSCustomObject] @{ Message = "3"; MachineName = "2" }
[PSCustomObject] @{ Message = "4"; MachineName = "2" }
[PSCustomObject] @{ Message = "5"; MachineName = "2" }
)
Write-Host "Sorted on both properties with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message,MachineName -Unique | Out-Host
Write-Host "Sorted on just Message with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property Message -Unique | Out-Host
Write-Host "Sorted on just MachineName with -Unique" -ForegroundColor Yellow
$objects | Sort-Object -Property MachineName -Unique | Out-Host
Output:
Sorted on both properties with -Unique
Message MachineName
------- -----------
1 1
1 2
2 1
2 2
3 1
3 2
4 1
4 2
5 1
5 2
Sorted on just Message with -Unique
Message MachineName
------- -----------
1 1
2 1
3 1
4 1
5 2
Sorted on just MachineName with -Unique
Message MachineName
------- -----------
1 1
3 2
Source: https://powershell.org/forums/topic/need-to-unique-based-on-multiple-properties/
Subtract char '0' or int 48 like this:
char c = '5';
int i = c - '0';
Explanation: Internally it works with ASCII value. From the ASCII table, decimal value of character 5 is 53 and 0 is 48. So 53 - 48 = 5
OR
char c = '5';
int i = c - 48; // Because decimal value of char '0' is 48
That means if you deduct 48 from any numeral character, it will convert integer automatically.
override func prepareForSegue(segue: UIStoryboardSegue?, sender: AnyObject?) {
if(segue!.identifier){
var name = segue!.identifier;
if (name.compare("Load View") == 0){
}
}
}
You can't compare the the identifier with == you have to use the compare() method
<xsl:variable name="count" select="count(/Property/long = $parPropId)"/>
Un-tested but I think that should work. I'm assuming the Property nodes are direct children of the root node and therefor taking out your descendant selector for peformance
Your compiler just tried to compile the file named foo.cc
. Upon hitting line number line
, the compiler finds:
#include "bar"
or
#include <bar>
The compiler then tries to find that file. For this, it uses a set of directories to look into, but within this set, there is no file bar
. For an explanation of the difference between the versions of the include statement look here.
g++
has an option -I
. It lets you add include search paths to the command line. Imagine that your file bar
is in a folder named frobnicate
, relative to foo.cc
(assume you are compiling from the directory where foo.cc
is located):
g++ -Ifrobnicate foo.cc
You can add more include-paths; each you give is relative to the current directory. Microsoft's compiler has a correlating option /I
that works in the same way, or in Visual Studio, the folders can be set in the Property Pages of the Project, under Configuration Properties->C/C++->General->Additional Include Directories.
Now imagine you have multiple version of bar
in different folders, given:
// A/bar
#include<string>
std::string which() { return "A/bar"; }
// B/bar
#include<string>
std::string which() { return "B/bar"; }
// C/bar
#include<string>
std::string which() { return "C/bar"; }
// foo.cc
#include "bar"
#include <iostream>
int main () {
std::cout << which() << std::endl;
}
The priority with #include "bar"
is leftmost:
$ g++ -IA -IB -IC foo.cc
$ ./a.out
A/bar
As you see, when the compiler started looking through A/
, B/
and C/
, it stopped at the first or leftmost hit.
This is true of both forms, include <>
and incude ""
.
#include <bar>
and #include "bar"
Usually, the #include <xxx>
makes it look into system folders first, the #include "xxx"
makes it look into the current or custom folders first.
E.g.:
Imagine you have the following files in your project folder:
list
main.cc
with main.cc
:
#include "list"
....
For this, your compiler will #include
the file list
in your project folder, because it currently compiles main.cc
and there is that file list
in the current folder.
But with main.cc
:
#include <list>
....
and then g++ main.cc
, your compiler will look into the system folders first, and because <list>
is a standard header, it will #include
the file named list
that comes with your C++ platform as part of the standard library.
This is all a bit simplified, but should give you the basic idea.
<>
/""
-priorities and -I
According to the gcc-documentation, the priority for include <>
is, on a "normal Unix system", as follows:
/usr/local/include
libdir/gcc/target/version/include
/usr/target/include
/usr/include
For C++ programs, it will also look in /usr/include/c++/version, first. In the above, target is the canonical name of the system GCC was configured to compile code for; [...].
The documentation also states:
You can add to this list with the -Idir command line option. All the directories named by -I are searched, in left-to-right order, before the default directories. The only exception is when dir is already searched by default. In this case, the option is ignored and the search order for system directories remains unchanged.
To continue our #include<list> / #include"list"
example (same code):
g++ -I. main.cc
and
#include<list>
int main () { std::list<int> l; }
and indeed, the -I.
prioritizes the folder .
over the system includes and we get a compiler error.
You can cast it to
(<any>$('.selector') ).function();
Ex: date picker initialize using jquery
(<any>$('.datepicker') ).datepicker();
Don't forget about CSS3's 'nth-child' selector. If you know the index of the column you wish to align text to the right on, you can just specify
table tr td:nth-child(2) {
text-align: right;
}
In cases with large tables this can save you a lot of extra markup!
here's a fiddle for ya.... https://jsfiddle.net/w16c2nad/
As has been mentioned, as of PHP 5.6+ you can (should!) use the ...
token (aka "splat operator", part of the variadic functions functionality) to easily call a function with an array of arguments:
<?php
function variadic($arg1, $arg2)
{
// Do stuff
echo $arg1.' '.$arg2;
}
$array = ['Hello', 'World'];
// 'Splat' the $array in the function call
variadic(...$array);
// 'Hello World'
Note: array items are mapped to arguments by their position in the array, not their keys.
As per CarlosCarucce's comment, this form of argument unpacking is the fastest method by far in all cases. In some comparisons, it's over 5x faster than call_user_func_array
.
Because I think this is really useful (though not directly related to the question): you can type-hint the splat operator parameter in your function definition to make sure all of the passed values match a specific type.
(Just remember that doing this it MUST be the last parameter you define and that it bundles all parameters passed to the function into the array.)
This is great for making sure an array contains items of a specific type:
<?php
// Define the function...
function variadic($var, SomeClass ...$items)
{
// $items will be an array of objects of type `SomeClass`
}
// Then you can call...
variadic('Hello', new SomeClass, new SomeClass);
// or even splat both ways
$items = [
new SomeClass,
new SomeClass,
];
variadic('Hello', ...$items);
In workbench 6.0 Connect to any of the database. You will see two tabs.
1.Management
2. Schemas
By default Schemas
tab is selected.
Select Management
tab
then select Data Export
.
You will get list of all databases.
select the desired database and and the file name and ther options you wish and start export.
You are done with backup.
You could run jconsole
(included with Java 6's SDK) then connect to your Java application. It will show you every Thread running and its stack trace.
This callable function works perfectly, returns true for valid date. Be sure to call using a date on ISO format (yyyy-mm-dd or yyyy/mm/dd):
function validateDate(isoDate) {
if (isNaN(Date.parse(isoDate))) {
return false;
} else {
if (isoDate != (new Date(isoDate)).toISOString().substr(0,10)) {
return false;
}
}
return true;
}
Try this
let path = "/{id}/{name}/{age}";
const paramsPattern = /[^{\}]+(?=})/g;
let extractParams = path.match(paramsPattern);
console.log("extractParams", extractParams) // prints all the names between {} = ["id", "name", "age"]
(For the record and before the thread disappears on the msdn forums) You can't disable the warning (at least under VS2010) because it is on the list of the warnings that can't be disabled (so /wd4099 will not work), but what you can do instead is patch link.exe (usually C:\Program Files (x86)\Microsoft Visual Studio 10.0\VC\bin\link.exe) to remove it from said list . Sounds like a jackhammer, i know. It works though.
For instance, if you want to remove the warning for 4099, open link.exe with an hex editor, goto line 15A0 which reads 03 10 (little endian for 4099) and replace it with FF 00 (which does not exist.)
I really wish I'd known that you can use CtrlC instead of Esc to switch out of insert mode. That's been a real productivity boost for me.
main()
{
int i = 247593;
char str[10];
sprintf(str, "%d", i);
// Now str contains the integer as characters
}
Hope it will be helpful to you.
From MySQL docs: Fixed-Point Types (Exact Value) - DECIMAL, NUMERIC:
In standard SQL, the syntax
DECIMAL(M)
is equivalent toDECIMAL(M,0)
So, you are converting to a number with 2 integer digits and 0 decimal digits. Try this instead:
CAST((COUNT(*) * 1.5) AS DECIMAL(12,2))
s = "hel\nlo"
raws = '%r'%s #coversion to raw string
#print(raws) will print 'hel\nlo' with single quotes.
print(raws[1:-1]) # will print hel\nlo without single quotes.
#raws[1:-1] string slicing is performed
From search engines, I ended up on this topic for non-json posting data with fetch, so thought I would add this.
For non-json you don't have to use form data. You can simply set the Content-Type
header to application/x-www-form-urlencoded
and use a string:
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: 'foo=bar&blah=1'
});
An alternative way to build that body
string, rather then typing it out as I did above, is to use libraries. For instance the stringify
function from query-string
or qs
packages. So using this it would look like:
import queryString from 'query-string'; // import the queryString class
fetch('url here', {
method: 'POST',
headers: {'Content-Type':'application/x-www-form-urlencoded'}, // this line is important, if this content-type is not set it wont work
body: queryString.stringify({for:'bar', blah:1}) //use the stringify object of the queryString class
});
Even same issue I faced, in browser it was showing compiled code. I have made below changes in webpack config file and it is working fine now.
devtool: '#inline-source-map',
debug: true,
and in loaders I kept babel-loader as first option
loaders: [
{
loader: "babel-loader",
include: [path.resolve(__dirname, "src")]
},
{ test: /\.js$/, exclude: [/app\/lib/, /node_modules/], loader: 'ng-annotate!babel' },
{ test: /\.html$/, loader: 'raw' },
{
test: /\.(jpe?g|png|gif|svg)$/i,
loaders: [
'file?hash=sha512&digest=hex&name=[hash].[ext]',
'image-webpack?bypassOnDebug&optimizationLevel=7&interlaced=false'
]
},
{test: /\.less$/, loader: "style!css!less"},
{ test: /\.styl$/, loader: 'style!css!stylus' },
{ test: /\.css$/, loader: 'style!css' }
]
The reason for the absence of implicit conversion (by design) was given in other answers.
I personally use unary operator+
for the conversion from enum classes to their underlying type:
template <typename T>
constexpr auto operator+(T e) noexcept
-> std::enable_if_t<std::is_enum<T>::value, std::underlying_type_t<T>>
{
return static_cast<std::underlying_type_t<T>>(e);
}
Which gives quite little "typing overhead":
std::cout << foo(+b::B2) << std::endl;
Where I actually use a macro to create enums and the operator functions in one shot.
#define UNSIGNED_ENUM_CLASS(name, ...) enum class name : unsigned { __VA_ARGS__ };\
inline constexpr unsigned operator+ (name const val) { return static_cast<unsigned>(val); }
Double check your autoloader's requirements & namespaces.
/Path/ClassName
) or with a use
statement at the top of your file.contentType
is the type of data you're sending, so application/json; charset=utf-8
is a common one, as is application/x-www-form-urlencoded; charset=UTF-8
, which is the default.
dataType
is what you're expecting back from the server: json
, html
, text
, etc. jQuery will use this to figure out how to populate the success function's parameter.
If you're posting something like:
{"name":"John Doe"}
and expecting back:
{"success":true}
Then you should have:
var data = {"name":"John Doe"}
$.ajax({
dataType : "json",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
alert(result.success); // result is an object which is created from the returned JSON
},
});
If you're expecting the following:
<div>SUCCESS!!!</div>
Then you should do:
var data = {"name":"John Doe"}
$.ajax({
dataType : "html",
contentType: "application/json; charset=utf-8",
data : JSON.stringify(data),
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
One more - if you want to post:
name=John&age=34
Then don't stringify
the data, and do:
var data = {"name":"John", "age": 34}
$.ajax({
dataType : "html",
contentType: "application/x-www-form-urlencoded; charset=UTF-8", // this is the default value, so it's optional
data : data,
success : function(result) {
jQuery("#someContainer").html(result); // result is the HTML text
},
});
I think this may help you solve your issue.
Imagine you have a dictionary like this:
dic0 = {0:"CL1", 1:"CL2", 2:"CL3"}
And you want to change values by this one:
dic0to1 = {"CL1":"Unknown1", "CL2":"Unknown2", "CL3":"Unknown3"}
You can use code bellow to change values of dic0
properly respected to dic0t01
without worrying yourself about indexes in dictionary:
for x, y in dic0.items():
dic0[x] = dic0to1[y]
Now you have:
>>> dic0
{0: 'Unknown1', 1: 'Unknown2', 2: 'Unknown3'}
You can show them with rake routes
directly.
In a Rails console, you can call app.post_path
. This will work in Rails ~= 2.3 and >= 3.1.0.
This is the your node is not properly install, first you need to uninstall the node then install again. To install the node this may help you http://array151.com/blog/nodejs-tutorial-and-set-up/
after that you can install the packages easily. To install the packages this may help you
This works perfectly
<i class="fa fa-power-off text-gray" style="transform: rotate(90deg);"></i>
I found something from Arvind Pereira (http://robotics.usc.edu/~ampereir/wordpress/?p=626) and seemed to work for me:
plt.savefig(filename, transparent = True, bbox_inches = 'tight', pad_inches = 0)
There is a race condition in the accepted answer when 2 processes running under 2 different users trying to initialize the mutex at the same time. After the first process initializes the mutex, if the second process tries to initialize the mutex before the first process sets the access rule to everyone, an unauthorized exception will be thrown by the second process.
See below for corrected answer:
using System.Runtime.InteropServices; //GuidAttribute
using System.Reflection; //Assembly
using System.Threading; //Mutex
using System.Security.AccessControl; //MutexAccessRule
using System.Security.Principal; //SecurityIdentifier
static void Main(string[] args)
{
// get application GUID as defined in AssemblyInfo.cs
string appGuid = ((GuidAttribute)Assembly.GetExecutingAssembly().GetCustomAttributes(typeof(GuidAttribute), false).GetValue(0)).Value.ToString();
// unique id for global mutex - Global prefix means it is global to the machine
string mutexId = string.Format( "Global\\{{{0}}}", appGuid );
bool createdNew;
// edited by Jeremy Wiebe to add example of setting up security for multi-user usage
// edited by 'Marc' to work also on localized systems (don't use just "Everyone")
var allowEveryoneRule = new MutexAccessRule(new SecurityIdentifier(WellKnownSidType.WorldSid, null), MutexRights.FullControl, AccessControlType.Allow);
var securitySettings = new MutexSecurity();
securitySettings.AddAccessRule(allowEveryoneRule);
using (var mutex = new Mutex(false, mutexId, out createdNew, securitySettings))
{
// edited by acidzombie24
var hasHandle = false;
try
{
try
{
// note, you may want to time out here instead of waiting forever
// edited by acidzombie24
// mutex.WaitOne(Timeout.Infinite, false);
hasHandle = mutex.WaitOne(5000, false);
if (hasHandle == false)
throw new TimeoutException("Timeout waiting for exclusive access");
}
catch (AbandonedMutexException)
{
// Log the fact the mutex was abandoned in another process, it will still get aquired
hasHandle = true;
}
// Perform your work here.
}
finally
{
// edited by acidzombie24, added if statemnet
if(hasHandle)
mutex.ReleaseMutex();
}
}
}
Why don't you place your table in a div?
<div style="height:100px;overflow:auto;">
... Your code goes here ...
</div>
In your test, you are comparing the two TestParent
beans, not the single TestedChild
bean.
Also, Spring proxies your @Configuration
class so that when you call one of the @Bean
annotated methods, it caches the result and always returns the same object on future calls.
See here:
We're using OpenCV. It has lots of non-face-recognition stuff in there also, but, rest assured, it does do face-recognition.
There's no difference, ==
is a synonym for =
(for the C/C++ people, I assume). See here, for example.
You could double-check just to be really sure or just for your interest by looking at the bash source code, should be somewhere in the parsing code there, but I couldn't find it straightaway.
If you use PHP 7.4 or later you can also do it using arrow function so it looks cleaner:
Post::with(['user' => fn ($query) => $query->select('id','username')])->get();
The maven dependency plugin can potentially solve your problem.
If you have a pom
with all your project dependencies specified, all you would need to do is run
mvn dependency:copy-dependencies
and you will find the target/dependencies
folder filled with all the dependencies, including transitive.
Adding Gustavo's answer from below: To download the dependency sources, you can use
mvn dependency:copy-dependencies -Dclassifier=sources
I'll try to give a proper answer myself:
The only punctuations that should be allowed in a name are full stop, apostrophe and hyphen. I haven't seen any other case in the list of corner cases.
Regarding numbers, there's only one case with an 8. I think I can safely disallow that.
Regarding letters, any letter is valid.
I also want to include space.
This would sum up to this regex:
^[\p{L} \.'\-]+$
This presents one problem, i.e. the apostrophe can be used as an attack vector. It should be encoded.
So the validation code should be something like this (untested):
var name = nameParam.Trim();
if (!Regex.IsMatch(name, "^[\p{L} \.\-]+$"))
throw new ArgumentException("nameParam");
name = name.Replace("'", "'"); //' does not work in IE
Can anyone think of a reason why a name should not pass this test or a XSS or SQL Injection that could pass?
complete tested solution
using System;
using System.Text.RegularExpressions;
namespace test
{
class MainClass
{
public static void Main(string[] args)
{
var names = new string[]{"Hello World",
"John",
"João",
"???",
"???",
"??",
"??",
"??????",
"Te???e?a",
"?????????",
"???? ?????",
"?????????",
"??????",
"?",
"D'Addario",
"John-Doe",
"P.A.M.",
"' --",
"<xss>",
"\""
};
foreach (var nameParam in names)
{
Console.Write(nameParam+" ");
var name = nameParam.Trim();
if (!Regex.IsMatch(name, @"^[\p{L}\p{M}' \.\-]+$"))
{
Console.WriteLine("fail");
continue;
}
name = name.Replace("'", "'");
Console.WriteLine(name);
}
}
}
}
If you assume that 0 is not a valid item in the array then the following code should work:
public static void main( String[] args )
{
int[] theArray = new int[20];
theArray[0] = 1;
theArray[1] = 2;
System.out.println(count(theArray));
}
private static int count(int[] array)
{
int count = 0;
for(int i : array)
{
if(i > 0)
{
count++;
}
}
return count;
}
#include <iostream>
#include <iomanip>
#include <sstream>
int main()
{
int x, y;
std::stringstream stream;
std::cin >> x;
stream << x;
stream >> std::hex >> y;
std::cout << y;
return 0;
}
-- Search in All Objects
SELECT OBJECT_NAME(OBJECT_ID),
definition
FROM sys.sql_modules
WHERE definition LIKE '%' + 'ColumnName' + '%'
GO
-- Search in Stored Procedure Only
SELECT DISTINCT OBJECT_NAME(OBJECT_ID)
FROM sys.Procedures
WHERE object_definition(OBJECT_ID) LIKE '%' + 'ColumnName' + '%'
GO
The underlying problem revolves around accessing the data within the array, as Felix Kling points out in the first response.
In the following code, I've accessed the values of the array with the print and echo constructs.
function data()
{
$a = "abc";
$b = "def";
$c = "ghi";
$array = array($a, $b, $c);
print_r($array);//outputs the key/value pair
echo "<br>";
echo $array[0].$array[1].$array[2];//outputs a concatenation of the values
}
data();
DateTime does not know its timezone offset. There is no built-in method to return the offset or the timezone name (e.g. EAT, CEST, EST etc).
Like suggested by others, you can convert your date to UTC:
DateTime localtime = new DateTime.Now;
var utctime = localtime.ToUniversalTime();
and then only calculate the difference:
TimeSpan difference = localtime - utctime;
Also you may convert one time to another by using the DateTimeOffset:
DateTimeOffset targetTime = DateTimeOffset.Now.ToOffset(new TimeSpan(5, 30, 0));
But this is sort of lossy compression - the offset alone cannot tell you which time zone it is as two different countries may be in different time zones and have the same time only for part of the year (eg. South Africa and Europe). Also, be aware that summer daylight saving time may be introduced at different dates (EST vs CET - a 3-week difference).
You can get the name of your local system time zone using TimeZoneInfo class:
TimeZoneInfo localZone = TimeZoneInfo.Local;
localZone.IsDaylightSavingTime(localtime) ? localZone.DaylightName : localZone.StandardName
I agree with Gerrie Schenck, please read the article he suggested.
//an easy way:
str := fmt.Sprint(data)
If you like to remove last 5 characters, you can use:
path.substring(0,path.length() - 5)
( could contain off by one error ;) )
If you like to remove some variable string:
path.substring(0,path.lastIndexOf('yoursubstringtoremove));
(could also contain off by one error ;) )
Are you sure your processor supports Intel Virtualization (VT-x) or AMD Virtualization (AMD-V)?
Here you can find Hardware-Assisted Virtualization Detection Tool ( http://www.microsoft.com/downloads/en/details.aspx?FamilyID=0ee2a17f-8538-4619-8d1c-05d27e11adb2&displaylang=en) which will tell you if your hardware supports VT-x.
Alternatively you can find your processor here: http://ark.intel.com/Default.aspx. All AMD processors since 2006 supports Virtualization.
There are 2 major differences.
Technical, there are 3 major differences:
First and foremost, Community doesn't have TFS support.
You'll just have to use git (arguable whether this constitutes a disadvantage or whether this actually is a good thing).
Note: This is what MS wrote. Actually, you can check-in&out with TFS as normal, if you have a TFS server in the network. You just cannot use Visual Studio as TFS SERVER.
Second, VS Community is severely limited in its testing capability.
Only unit tests. No Performance tests, no load tests, no performance profiling.
Third, VS Community's ability to create Virtual Environments has been severely cut.
On the other hand, syntax highlighting, IntelliSense, Step-Through debugging, GoTo-Definition, Git-Integration and Build/Publish are really all the features I need, and I guess that applies to a lot of developers.
For all other things, there are tools that do the same job faster, better and cheaper.
If you, like me, anyway use git, do unit testing with NUnit, and use Java-Tools to do Load-Testing on Linux plus TeamCity for CI, VS Community is more than sufficient, technically speaking.
Licensing:
A) If you're an individual developer (no enterprise, no organization), no difference (AFAIK), you can use CommunityEdition like you'd use the paid edition (as long as you don't do subcontracting)
B) You can use CommunityEdition freely for OpenSource (OSI) projects
C) If you're an educational insitution, you can use CommunityEdition freely (for education/classroom use)
D) If you're an enterprise with 250 PCs or users or more than one million US dollars in revenue (including subsidiaries), you are NOT ALLOWED to use CommunityEdition.
E) If you're not an enterprise as defined above, and don't do OSI or education, but are an "enterprise"/organization, with 5 or less concurrent (VS) developers, you can use VS Community freely (but only if you're the owner of the software and sell it, not if you're a subcontractor creating software for a larger enterprise, software which in the end the enterprise will own), otherwise you need a paid edition.
The above does not consitute legal advise.
See also:
https://softwareengineering.stackexchange.com/questions/262916/understanding-visual-studio-community-edition-license
The proper interval to get one second is 1000. The Interval
property is the time between ticks in milliseconds:
So, it's not the interval that you set that is wrong. Check the rest of your code for something like changing the interval of the timer, or binding the Tick
event multiple times.
"+" is correct. If you really need %20, then replace the Plusses yourself afterwards.
Warning: This answer is heavily disputed (+8 vs. -6), so take this with a grain of salt.
One way:
SELECT DISTINCT sc.StoreId
FROM StoreClients sc
WHERE NOT EXISTS(
SELECT * FROM StoreClients sc2
WHERE sc2.StoreId = sc.StoreId AND sc2.ClientId = 5)
Use the attribute 'display' as in the example:
<span style="background: gray; width: 100px; display:block;">hello</span>
<span style="background: gray; width: 200px; display:block;">world</span>
My vote is string.Join
No need for lambda evaluations and temporary functions to be created, fewer function calls, less stack pushing and popping.
To update this for Python-3 you can do this
"{} {}".format(True, False)
However if you want to actually format the string (e.g. add white space), you encounter Python casting the boolean into the underlying C value (i.e. an int), e.g.
>>> "{:<8} {}".format(True, False)
'1 False'
To get around this you can cast True
as a string, e.g.
>>> "{:<8} {}".format(str(True), False)
'True False'
I know this is old, but just to make it clear, there is an explanation of each in the official android documentation:
from http://developer.android.com/tools/projects/index.html
assets/
This is empty. You can use it to store raw asset files. Files that you save here are compiled into an .apk file as-is, and the original filename is preserved. You can navigate this directory in the same way as a typical file system using URIs and read files as a stream of bytes using the AssetManager. For example, this is a good location for textures and game data.
res/raw/
For arbitrary raw asset files. Saving asset files here instead of in the assets/ directory only differs in the way that you access them. These files are processed by aapt and must be referenced from the application using a resource identifier in the R class. For example, this is a good place for media, such as MP3 or Ogg files.
This works:
package main
import (
"fmt"
"os"
"os/signal"
"syscall"
"time" // or "runtime"
)
func cleanup() {
fmt.Println("cleanup")
}
func main() {
c := make(chan os.Signal)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
go func() {
<-c
cleanup()
os.Exit(1)
}()
for {
fmt.Println("sleeping...")
time.Sleep(10 * time.Second) // or runtime.Gosched() or similar per @misterbee
}
}
This link shows how to list all the active properties: http://skillshared.blogspot.co.uk/2012/11/how-to-list-down-all-maven-available.html
In summary, add the following plugin definition to your POM, then run mvn install
:
<plugin>
<artifactId>maven-antrun-plugin</artifactId>
<version>1.7</version>
<executions>
<execution>
<phase>install</phase>
<configuration>
<target>
<echoproperties />
</target>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
</executions>
</plugin>
As Matt said, the curly braces are for concatenation. The extra curly braces around 16{a[15]}
are the replication operator. They are described in the IEEE Standard for Verilog document (Std 1364-2005), section "5.1.14 Concatenations".
{16{a[15]}}
is the same as
{
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15],
a[15], a[15], a[15], a[15], a[15], a[15], a[15], a[15]
}
In bit-blasted form,
assign result = {{16{a[15]}}, {a[15:0]}};
is the same as:
assign result[ 0] = a[ 0];
assign result[ 1] = a[ 1];
assign result[ 2] = a[ 2];
assign result[ 3] = a[ 3];
assign result[ 4] = a[ 4];
assign result[ 5] = a[ 5];
assign result[ 6] = a[ 6];
assign result[ 7] = a[ 7];
assign result[ 8] = a[ 8];
assign result[ 9] = a[ 9];
assign result[10] = a[10];
assign result[11] = a[11];
assign result[12] = a[12];
assign result[13] = a[13];
assign result[14] = a[14];
assign result[15] = a[15];
assign result[16] = a[15];
assign result[17] = a[15];
assign result[18] = a[15];
assign result[19] = a[15];
assign result[20] = a[15];
assign result[21] = a[15];
assign result[22] = a[15];
assign result[23] = a[15];
assign result[24] = a[15];
assign result[25] = a[15];
assign result[26] = a[15];
assign result[27] = a[15];
assign result[28] = a[15];
assign result[29] = a[15];
assign result[30] = a[15];
assign result[31] = a[15];
In my case it was due to 'lower_case_table_names' parameter.
The error number 39 thrown out when I tried to drop the databases which consists upper case table names with lower_case_table_names parameter is enabled.
This is fixed by reverting back the lower case parameter changes to the previous state.
one of the other tool (besides file) you can use is xdg-mime
eg xdg-mime query filetype <file>
if you have yum,
yum install xdg-utils.noarch
An example comparison of xdg-mime and file on a Subrip(subtitles) file
$ xdg-mime query filetype subtitles.srt
application/x-subrip
$ file --mime-type subtitles.srt
subtitles.srt: text/plain
in the above file only show it as plain text.
class LinksParser(HTMLParser.HTMLParser):
def __init__(self):
HTMLParser.HTMLParser.__init__(self)
self.recording = 0
self.data = []
def handle_starttag(self, tag, attributes):
if tag != 'div':
return
if self.recording:
self.recording += 1
return
for name, value in attributes:
if name == 'id' and value == 'remository':
break
else:
return
self.recording = 1
def handle_endtag(self, tag):
if tag == 'div' and self.recording:
self.recording -= 1
def handle_data(self, data):
if self.recording:
self.data.append(data)
self.recording
counts the number of nested div
tags starting from a "triggering" one. When we're in the sub-tree rooted in a triggering tag, we accumulate the data in self.data
.
The data at the end of the parse are left in self.data
(a list of strings, possibly empty if no triggering tag was met). Your code from outside the class can access the list directly from the instance at the end of the parse, or you can add appropriate accessor methods for the purpose, depending on what exactly is your goal.
The class could be easily made a bit more general by using, in lieu of the constant literal strings seen in the code above, 'div'
, 'id'
, and 'remository'
, instance attributes self.tag
, self.attname
and self.attvalue
, set by __init__
from arguments passed to it -- I avoided that cheap generalization step in the code above to avoid obscuring the core points (keep track of a count of nested tags and accumulate data into a list when the recording state is active).
For readonly/disabled and other attributes with true/false values
$(':submit').attr('disabled', function(_, attr){ return !attr});
Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict
In your case, sort the dict by key before plotting,
import matplotlib.pylab as plt
lists = sorted(d.items()) # sorted by key, return a list of tuples
x, y = zip(*lists) # unpack a list of pairs into two tuples
plt.plot(x, y)
plt.show()
This error occurs when Gradle files are not completely downloaded or corrupted by some other reason, so we have to redownload the files. The easy way is to delete the old files in
C:\Users\username.gradle\wrapper\dists
and rebuild the project, Android Studio will automatically download the new files.
If you actually have set a root password and you've just lost/forgotten it:
Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables
Now, open a new terminal window and run the MySQL client: mysql -u root
Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root';
If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:
UPDATE mysql.user SET authentication_string=PASSWORD('password') WHERE User='root';
Flush the privileges with this MySQL command: FLUSH PRIVILEGES;
From http://www.tech-faq.com/reset-mysql-password.shtml
(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)
<resources>
<!-- Base application theme. -->
<style name="AppTheme" parent="android:Theme.Holo.NoActionBar">
<item name="android:windowBackground">@android:color/black</item>
</style>
</resources>
To elaborate some more on this, adding
script-src 'self' http://somedomain 'unsafe-inline' 'unsafe-eval';
to the meta tag like so,
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; script-src 'self' https://somedomain.com/ 'unsafe-inline' 'unsafe-eval'; media-src *">
fixes the error.
Try this for Dynamic Casting. It will work!!!
String something = "1234";
String theType = "java.lang.Integer";
Class<?> theClass = Class.forName(theType);
Constructor<?> cons = theClass.getConstructor(String.class);
Object ob = cons.newInstance(something);
System.out.println(ob.equals(1234));
yourbox {
position: absolute;
left: 100%;
top: 0;
}
left:100%; is the important issue here!
In java 8:
Optional<String> firstElement = collection.stream().findFirst();
For older versions of java, there is a getFirst method in Guava Iterables:
Iterables.getFirst(iterable, defaultValue)
Handy Swift 4 extension, in case it's helpful to someone else. Works even if the current view controller does not display a navigation bar.
import UIKit
extension UINavigationController {
static public func navBarHeight() -> CGFloat {
let nVc = UINavigationController(rootViewController: UIViewController(nibName: nil, bundle: nil))
let navBarHeight = nVc.navigationBar.frame.size.height
return navBarHeight
}
}
Usage:
UINavigationController.navBarHeight()
User float:left
property in child div class
check for div structure in detail : http://www.dzone.com/links/r/div_table.html
It appears that both methods pretty much do the same thing, but the compareTo() method takes in a String, not an Object, and adds some extra functionality on top of the normal equals() method. If all you care about is equality, then the equals() method is the best choice, simply because it makes more sense to the next programmer that takes a look at your code. The time difference between the two different functions shouldn't matter unless you're looping over some huge amount of items. The compareTo() is really useful when you need to know the order of Strings in a collection or when you need to know the difference in length between strings that start with the same sequence of characters.
source: http://java.sun.com/javase/6/docs/api/java/lang/String.html
I think Dan and Nicola have suitable corrected code, however you may not be clear on why the original code didn't work.
What has been called here a "ternary operator" is called a conditional operator in ECMA-262 section 11.12. It has the form:
LogicalORExpression ? AssignmentExpression : AssignmentExpression
The LogicalORExpression is evaluated and the returned value converted to Boolean (just like an expression in an if condition). If it evaluates to true, then the first AssignmentExpression is evaluated and the returned value returned, otherwise the second is evaluated and returned.
The error in the original code is the extra semi-colons that change the attempted conditional operator into a series of statements with syntax errors.
Here is some more cool knowledge to go with this:
I had a situation where I needed to be able to find folders based on a bit of criteria in the record and then open the folder(s) that were found. While doing work on finding a solution I created a small database that asks for a search starting folder gives a place for 4 pieces of criteria and then allows the user to do criteria matching that opens the 4 (or more) possible folders that match the entered criteria.
Here is the whole code on the form:
Option Compare Database
Option Explicit
Private Sub cmdChooseFolder_Click()
Dim inputFileDialog As FileDialog
Dim folderChosenPath As Variant
If MsgBox("Clear List?", vbYesNo, "Clear List") = vbYes Then DoCmd.RunSQL "DELETE * FROM tblFileList"
Me.sfrmFolderList.Requery
Set inputFileDialog = Application.FileDialog(msoFileDialogFolderPicker)
With inputFileDialog
.Title = "Select Folder to Start with"
.AllowMultiSelect = False
If .Show = False Then Exit Sub
folderChosenPath = .SelectedItems(1)
End With
Me.txtStartPath = folderChosenPath
Call subListFolders(Me.txtStartPath, 1)
End Sub
Private Sub cmdFindFolderPiece_Click()
Dim strCriteria As String
Dim varCriteria As Variant
Dim varIndex As Variant
Dim intIndex As Integer
varCriteria = Array(Nz(Me.txtSerial, "Null"), Nz(Me.txtCustomerOrder, "Null"), Nz(Me.txtAXProject, "Null"), Nz(Me.txtWorkOrder, "Null"))
intIndex = 0
For Each varIndex In varCriteria
strCriteria = varCriteria(intIndex)
If strCriteria <> "Null" Then
Call fnFindFoldersWithCriteria(TrailingSlash(Me.txtStartPath), strCriteria, 1)
End If
intIndex = intIndex + 1
Next varIndex
Set varIndex = Nothing
Set varCriteria = Nothing
strCriteria = ""
End Sub
Private Function fnFindFoldersWithCriteria(ByVal strStartPath As String, ByVal strCriteria As String, intCounter As Integer)
Dim fso As New FileSystemObject
Dim fldrStartFolder As Folder
Dim subfldrInStart As Folder
Dim subfldrInSubFolder As Folder
Dim subfldrInSubSubFolder As String
Dim strActionLog As String
Set fldrStartFolder = fso.GetFolder(strStartPath)
' Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(fldrStartFolder.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path
If fnCompareCriteriaWithFolderName(fldrStartFolder.Name, strCriteria) Then
' Debug.Print "Found and Opening: " & fldrStartFolder.Name & "Because of: " & strCriteria
Shell "EXPLORER.EXE" & " " & Chr(34) & fldrStartFolder.Path & Chr(34), vbNormalFocus
Else
For Each subfldrInStart In fldrStartFolder.SubFolders
intCounter = intCounter + 1
Debug.Print "Criteria: " & Replace(strCriteria, " ", "", 1, , vbTextCompare) & " and Folder Name is " & Replace(subfldrInStart.Name, " ", "", 1, , vbTextCompare) & " and Path is: " & fldrStartFolder.Path
If fnCompareCriteriaWithFolderName(subfldrInStart.Name, strCriteria) Then
' Debug.Print "Found and Opening: " & subfldrInStart.Name & "Because of: " & strCriteria
Shell "EXPLORER.EXE" & " " & Chr(34) & subfldrInStart.Path & Chr(34), vbNormalFocus
Else
Call fnFindFoldersWithCriteria(subfldrInStart, strCriteria, intCounter)
End If
Me.txtProcessed = intCounter
Me.txtProcessed.Requery
Next
End If
Set fldrStartFolder = Nothing
Set subfldrInStart = Nothing
Set subfldrInSubFolder = Nothing
Set fso = Nothing
End Function
Private Function fnCompareCriteriaWithFolderName(strFolderName As String, strCriteria As String) As Boolean
fnCompareCriteriaWithFolderName = False
fnCompareCriteriaWithFolderName = InStr(1, Replace(strFolderName, " ", "", 1, , vbTextCompare), Replace(strCriteria, " ", "", 1, , vbTextCompare), vbTextCompare) > 0
End Function
Private Sub subListFolders(ByVal strFolders As String, intCounter As Integer)
Dim dbs As Database
Dim fso As New FileSystemObject
Dim fldFolders As Folder
Dim fldr As Folder
Dim subfldr As Folder
Dim sfldFolders As String
Dim strSQL As String
Set fldFolders = fso.GetFolder(TrailingSlash(strFolders))
Set dbs = CurrentDb
strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldFolders.Path & Chr(34) & ", " & Chr(34) & fldFolders.Name & Chr(34) & ", '" & fldFolders.Size & "')"
dbs.Execute strSQL
For Each fldr In fldFolders.SubFolders
intCounter = intCounter + 1
strSQL = "INSERT INTO tblFileList (FilePath, FileName, FolderSize) VALUES (" & Chr(34) & fldr.Path & Chr(34) & ", " & Chr(34) & fldr.Name & Chr(34) & ", '" & fldr.Size & "')"
dbs.Execute strSQL
For Each subfldr In fldr.SubFolders
intCounter = intCounter + 1
sfldFolders = subfldr.Path
Call subListFolders(sfldFolders, intCounter)
Me.sfrmFolderList.Requery
Next
Me.txtListed = intCounter
Me.txtListed.Requery
Next
Set fldFolders = Nothing
Set fldr = Nothing
Set subfldr = Nothing
Set dbs = Nothing
End Sub
Private Function TrailingSlash(varIn As Variant) As String
If Len(varIn) > 0& Then
If Right(varIn, 1&) = "\" Then
TrailingSlash = varIn
Else
TrailingSlash = varIn & "\"
End If
End If
End Function
The form has a subform based on the table, the form has 4 text boxes for the criteria, 2 buttons leading to the click procedures and 1 other text box to store the string for the start folder. There are 2 text boxes that are used to show the number of folders listed and the number processed when searching them for the criteria.
If I had the Rep I would post a picture... :/
I have some other things I wanted to add to this code but haven't had the chance yet. I want to have a way to store the ones that worked in another table or get the user to mark them as good to store.
I can not claim full credit for all the code, I cobbled some of it together from stuff I found all around, even in other posts on stackoverflow.
I really like the idea of posting questions here and then answering them yourself because as the linked article says, it makes it easy to find the answer for later reference.
When I finish the other parts I want to add I will post the code for that too. :)
If USB Debugging Mode is enabled and does not work, you should install your device driver.
For Nexus Devices;
For Another Devices;
Hope it helps!
Try this:
#include <QDebug>
QString string;
// do things...
qDebug() << "right" << string << std::endl;
It's just a syntax error. You just have to replace j+3
by j=j+3
or j+=3
.
Joe Kington's excellent answer is already 4 years old,
Matplotlib has incrementally changed (in particular, the introduction
of the cycler
module) and the new major release, Matplotlib 2.0.x,
has introduced stylistic differences that are important from the point
of view of the colors used by default.
The color of individual lines (as well as the color of different plot
elements, e.g., markers in scatter plots) is controlled by the color
keyword argument,
plt.plot(x, y, color=my_color)
my_color
is either
(0.,0.5,0.5)
),"#008080"
(RGB) or "#008080A0"
),"k"
for black, possible values in "bgrcmykw"
),"teal"
) --- aka HTML color name (in the docs also X11/CSS4 color name),'xkcd:'
(e.g., 'xkcd:barbie pink'
),'T10'
categorical palette, (e.g., 'tab:blue'
, 'tab:olive'
),"C3"
, i.e., the letter "C"
followed by a single digit in "0-9"
).By default, different lines are plotted using different colors, that are defined by default and are used in a cyclic manner (hence the name color cycle).
The color cycle is a property of the axes
object, and in older
releases was simply a sequence of valid color names (by default a
string of one character color names, "bgrcmyk"
) and you could set it
as in
my_ax.set_color_cycle(['kbkykrkg'])
(as noted in a comment this API has been deprecated, more on this later).
In Matplotlib 2.0 the default color cycle is ["#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf"]
, the Vega category10 palette.
(the image is a screenshot from https://vega.github.io/vega/docs/schemes/)
The following code shows that the color cycle notion has been deprecated
In [1]: from matplotlib import rc_params
In [2]: rc_params()['axes.color_cycle']
/home/boffi/lib/miniconda3/lib/python3.6/site-packages/matplotlib/__init__.py:938: UserWarning: axes.color_cycle is deprecated and replaced with axes.prop_cycle; please use the latter.
warnings.warn(self.msg_depr % (key, alt_key))
Out[2]:
['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd',
'#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf']
Now the relevant property is the 'axes.prop_cycle'
In [3]: rc_params()['axes.prop_cycle']
Out[3]: cycler('color', ['#1f77b4', '#ff7f0e', '#2ca02c', '#d62728', '#9467bd', '#8c564b', '#e377c2', '#7f7f7f', '#bcbd22', '#17becf'])
Previously, the color_cycle
was a generic sequence of valid color
denominations, now by default it is a cycler
object containing a
label ('color'
) and a sequence of valid color denominations. The
step forward with respect to the previous interface is that it is
possible to cycle not only on the color of lines but also on other
line attributes, e.g.,
In [5]: from cycler import cycler
In [6]: new_prop_cycle = cycler('color', ['k', 'r']) * cycler('linewidth', [1., 1.5, 2.])
In [7]: for kwargs in new_prop_cycle: print(kwargs)
{'color': 'k', 'linewidth': 1.0}
{'color': 'k', 'linewidth': 1.5}
{'color': 'k', 'linewidth': 2.0}
{'color': 'r', 'linewidth': 1.0}
{'color': 'r', 'linewidth': 1.5}
{'color': 'r', 'linewidth': 2.0}
As you have seen, the cycler
objects are composable and when you iterate on a composed cycler
what you get, at each iteration, is a dictionary of keyword arguments for plt.plot
.
You can use the new defaults on a per axes
object ratio,
my_ax.set_prop_cycle(new_prop_cycle)
or you can install temporarily the new default
plt.rc('axes', prop_cycle=new_prop_cycle)
or change altogether the default editing your .matplotlibrc
file.
Last possibility, use a context manager
with plt.rc_context({'axes.prop_cycle': new_prop_cycle}):
...
to have the new cycler
used in a group of different plots, reverting to defaults at the end of the context.
The doc string of the cycler()
function is useful, but the (not so much) gory details about the cycler
module and the cycler()
function, as well as examples, can be found in the fine docs.
Click "Tab Moves Focus" at the bottom right in the status bar.
I believe I had clicked on ctrl+M. When doing this, the "Tab Moves Focus" tab/button showed up at the bottom right. Clicking on that makes it go away and starts working again.
in response to mattlant's reply - sharepoint will work well as a version control only if the version control feature is turned on in the document library. in addition be aware that any code that calls other files by relative paths wont work. and finally any links to external files will break when a file is saved in sharepoint.
You can run Git (not the whole Github) via Apache HTTP Server, so that you host the Git repo on your server's filesystem and expose it via HTTP.
You get all Git functionalities, but obviously you won't be able to pull-request
or track issues. Any tool attached to your self-hosted Git repo can implement the rest of the features.
Reference: http://git-scm.com/docs/git-http-backend
First, you'll need to add session_start()
at the top of any page that you wish to use SESSION
variables on.
Also, you should check to make sure the variable is set first before using it:
if(isset($_SESSION['SESS_fname'])){
echo $_SESSION['SESS_fname'];
}
Or, simply:
echo (isset($_SESSION['SESS_fname']) ? $_SESSION['SESS_fname'] : "Visitor");
Albeit very similar to a previous suggestion, I like to keep it simple and apply the following:
string MyFancyString = "*";
int strLength = 50;
System.Console.WriteLine(MyFancyString.PadRight(strLength, "*");
Standard .Net really,
This helped me:
<p>Date/Time: <span id="datetime"></span></p><script>var dt = new Date();
document.getElementById("datetime").innerHTML=dt.toLocaleString();</script>
Another option is to change the version number in the packages.config
file. This will cause NuGet to download the dlls for that version the next time you build.
jqplugin: http://code.google.com/p/jqplugin/
$.browser.flash == true
Add a reference to Microsoft.VisualBasic.dll, as someone mentioned above. Then getting total physical memory is as simple as this (yes, I tested it):
static ulong GetTotalMemoryInBytes()
{
return new Microsoft.VisualBasic.Devices.ComputerInfo().TotalPhysicalMemory;
}
Tomcat is just a servlet container, i.e. it implements only the servlets and JSP specification. Glassfish and JBoss are full Java EE servers (including stuff like EJB, JMS, ...), with Glassfish being the reference implementation of the latest Java EE 6 stack, but JBoss in 2010 was not fully supporting it yet.
Jquery One-liners:
ES6 + jQuery:
$('#select').append([...Array(100).keys()].map((i,j) => `< option >${i}</option >`))
Lodash + jQuery:
$('#select').append(_.range(100).map(function(i,j){ return $('<option>',{text:i})}))
In my Angular Bootstrap dropdowns I initialize the JSON Array (vm.zoneDropdown) with ng-init (you can also have ng-init inside the directive template) and I pass the Array in a custom src attribute
<custom-dropdown control-id="zone" label="Zona" model="vm.form.zone" src="vm.zoneDropdown"
ng-init="vm.getZoneDropdownSrc()" is-required="true" form="farmaciaForm" css-class="custom-dropdown col-md-3"></custom-dropdown>
Inside the controller:
vm.zoneDropdown = [];
vm.getZoneDropdownSrc = function () {
vm.zoneDropdown = $customService.getZone();
}
And inside the customDropdown directive template(note that this is only one part of the bootstrap dropdown):
<ul class="uib-dropdown-menu" role="menu" aria-labelledby="btn-append-to-body">
<li role="menuitem" ng-repeat="dropdownItem in vm.src" ng-click="vm.setValue(dropdownItem)">
<a ng-click="vm.preventDefault($event)" href="##">{{dropdownItem.text}}</a>
</li>
</ul>
To get date and time of your zone.
Date date = new Date();
DateFormat df = new SimpleDateFormat("MM/dd/YYYY HH:mm a");
df.setTimeZone(TimeZone.getDefault());
df.format(date);
Employee emp1 = new Employee() { ID = 1, Name = "Narendra1", Salary = 11111, Experience = 3, Age = 30 };Employee emp2 = new Employee() { ID = 2, Name = "Narendra2", Salary = 21111, Experience = 10, Age = 38 };
Employee emp3 = new Employee() { ID = 3, Name = "Narendra3", Salary = 31111, Experience = 4, Age = 33 };
Employee emp4 = new Employee() { ID = 3, Name = "Narendra4", Salary = 41111, Experience = 7, Age = 33 };
List<Employee> lstEmployee = new List<Employee>();
lstEmployee.Add(emp1);
lstEmployee.Add(emp2);
lstEmployee.Add(emp3);
lstEmployee.Add(emp4);
var eemmppss=lstEmployee.Select(cc=>new {cc.ID,cc.Age}).Distinct();
Mouse.GetPosition(mWindow)
gives you the mouse position relative to the parameter of your choice.
mWindow.PointToScreen()
convert the position to a point relative to the screen.
So mWindow.PointToScreen(Mouse.GetPosition(mWindow))
gives you the mouse position relative to the screen, assuming that mWindow
is a window(actually, any class derived from System.Windows.Media.Visual
will have this function), if you are using this inside a WPF window class, this
should work.
I'm getting best results to put jQuery dialog in the center of browser's window with:
position: { my: "center bottom", at: "center center", of: window },
There's probably more accurate way to position it with option "using" as described in the documentation at http://api.jqueryui.com/position/ but I'm in a hurry...
Is that your actual code? A javascript object (which is what you've given us) does not have a length property, so in this case exampleArray.length
returns undefined rather than 5.
This stackoverflow explains the length differences between an object and an array, and this stackoverflow shows how to get the 'size' of an object.
How about
^[A-Za-z]\S*
a letter followed by 0 or more non-space characters (will include all special symbols).
height: 100%
works if you give a fixed size to the parent element.
You can use segue like this:
self.performSegueWithIdentifier("push", sender: self)
override func prepareForSegue(segue: UIStoryboardSegue!, sender: AnyObject!) {
if segue.identifier == "push" {
}
}
Try purge
sudo aptitude purge phpmyadmin
Not sure this works with plain old apt-get
though
Use a pattern along these lines:
function getValue(file) {
return lookupValue(file);
}
getValue('myFile.txt').then(function(res) {
// do whatever with res here
});
(although this is a bit redundant, I'm sure your actual code is more complicated)
I know it's waaay late, but it did take me 2 minutes to write this optimized and improved version of AgileJon's answer:
var key, obj, prop, owns = Object.prototype.hasOwnProperty;
for (key in validation_messages ) {
if (owns.call(validation_messages, key)) {
obj = validation_messages[key];
for (prop in obj ) {
// using obj.hasOwnProperty might cause you headache if there is
// obj.hasOwnProperty = function(){return false;}
// but owns will always work
if (owns.call(obj, prop)) {
console.log(prop, "=", obj[prop]);
}
}
}
}
In Rails 4 you could do:
GroupMember.find_or_create_by(member_id: 4, group_id: 7)
And use where
is different:
GroupMember.where(member_id: 4, group_id: 7).first_or_create
This will call create
on GroupMember.where(member_id: 4, group_id: 7)
:
GroupMember.where(member_id: 4, group_id: 7).create
On the contrary, the find_or_create_by(member_id: 4, group_id: 7)
will call create
on GroupMember
:
GroupMember.create(member_id: 4, group_id: 7)
Please see this relevant commit on rails/rails.
@ts-expect-error
TS 3.9 introduces a new magic comment. @ts-expect-error
will:
@ts-ignore
if (false) {
// @ts-expect-error: Let's ignore a single compiler error like this unreachable code
console.log("hello"); // compiles
}
// If @ts-expect-error didn't suppress anything at all, we now get a nice warning
let flag = true;
// ...
if (flag) {
// @ts-expect-error
// ^~~~~~~~~~~~~~~^ error: "Unused '@ts-expect-error' directive.(2578)"
console.log("hello");
}
@ts-ignore
and @ts-expect-error
can be used for all sorts of compiler errors. For type issues (like in OP), I recommend one of the following alternatives due to narrower error suppression scope:
? Use any
type
// type assertion for single expression
delete ($ as any).summernote.options.keyMap.pc.TAB;
// new variable assignment for multiple usages
const $$: any = $
delete $$.summernote.options.keyMap.pc.TAB;
delete $$.summernote.options.keyMap.mac.TAB;
? Augment JQueryStatic
interface
// ./global.d.ts
interface JQueryStatic {
summernote: any;
}
// ./main.ts
delete $.summernote.options.keyMap.pc.TAB; // works
In other cases, shorthand module declarations or module augmentations for modules with no/extendable types are handy utilities. A viable strategy is also to keep not migrated code in .js
and use --allowJs
with checkJs: false
.
public static T Runner<T>(Func<T> funcToRun)
{
//Do stuff before running function as normal
return funcToRun();
}
Usage:
var ReturnValue = Runner(() => GetUser(99));
As I understand it, loadData()
simply generates a data:
URL with the data provide it.
Read the javadocs for loadData()
:
If the value of the encoding parameter is 'base64', then the data must be encoded as base64. Otherwise, the data must use ASCII encoding for octets inside the range of safe URL characters and use the standard %xx hex encoding of URLs for octets outside that range. For example, '#', '%', '\', '?' should be replaced by %23, %25, %27, %3f respectively.
The 'data' scheme URL formed by this method uses the default US-ASCII charset. If you need need to set a different charset, you should form a 'data' scheme URL which explicitly specifies a charset parameter in the mediatype portion of the URL and call loadUrl(String) instead. Note that the charset obtained from the mediatype portion of a data URL always overrides that specified in the HTML or XML document itself.
Therefore, you should either use US-ASCII and escape any special characters yourself, or just encode everything using Base64. The following should work, assuming you use UTF-8 (I haven't tested this with latin1):
String data = ...; // the html data
String base64 = android.util.Base64.encodeToString(data.getBytes("UTF-8"), android.util.Base64.DEFAULT);
webView.loadData(base64, "text/html; charset=utf-8", "base64");
The Angular6 equivalent code should be:
app.component.html
<div (mouseover)="changeText=true" (mouseout)="changeText=false">
<span *ngIf="!changeText">Hide</span>
<span *ngIf="changeText">Show</span>
</div>
app.component.ts
@Component({
selector: 'app-main',
templateUrl: './app.component.html'
})
export class AppComponent {
changeText: boolean;
constructor() {
this.changeText = false;
}
}
Notice that there is no such thing as $scope
anymore as it existed in AngularJS. Its been replaced with member variables from the component class. Also, there is no scope resolution algorithm based on prototypical inheritance either - it either resolves to a component class member, or it doesn't.
NSArray *_returnedArguments = [serverOutput componentsSeparatedByString:@":"];
_returnedArguments
is an array of NSStrings
which the UITextField text
property is expecting. No need to convert.
Syntax error:
[_appDelegate loggedIn:usernameField.text:passwordField.text:(int)[[_returnedArguments objectAtIndex:2] intValue]];
If your _appDelegate has a passwordField
property, then you can set the text using the following
[[_appDelegate passwordField] setText:[_returnedArguments objectAtIndex:2]];
order by coalesce(date-time-field,large date in future)