The code works as best I can tell. I would fire up Sysinternals process explorer and find out what is holding the file open. It might very well be Visual Studio.
With ES6: This is now part of the language:
function myFunc(a, b = 0) {
// function body
}
Please keep in mind that ES6 checks the values against undefined
and not against truthy-ness (so only real undefined values get the default value - falsy values like null will not default).
With ES5:
function myFunc(a,b) {
b = b || 0;
// b will be set either to b or to 0.
}
This works as long as all values you explicitly pass in are truthy.
Values that are not truthy as per MiniGod's comment: null, undefined, 0, false, ''
It's pretty common to see JavaScript libraries to do a bunch of checks on optional inputs before the function actually starts.
{{ word|striptags('<b>,<a>,<pre>')|raw }}
if you want to allow multiple tags
Synthesizing from the other responses: pushd
is bash-specific and you are make is using another POSIX shell. There is a simple workaround to use separate shell for the part that needs different directory, so just try changing it to:
test -z gen || mkdir -p gen \
&& ( cd $(CURRENT_DIRECTORY)/genscript > /dev/null \
&& perl genmakefile.pl \
&& mv Makefile ../gen/ ) \
&& echo "" > $(CURRENT_DIRECTORY)/gen/SvcGenLog
(I substituted the long path with a variable expansion. I probably is one in the makefile and it clearly expands to the current directory).
Since you are running it from make, I would probably replace the test with a make rule, too. Just
gen/SvcGenLog :
mkdir -p gen
cd genscript > /dev/null \
&& perl genmakefile.pl \
&& mv Makefile ../gen/ \
echo "" > gen/SvcGenLog
(dropped the current directory prefix; you were using relative path at some points anyway)
And than just make the rule depend on gen/SvcGenLog
. It would be a bit more readable and you can make it depend on the genscript/genmakefile.pl
too, so the Makefile
in gen
will be regenerated if you modify the script. Of course if anything else affects the content of the Makefile
, you can make the rule depend on that too.
During initialization you have to set to false the option enableOnReadonly which by default is true.
$('#datepicker').datepicker({
enableOnReadonly: false
});
Then, you need to make the field readonly
$('#datepicker').prop('readonly', true);
See https://bootstrap-datepicker.readthedocs.io/en/latest/options.html#enableonreadonly
This depend on how you want to incorporate it. The scenario 1. click on a link 2. explorer window popped up
<a href="\\server\folder\path" target="_blank">click</a>
If there is a need in a fancy UI - then it will barely serve as a solution.
You can utilize the fact that the character encodings for digits are all in order from 48 (for '0') to 57 (for '9'). This holds true for ASCII, UTF-x and practically all other encodings (see comments below for more on this).
Therefore the integer value for any digit is the digit minus '0' (or 48).
char c = '1';
int i = c - '0'; // i is now equal to 1, not '1'
is synonymous to
char c = '1';
int i = c - 48; // i is now equal to 1, not '1'
However I find the first c - '0'
far more readable.
You can just do it like this:
#content {
position: relative;
}
#content img {
position: absolute;
top: 0px;
right: 0px;
}
<div id="content">
<img src="images/ribbon.png" class="ribbon"/>
<div>some text...</div>
</div>
As Ben said, you are POSTing your request ( HttpMethod.Post specified in your code )
The querystring (get) parameters included in your url probably will not do anything.
Try this:
string url = "http://myserver/method";
string content = "param1=1¶m2=2";
HttpClientHandler handler = new HttpClientHandler();
HttpClient httpClient = new HttpClient(handler);
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, url);
HttpResponseMessage response = await httpClient.SendAsync(request,content);
HTH,
bovako
Solution for MAC OS
I'm not sure if this answer suits here, but I would like to share a solution for MAC users and it looks awkward if I start a new question and answer myself there.
look for your VSCode theme path something like below:
..your_install_location/Visual Studio Code.app/Contents/Resources/app/extensions/theme-name/themes/theme_file.json
open .json file and look for your targeted styles to change.
For my case, I want to change the whitespace render colour
and I've found it as"editorWhitespace.foreground"
so under settings.json
in Visual Studio Code,
I added the following lines (I do in Workspace Settings),
"workbench.colorCustomizations": {
"editorWhitespace.foreground": "#93A1A130" // stand as #RRGGBBAA
}
Solutions guided from : https://code.visualstudio.com/docs/getstarted/themes#_customize-a-color-theme
Don't forget to ⌘ Command+S save settings to take effect.
If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.
Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:
git rebase -i HEAD~2
This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example
pick 222 commit to be stashed
pick 111 commit to be pushed to remote
# Rebase 111..222 onto 333
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out
Reorder the two commits (they are listed oldest => newest) like this:
pick 111 commit to be pushed to remote
pick 222 commit to be stashed
Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5
which will output newest-first.
At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:
git reset --soft HEAD~1
git stash
It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.
There is a rather clever solution:
#define MACRO(X,Y) \
do { \
cout << "1st arg is:" << (X) << endl; \
cout << "2nd arg is:" << (Y) << endl; \
cout << "Sum is:" << ((X)+(Y)) << endl; \
} while (0)
Now you have a single block-level statement, which must be followed by a semicolon. This behaves as expected and desired in all three examples.
Make the outer loop a while loop, and "Exit While" in the if statement.
This command will create two files in /path/to/directory table_name.sql and table_name.txt.
The SQL file will contain the table creation schema and the txt file will contain the records of the mytable table with fields delimited by a comma.
mysqldump -u username -p -t -T/path/to/directory dbname table_name --fields-terminated-by=','
TL;DR
The @Autowired
annotation spares you the need to do the wiring by yourself in the XML file (or any other way) and just finds for you what needs to be injected where and does that for you.
Full explanation
The @Autowired
annotation allows you to skip configurations elsewhere of what to inject and just does it for you. Assuming your package is com.mycompany.movies
you have to put this tag in your XML (application context file):
<context:component-scan base-package="com.mycompany.movies" />
This tag will do an auto-scanning. Assuming each class that has to become a bean is annotated with a correct annotation like @Component
(for simple bean) or @Controller
(for a servlet control) or @Repository
(for DAO
classes) and these classes are somewhere under the package com.mycompany.movies
, Spring will find all of these and create a bean for each one. This is done in 2 scans of the classes - the first time it just searches for classes that need to become a bean and maps the injections it needs to be doing, and on the second scan it injects the beans. Of course, you can define your beans in the more traditional XML file or with an @Configuration
class (or any combination of the three).
The @Autowired
annotation tells Spring where an injection needs to occur. If you put it on a method setMovieFinder
it understands (by the prefix set
+ the @Autowired
annotation) that a bean needs to be injected. In the second scan, Spring searches for a bean of type MovieFinder
, and if it finds such bean, it injects it to this method. If it finds two such beans you will get an Exception
. To avoid the Exception
, you can use the @Qualifier
annotation and tell it which of the two beans to inject in the following manner:
@Qualifier("redBean")
class Red implements Color {
// Class code here
}
@Qualifier("blueBean")
class Blue implements Color {
// Class code here
}
Or if you prefer to declare the beans in your XML, it would look something like this:
<bean id="redBean" class="com.mycompany.movies.Red"/>
<bean id="blueBean" class="com.mycompany.movies.Blue"/>
In the @Autowired
declaration, you need to also add the @Qualifier
to tell which of the two color beans to inject:
@Autowired
@Qualifier("redBean")
public void setColor(Color color) {
this.color = color;
}
If you don't want to use two annotations (the @Autowired
and @Qualifier
) you can use @Resource
to combine these two:
@Resource(name="redBean")
public void setColor(Color color) {
this.color = color;
}
The @Resource
(you can read some extra data about it in the first comment on this answer) spares you the use of two annotations and instead, you only use one.
I'll just add two more comments:
@Inject
instead of @Autowired
because it is not Spring-specific and is part of the JSR-330
standard.@Inject
/ @Autowired
on a constructor instead of a method. If you put it on a constructor, you can validate that the injected beans are not null and fail fast when you try to start the application and avoid a NullPointerException
when you need to actually use the bean.Update: To complete the picture, I created a new question about the @Configuration
class.
No, just include the different fields in the "ON" clause of 1 inner join statement:
SELECT * from Evalulation e JOIN Value v ON e.CaseNum = v.CaseNum
AND e.FileNum = v.FileNum AND e.ActivityNum = v.ActivityNum
mysqladmin
is not a SQL statement. It's a little helper utility program you'll find on your MySQL server... and "flush-hosts" is one of the things it can do. ("status" and "shutdown" are a couple of other things that come to mind).
You type that command from a shell prompt.
Alternately, from your query browser (such as phpMyAdmin), the SQL statement you're looking for is simply this:
FLUSH HOSTS;
I know I'm late to answer this, but I read most of the answers and while many were great, only djn actually explained why you were getting this 500 Internal Server Error
.
While his explanation was 100% correct, this is a perfect example of why you should always wrap those in an <IfModule>
. While this won't fix the actual problem of not being able to set those flags in your .htaccess
, it will at least prevent the 500
error.
<IfModule mod_php5.c>
# put all of your php_flags here, for example:
php_flag magic_quotes_gpc off
</IfModule>
Or for older versions it would be <IfModule mod_php.c>
etc.
I try to make a habit out of always doing this so as to avoid any such 500 errors. After that, just apply what Peter Bailey said.
I like Consolas
a lot. This top-10 list is a good resource for others. It includes examples and descriptions.
Just for super noobs like me wondering how or what people meant by
PRAGMA table_info('table_name')
You want to use use that as your prepare statement as shown below. Doing so selects a table that looks like this except is populated with values pertaining to your table.
cid name type notnull dflt_value pk
---------- ---------- ---------- ---------- ---------- ----------
0 id integer 99 1
1 name 0 0
Where id and name are the actual names of your columns. So to get that value you need to select column name by using:
//returns the name
sqlite3_column_text(stmt, 1);
//returns the type
sqlite3_column_text(stmt, 2);
Which will return the current row's column's name. To grab them all or find the one you want you need to iterate through all the rows. Simplest way to do so would be in the manner below.
//where rc is an int variable if wondering :/
rc = sqlite3_prepare_v2(dbPointer, "pragma table_info ('your table name goes here')", -1, &stmt, NULL);
if (rc==SQLITE_OK)
{
//will continue to go down the rows (columns in your table) till there are no more
while(sqlite3_step(stmt) == SQLITE_ROW)
{
sprintf(colName, "%s", sqlite3_column_text(stmt, 1));
//do something with colName because it contains the column's name
}
}
The best way is to change any setting you want in your code.
Check out the below example:
using(WCFServiceClient client = new WCFServiceClient ())
{
client.Endpoint.Binding.SendTimeout = new TimeSpan(0, 1, 30);
}
you can use url module to collect parameters by using url.parse
var url = require('url');
var url_data = url.parse(request.url, true);
var query = url_data.query;
In expressjs it's done by,
var id = req.query.id;
Eg:
var express = require('express');
var app = express();
app.get('/login', function (req, res, next) {
console.log(req.query);
console.log(req.query.id); //Give parameter id
});
It helps to make a clear distinction between the function foo, and the generator foo(n):
def foo(n):
yield n
yield n+1
foo is a function. foo(6) is a generator object.
The typical way to use a generator object is in a loop:
for n in foo(6):
print(n)
The loop prints
# 6
# 7
Think of a generator as a resumable function.
yield
behaves like return
in the sense that values that are yielded get "returned" by the generator. Unlike return, however, the next time the generator gets asked for a value, the generator's function, foo, resumes where it left off -- after the last yield statement -- and continues to run until it hits another yield statement.
Behind the scenes, when you call bar=foo(6)
the generator object bar is defined for you to have a next
attribute.
You can call it yourself to retrieve values yielded from foo:
next(bar) # Works in Python 2.6 or Python 3.x
bar.next() # Works in Python 2.5+, but is deprecated. Use next() if possible.
When foo ends (and there are no more yielded values), calling next(bar)
throws a StopInteration error.
SELECT owner, table_name
FROM dba_tables
This is assuming that you have access to the DBA_TABLES
data dictionary view. If you do not have those privileges but need them, you can request that the DBA explicitly grants you privileges on that table, or, that the DBA grants you the SELECT ANY DICTIONARY
privilege or the SELECT_CATALOG_ROLE
role (either of which would allow you to query any data dictionary table). Of course, you may want to exclude certain schemas like SYS
and SYSTEM
which have large numbers of Oracle tables that you probably don't care about.
Alternatively, if you do not have access to DBA_TABLES
, you can see all the tables that your account has access to through the ALL_TABLES
view:
SELECT owner, table_name
FROM all_tables
Although, that may be a subset of the tables available in the database (ALL_TABLES
shows you the information for all the tables that your user has been granted access to).
If you are only concerned with the tables that you own, not those that you have access to, you could use USER_TABLES
:
SELECT table_name
FROM user_tables
Since USER_TABLES
only has information about the tables that you own, it does not have an OWNER
column – the owner, by definition, is you.
Oracle also has a number of legacy data dictionary views-- TAB
, DICT
, TABS
, and CAT
for example-- that could be used. In general, I would not suggest using these legacy views unless you absolutely need to backport your scripts to Oracle 6. Oracle has not changed these views in a long time so they often have problems with newer types of objects. For example, the TAB
and CAT
views both show information about tables that are in the user's recycle bin while the [DBA|ALL|USER]_TABLES
views all filter those out. CAT
also shows information about materialized view logs with a TABLE_TYPE
of "TABLE" which is unlikely to be what you really want. DICT
combines tables and synonyms and doesn't tell you who owns the object.
flash message after redirect will available in controller not in view. to show in view get in controller's action and pass it view
Or you can have your alias in a HAVING
clause
I am assuming this is a custom font. For any custom font this is what you do.
First download and add your font files to your project in Xcode (The files should appear as well in “Target -> Build Phases -> Copy Bundle Resources”).
In your Info.plist file add the key “Fonts provided by application” with type “Array”.
For each font you want to add to your project, create an item for the array you have created with the full name of the file including its extension (e.g. HelveticaNeue-UltraLight.ttf). Save your “Info.plist” file.
label.font = UIFont (name: "HelveticaNeue-UltraLight", size: 30)
Pythonic
X = X[:, :, None]
which is equivalent to
X = X[:, :, numpy.newaxis]
and
X = numpy.expand_dims(X, axis=-1)
But as you are explicitly asking about stacking images,
I would recommend going for stacking the list
of images np.stack([X1, X2, X3])
that you may have collected in a loop.
If you do not like the order of the dimensions you can rearrange with np.transpose()
Try using System.getProperty("line.separator")
to get a new line.
There is no built-in way. You can have MyClass implement the IClonable
interface (but it is sort of deprecated) or just write your own Copy/Clone method. In either case you will have to write some code.
For big objects you could consider Serialization + Deserialization (through a MemoryStream), just to reuse existing code.
Whatever the method, think carefully about what "a copy" means exactly. How deep should it go, are there Id fields to be excepted etc.
The default
condition can be anyplace within the switch that a case clause can exist. It is not required to be the last clause. I have seen code that put the default as the first clause. The case 2:
gets executed normally, even though the default clause is above it.
As a test, I put the sample code in a function, called test(int value){}
and ran:
printf("0=%d\n", test(0));
printf("1=%d\n", test(1));
printf("2=%d\n", test(2));
printf("3=%d\n", test(3));
printf("4=%d\n", test(4));
The output is:
0=2
1=1
2=4
3=8
4=10
If you http request is Post and request.Accept = "application/x-www-form-urlencoded";
then i think you can to get text of respone by code bellow:
var contentEncoding = response.Headers["content-encoding"];
if (contentEncoding != null && contentEncoding.Contains("gzip")) // cause httphandler only request gzip
{
// using gzip stream reader
using (var responseStreamReader = new StreamReader(new GZipStream(response.GetResponseStream(), CompressionMode.Decompress)))
{
strResponse = responseStreamReader.ReadToEnd();
}
}
else
{
// using ordinary stream reader
using (var responseStreamReader = new StreamReader(response.GetResponseStream()))
{
strResponse = responseStreamReader.ReadToEnd();
}
}
First you should learn about loops, in this case most suitable is for
loop. For instance let's initialize whole table with increasing values starting with 0:
final int SIZE = 10;
int[] array = new int[SIZE];
for (int i = 0; i < SIZE; i++) {
array[i] = i;
}
Now you can modify it to initialize your table with values as per your assignment.
But what happen if you replace condition i < SIZE
with i < 11
? Well, you will get IndexOutOfBoundException
, as you try to access (at some point) an object under index 10, but the highest index in 10-element array is 9. So you are trying, in other words, to find friend's home with number 11, but there are only 10 houses in the street.
In case of the code you presented, well, there must be more of it, as you can not get this error (exception) from that code.
I've found a great example using javax.websocket
here:
http://www.programmingforliving.com/2013/08/jsr-356-java-api-for-websocket-client-api.html
Here the code based on the example linked above:
TestApp.java
:
package testapp;
import java.net.URI;
import java.net.URISyntaxException;
public class TestApp {
public static void main(String[] args) {
try {
// open websocket
final WebsocketClientEndpoint clientEndPoint = new WebsocketClientEndpoint(new URI("wss://real.okcoin.cn:10440/websocket/okcoinapi"));
// add listener
clientEndPoint.addMessageHandler(new WebsocketClientEndpoint.MessageHandler() {
public void handleMessage(String message) {
System.out.println(message);
}
});
// send message to websocket
clientEndPoint.sendMessage("{'event':'addChannel','channel':'ok_btccny_ticker'}");
// wait 5 seconds for messages from websocket
Thread.sleep(5000);
} catch (InterruptedException ex) {
System.err.println("InterruptedException exception: " + ex.getMessage());
} catch (URISyntaxException ex) {
System.err.println("URISyntaxException exception: " + ex.getMessage());
}
}
}
WebsocketClientEndpoint.java
:
package testapp;
import java.net.URI;
import javax.websocket.ClientEndpoint;
import javax.websocket.CloseReason;
import javax.websocket.ContainerProvider;
import javax.websocket.OnClose;
import javax.websocket.OnMessage;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.WebSocketContainer;
/**
* ChatServer Client
*
* @author Jiji_Sasidharan
*/
@ClientEndpoint
public class WebsocketClientEndpoint {
Session userSession = null;
private MessageHandler messageHandler;
public WebsocketClientEndpoint(URI endpointURI) {
try {
WebSocketContainer container = ContainerProvider.getWebSocketContainer();
container.connectToServer(this, endpointURI);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
/**
* Callback hook for Connection open events.
*
* @param userSession the userSession which is opened.
*/
@OnOpen
public void onOpen(Session userSession) {
System.out.println("opening websocket");
this.userSession = userSession;
}
/**
* Callback hook for Connection close events.
*
* @param userSession the userSession which is getting closed.
* @param reason the reason for connection close
*/
@OnClose
public void onClose(Session userSession, CloseReason reason) {
System.out.println("closing websocket");
this.userSession = null;
}
/**
* Callback hook for Message Events. This method will be invoked when a client send a message.
*
* @param message The text message
*/
@OnMessage
public void onMessage(String message) {
if (this.messageHandler != null) {
this.messageHandler.handleMessage(message);
}
}
/**
* register message handler
*
* @param msgHandler
*/
public void addMessageHandler(MessageHandler msgHandler) {
this.messageHandler = msgHandler;
}
/**
* Send a message.
*
* @param message
*/
public void sendMessage(String message) {
this.userSession.getAsyncRemote().sendText(message);
}
/**
* Message handler.
*
* @author Jiji_Sasidharan
*/
public static interface MessageHandler {
public void handleMessage(String message);
}
}
Here is some relevant code:
// Create a trust manager that does not validate certificate chains
TrustManager[] trustAllCerts = new TrustManager[]{
new X509TrustManager() {
public java.security.cert.X509Certificate[] getAcceptedIssuers() {
return null;
}
public void checkClientTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
public void checkServerTrusted(
java.security.cert.X509Certificate[] certs, String authType) {
}
}
};
// Install the all-trusting trust manager
try {
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new java.security.SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
} catch (Exception e) {
}
// Now you can access an https URL without having the certificate in the truststore
try {
URL url = new URL("https://hostname/index.html");
} catch (MalformedURLException e) {
}
This will completely disable SSL checking—just don't learn exception handling from such code!
To do what you want, you would have to implement a check in your TrustManager that prompts the user.
You can either Drop the columns you do not need OR Select the ones you need
# Using DataFrame.drop
df.drop(df.columns[[1, 2]], axis=1, inplace=True)
# drop by Name
df1 = df1.drop(['B', 'C'], axis=1)
# Select the ones you want
df1 = df[['a','d']]
On a mac you can also use command Z and that will go undo. I'm not sure why, but sometimes it stops, and if your like me and vimtutor is on the bottom of that long list of things you need to learn, than u can just close the window and reopen it and should work fine.
You have at least two issues in your code:
ng-change="getScoreData(Score)
Angular doesn't see getScoreData
method that refers to defined service
getScoreData: function (Score, callback)
We don't need to use callback since GET
returns promise. Use then
instead.
Here is a working example (I used random address only for simulation):
HTML
<select ng-model="score"
ng-change="getScoreData(score)"
ng-options="score as score.name for score in scores"></select>
<pre>{{ScoreData|json}}</pre>
JS
var fessmodule = angular.module('myModule', ['ngResource']);
fessmodule.controller('fessCntrl', function($scope, ScoreDataService) {
$scope.scores = [{
name: 'Bukit Batok Street 1',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, 153 Bukit Batok Street 1&sensor=true'
}, {
name: 'London 8',
URL: 'http://maps.googleapis.com/maps/api/geocode/json?address=Singapore, SG, Singapore, London 8&sensor=true'
}];
$scope.getScoreData = function(score) {
ScoreDataService.getScoreData(score).then(function(result) {
$scope.ScoreData = result;
}, function(result) {
alert("Error: No data returned");
});
};
});
fessmodule.$inject = ['$scope', 'ScoreDataService'];
fessmodule.factory('ScoreDataService', ['$http', '$q', function($http) {
var factory = {
getScoreData: function(score) {
console.log(score);
var data = $http({
method: 'GET',
url: score.URL
});
return data;
}
}
return factory;
}]);
Demo Fiddle
Inspired by Robert K's solution, strips html tags and prevents executing scripts and eventhandlers like: <img src=fake onerror="prompt(1)">
Tested on latest Chrome, FF, IE (should work from IE9, but haven't tested).
var decodeEntities = (function () {
//create a new html document (doesn't execute script tags in child elements)
var doc = document.implementation.createHTMLDocument("");
var element = doc.createElement('div');
function getText(str) {
element.innerHTML = str;
str = element.textContent;
element.textContent = '';
return str;
}
function decodeHTMLEntities(str) {
if (str && typeof str === 'string') {
var x = getText(str);
while (str !== x) {
str = x;
x = getText(x);
}
return x;
}
}
return decodeHTMLEntities;
})();
Simply call:
decodeEntities('<img src=fake onerror="prompt(1)">');
decodeEntities("<script>alert('aaa!')</script>");
There is a free library called barcode4j
For me this worked:
var in_canvas = document.getElementById('chart_holder');_x000D_
//remove canvas if present_x000D_
while (in_canvas.hasChildNodes()) {_x000D_
in_canvas.removeChild(in_canvas.lastChild);_x000D_
} _x000D_
//insert canvas_x000D_
var newDiv = document.createElement('canvas');_x000D_
in_canvas.appendChild(newDiv);_x000D_
newDiv.id = "myChart";
_x000D_
Or just use Apache CXF's wsdl2java to generate objects you can use.
It is included in the binary package you can download from their website. You can simply run a command like this:
$ ./wsdl2java -p com.mynamespace.for.the.api.objects -autoNameResolution http://www.someurl.com/DefaultWebService?wsdl
It uses the wsdl to generate objects, which you can use like this (object names are also grabbed from the wsdl, so yours will be different a little):
DefaultWebService defaultWebService = new DefaultWebService();
String res = defaultWebService.getDefaultWebServiceHttpSoap11Endpoint().login("webservice","dadsadasdasd");
System.out.println(res);
There is even a Maven plug-in which generates the sources: https://cxf.apache.org/docs/maven-cxf-codegen-plugin-wsdl-to-java.html
Note: If you generate sources using CXF and IDEA, you might want to look at this: https://stackoverflow.com/a/46812593/840315
When there are multiple activities entries in AndroidManifest.xml, how does android know which activity to start first?
There is no "first". In your case, with your manifest as shown, you will have two icons in your launcher. Whichever one the user taps on is the one that gets launched.
I could not understand intent-filters. Can anyone please explain.
There is quite a bit of documentation on the subject. Please consider reading that, then asking more specific questions.
Also, when you get "application has stopped unexpectedly, try again", use adb logcat
, DDMS, or the DDMS perspective in Eclipse to examine the Java stack trace associated with the error.
For anyone trying to this in react. There is a slight difference.
// Document of 8.5 inch width and 11 inch high
new jsPDF('p', 'in', [612, 792]);
or
// Document of 8.5 inch width and 11 inch high
new jsPDF({
orientation: 'p',
unit: 'in',
format: [612, 792]
});
When i tried the @Aidiakapi solution the pages were tiny. For a difference size take size in inches * 72 to get the dimensions you need. For example, i wanted 8.5 so 8.5 * 72 = 612. This is for [email protected].
When using WebAPI, you should just return the Object rather than specifically returning Json, as the API will either return JSON or XML depending on the request.
I am not sure why your WebAPI is returning an ActionResult, but I would change the code to something like;
public IEnumerable<ListItems> GetAllNotificationSettings()
{
var result = new List<ListItems>();
// Filling the list with data here...
// Then I return the list
return result;
}
This will result in JSON if you are calling it from some AJAX code.
P.S
WebAPI is supposed to be RESTful, so your Controller should be called ListItemController
and your Method should just be called Get
. But that is for another day.
The IF statement has these forms in PL/SQL
:
IF THEN
IF THEN ELSE
IF THEN ELSIF
You have used elseif
which in terms of PL/SQL is wrong. That need to be replaced with ELSIF
.
DECLARE
mark NUMBER :=50;
BEGIN
mark :=& mark;
IF (mark BETWEEN 85 AND 100) THEN
dbms_output.put_line('mark is A ');
elsif (mark BETWEEN 50 AND 65) THEN
dbms_output.put_line('mark is D ');
elsif (mark BETWEEN 66 AND 75) THEN
dbms_output.put_line('mark is C ');
elsif (mark BETWEEN 76 AND 84) THEN
dbms_output.put_line('mark is B');
ELSE
dbms_output.put_line('mark is F');
END IF;
END;
/
mv
in unix-ish systems, move
in dos/windows.
e.g.
C:\> move c:\users\you\somefile.txt c:\temp\newlocation.txt
and
$ mv /home/you/somefile.txt /tmp/newlocation.txt
.text is correct, the following code works for me:
$('#lb'+(n+1)).text(a[i].attributes[n].name+": "+ a[i].attributes[n].value);
You can use this method to send whatever confirmation message you want like "OK" or the password. This is my solution with an example:
def SpecialConfirmation(command, message, reply):
net_connect.config_mode() # To enter config mode
net_connect.remote_conn.sendall(str(command)+'\n' )
time.sleep(3)
output = net_connect.remote_conn.recv(65535).decode('utf-8')
ReplyAppend=''
if str(message) in output:
for i in range(0,(len(reply))):
ReplyAppend+=str(reply[i])+'\n'
net_connect.remote_conn.sendall(ReplyAppend)
output = net_connect.remote_conn.recv(65535).decode('utf-8')
print (output)
return output
CryptoPkiEnroll=['','','no','no','yes']
output=SpecialConfirmation ('crypto pki enroll TCA','Password' , CryptoPkiEnroll )
print (output)
In onCreate with activity or in onCreateView with fragment.
if (view != null) {
ViewGroup parent = (ViewGroup) view.getParent();
if (parent != null) {
parent.removeView(view);
}
}
try {
view = inflater.inflate(R.layout.fragment_main, container, false);
} catch (InflateException e) {
}
It is being pointed out not directly in the file which is caused the error. But it is actually triggered in a controller file. It happens when a return value from a method defined inside in a controller file is set on a boolean value. It must not be set on a boolean type but on the other hand, it must be set or given a value of a string type. It can be shown as follows :
public function saveFormSummary(Request $request) {
...
$status = true;
return $status;
}
Given the return value of a boolean type above in a method, to be able to solve the problem to handle the error specified. Just change the type of the return value into a string type
as follows :
public function saveFormSummary(Request $request) {
...
$status = "true";
return $status;
}
Use itertools.chain:
itertools.chain(*iterables)
:Make an iterator that returns elements from the first iterable until it is exhausted, then proceeds to the next iterable, until all of the iterables are exhausted. Used for treating consecutive sequences as a single sequence.
from itertools import chain
A = [[1,2], [3,4]]
print list(chain(*A))
# or better: (available since Python 2.6)
print list(chain.from_iterable(A))
The output is:
[1, 2, 3, 4]
[1, 2, 3, 4]
May be a little late but the following solution happened very useful in my case.
In a way all you need to do is add to your ListView a Footer
and create for it addOnLayoutChangeListener
.
http://developer.android.com/reference/android/widget/ListView.html#addFooterView(android.view.View)
For example:
ListView listView1 = (ListView) v.findViewById(R.id.dialogsList); // Your listView
View loadMoreView = getActivity().getLayoutInflater().inflate(R.layout.list_load_more, null); // Getting your layout of FooterView, which will always be at the bottom of your listview. E.g. you may place on it the ProgressBar or leave it empty-layout.
listView1.addFooterView(loadMoreView); // Adding your View to your listview
...
loadMoreView.addOnLayoutChangeListener(new View.OnLayoutChangeListener() {
@Override
public void onLayoutChange(View v, int left, int top, int right, int bottom, int oldLeft, int oldTop, int oldRight, int oldBottom) {
Log.d("Hey!", "Your list has reached bottom");
}
});
This event fires once when a footer becomes visible and works like a charm.
Instead of using ->bindParam()
you can pass the data only at the time of ->execute()
:
$data = [ ':item_name' => $_POST['item_name'], ':item_type' => $_POST['item_type'], ':item_price' => $_POST['item_price'], ':item_description' => $_POST['item_description'], ':image_location' => 'images/'.$_FILES['file']['name'], ':status' => 0, ':id' => 0, ]; $stmt->execute($data);
In this way you would know exactly what values are going to be sent.
Here is a quick edit of Enve's answer. I do like roXor's solution, but background images are not necessary. And everbody seems to forgot a preventDefault
as well.
$(document).ready(function() {_x000D_
$(".slidingDiv").hide();_x000D_
_x000D_
$('.show_hide').click(function(e) {_x000D_
$(".slidingDiv").slideToggle("fast");_x000D_
var val = $(this).text() == "-" ? "+" : "-";_x000D_
$(this).hide().text(val).fadeIn("fast");_x000D_
e.preventDefault();_x000D_
});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<a href="#" class="show_hide">+</a>_x000D_
_x000D_
<div class="slidingDiv">_x000D_
<p>Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero. Sed cursus ante dapibus diam. Sed nisi. Nulla quis sem at nibh elementum imperdiet. Duis sagittis ipsum. Praesent mauris. Fusce nec tellus sed augue semper porta._x000D_
Mauris massa. Vestibulum lacinia arcu eget nulla. </p>_x000D_
_x000D_
<p>Class aptent taciti sociosqu ad litora torquent per conubia nostra, per inceptos himenaeos. Curabitur sodales ligula in libero. Sed dignissim lacinia nunc. Curabitur tortor. Pellentesque nibh. Aenean quam. In scelerisque sem at dolor. Maecenas mattis._x000D_
Sed convallis tristique sem. Proin ut ligula vel nunc egestas porttitor. Morbi lectus risus, iaculis vel, suscipit quis, luctus non, massa. Fusce ac turpis quis ligula lacinia aliquet. Mauris ipsum. </p>_x000D_
_x000D_
</div>
_x000D_
Syntax:
CASE value WHEN [compare_value] THEN result
[WHEN [compare_value] THEN result ...]
[ELSE result]
END
Alternative: CASE WHEN [condition] THEN result [WHEN [condition] THEN result ...]
mysql> SELECT CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END;
+-------------------------------------------------------------+
| CASE WHEN 2>3 THEN 'this is true' ELSE 'this is false' END |
+-------------------------------------------------------------+
| this is false |
+-------------------------------------------------------------+
I am use:
SELECT act.*,
CASE
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NULL) THEN lises.location_id
WHEN (lises.session_date IS NULL AND ses.session_date IS NOT NULL) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date>ses.session_date) THEN ses.location_id
WHEN (lises.session_date IS NOT NULL AND ses.session_date IS NOT NULL AND lises.session_date<ses.session_date) THEN lises.location_id
END AS location_id
FROM activity AS act
LEFT JOIN li_sessions AS lises ON lises.activity_id = act.id AND lises.session_date >= now()
LEFT JOIN session AS ses ON ses.activity_id = act.id AND ses.session_date >= now()
WHERE act.id
You can get value of id,name or value in this way. class name my_class
var id_value = $('.my_class').$(this).attr('id'); //get id value
var name_value = $('.my_class').$(this).attr('name'); //get name value
var value = $('.my_class').$(this).attr('value'); //get value any input or tag
You need to have your function in the componentDidMount
lifecycle since this is the function that is called when the DOM has loaded.
Make use of refs
to access the DOM element
<input type="submit" className="nameInput" id="name" value="cp-dev1" onClick={this.writeData} ref = "cpDev1"/>
componentDidMount: function(){
var name = React.findDOMNode(this.refs.cpDev1).value;
this.someOtherFunction(name);
}
See this answer for more info on How to access the dom element in React
The closest to Eclipse will be Ctrl+Button2 Click (Scroll click)
It's called Quick Doc in IntelliJ, I wish guys from JetBrains one day add quick doc like Eclipse with Ctrl+Mouse Move it's so much better.
In my case only with only mouse move is a bit annoying, so if you search in Preferences/Settings --> Keymap for "quick documentation" you will find:
It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.
I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.
For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.
// This is a fix for that bug that causes Servers to pop offline/online.
// Servers will intermittently pop offline/online for 10 seconds or so.
// The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
// After several minutes, the route to the DHCP gateway may timeout, at which
// point the pingponging stops.
// You need 3 machines, Client machine, server A, and server B
// Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
// Now turn off the ping from machine B (en1), but leave the network connected.
// You will notice that the machine transmitting on the interface with
// the DHCP gateway will fail sendto() with errno 'No route to host'
if ( theErr == 0 )
{
// inspired by 'ping -b' option in man page:
// -b boundif
// Bind the socket to interface boundif for sending.
struct sockaddr_in bindInterfaceAddr;
bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
bindInterfaceAddr.sin_family = AF_INET;
bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
struct sockaddr_in serverAddress;
int namelen = sizeof(serverAddress);
if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
DLogErr(@"ERROR Publishing service... getsockname err");
}
else
{
DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
}
Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.
For the comment on the answer by vogash, I understand that you want something like a time counter, thats because you can have more than 24 hours. For this you can do the following:
select to_char(trunc(xxx/3600)) || to_char(to_date(mod(xxx, 86400),'sssss'),':mi:ss') as time
from dual;
xxx
are your number of seconds.
The first part accumulate the hours and the second part calculates the remaining minutes and seconds. For example, having 150023 seconds
it will give you 41:40:23
.
But if you always want have hh24:mi:ss even if you have more than 86000 seconds
(1 day) you can do:
select to_char(to_date(mod(xxx, 86400),'sssss'),'hh24:mi:ss') as time
from dual;
xxx
are your number of seconds.
For example, having 86402 seconds
it will reset the time to 00:00:02
.
setting the font size might not be practical though, since setting
ctx.font = ''
will use the one defined by CSS as well as any embedded font tags. If you use the CSS font you have no idea what the height is from a programmatic way, using the measureText method, which is very short sighted. On another note though, IE8 DOES return the width and height.
Well you could either initialize the xib using a view controller and use viewController.view. or do it the way you did it. Only making a UIView
subclass as the controller for UIView
is a bad idea.
If you don't have any outlets from your custom view then you can directly use a UIViewController
class to initialize it.
Update: In your case:
UIViewController *genericViewCon = [[UIViewController alloc] initWithNibName:@"CustomView"];
//Assuming you have a reference for the activity indicator in your custom view class
CustomView *myView = (CustomView *)genericViewCon.view;
[parentView addSubview:myView];
//And when necessary
[myView.activityIndicator startAnimating]; //or stop
Otherwise you have to make a custom UIViewController
(to make it as the file's owner so that the outlets are properly wired up).
YourCustomController *yCustCon = [[YourCustomController alloc] initWithNibName:@"YourXibName"].
Wherever you want to add the view you can use.
[parentView addSubview:yCustCon.view];
However passing the another view controller(already being used for another view) as the owner while loading the xib is not a good idea as the view property of the controller will be changed and when you want to access the original view, you won't have a reference to it.
EDIT: You will face this problem if you have setup your new xib with file's owner as the same main UIViewController
class and tied the view property to the new xib view.
i.e;
The below code will cause confusion later on, if you write it inside view did load of YourMainViewController
. That is because self.view
from this point on will refer to your customview
-(void)viewDidLoad:(){
UIView *childView= [[[NSBundle mainBundle] loadNibNamed:@"YourXibName" owner:self options:nil] objectAtIndex:0];
}
In your form tag, rather than
name="booking.php"
use
action="booking.php"
And then, in booking.php use
$checkValue = $_POST['booking-check'];
Also, you'll need a submit button in there
<input type='submit'>
Check your files properties. If the read-only is checked, uncheck it. This was my personal issue with the UnauthorizedAccessException.
We copy/paste html pages from our ERP to Excel using "paste special.. as html/unicode" and it works quite well with tables.
Use the %r
for debugging, since it displays the "raw" data of the variable,
but the others are used for displaying to users.
That's how %r
formatting works; it prints it the way you wrote it (or close to it). It's the "raw" format for debugging. Here \n
used to display to users doesn't work. %r
shows the representation if the raw data of the variable.
months = "\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug"
print "Here are the months: %r" % months
Output:
Here are the months: '\nJan\nFeb\nMar\nApr\nMay\nJun\nJul\nAug'
Check this example from Learn Python the Hard Way.
Try this for Set:
Set<String> listOfTopicAuthors = .....
List<String> setList = new ArrayList<String>(listOfTopicAuthors);
Try this for Map:
Map<String, String> listOfTopicAuthors = .....
// List of values:
List<String> mapValueList = new ArrayList<String>(listOfTopicAuthors.values());
// List of keys:
List<String> mapKeyList = new ArrayList<String>(listOfTopicAuthors.KeySet());
Your problem is with this line:
number4 = list(cow[n])
It tries to take cow[n]
, which returns an integer, and make it a list. This doesn't work, as demonstrated below:
>>> a = 1
>>> list(a)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>
Perhaps you meant to put cow[n]
inside a list:
number4 = [cow[n]]
See a demonstration below:
>>> a = 1
>>> [a]
[1]
>>>
Also, I wanted to address two things:
:
at the end.input
like that, since it evaluates its input as real Python code. It would be better here to use raw_input
and then convert the input to an integer with int
.To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum
:
>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>
I would go about it somewhat like this:
<html>
<head>
<title>Print Test Page</title>
<script>
printDivCSS = new String ('<link href="myprintstyle.css" rel="stylesheet" type="text/css">')
function printDiv(divId) {
window.frames["print_frame"].document.body.innerHTML=printDivCSS + document.getElementById(divId).innerHTML;
window.frames["print_frame"].window.focus();
window.frames["print_frame"].window.print();
}
</script>
</head>
<body>
<h1><b><center>This is a test page for printing</center></b><hr color=#00cc00 width=95%></h1>
<b>Div 1:</b> <a href="javascript:printDiv('div1')">Print</a><br>
<div id="div1">This is the div1's print output</div>
<br><br>
<b>Div 2:</b> <a href="javascript:printDiv('div2')">Print</a><br>
<div id="div2">This is the div2's print output</div>
<br><br>
<b>Div 3:</b> <a href="javascript:printDiv('div3')">Print</a><br>
<div id="div3">This is the div3's print output</div>
<iframe name="print_frame" width="0" height="0" frameborder="0" src="about:blank"></iframe>
</body>
</html>
You have to sort it if you want the data to come back a certain way. When you say you are expecting "Mohit
" to be the first row, I am assuming you say that because "Mohit
" is the first row in the [One]
table. However, when SQL Server joins tables, it doesn't necessarily join in the order you think.
If you want the first row from [One]
to be returned, then try sorting by [One].[ID]
. Alternatively, you can order by
any other column.
MYSQL PROCEDURE steps:
DELIMITER //
create PROCEDURE, you can refer syntax
NOTE: Don't forget to end statement with ' ; '
create procedure ProG() begin SELECT * FROM hs_hr_employee_leave_quota; end;//
delimiter ;
call ProG();
Broadcast receivers receive events of a certain type. I don't think you can invoke them by class name.
First, your IntentFilter must contain an event.
static final String SOME_ACTION = "com.yourcompany.yourapp.SOME_ACTION";
IntentFilter intentFilter = new IntentFilter(SOME_ACTION);
Second, when you send a broadcast, use this same action:
Intent i = new Intent(SOME_ACTION);
sendBroadcast(i);
Third, do you really need MyIntentService to be inline? Static? [EDIT] I discovered that MyIntentSerivce MUST be static if it is inline.
Fourth, is your service declared in the AndroidManifest.xml?
I found that you don't necessarily need the text vertically centred, it also looks good near the bottom of the row, it's only when it's at the top (or above centre?) that it looks wrong. So I went with this to push the links to the bottom of the row:
.navbar-brand {
min-height: 80px;
}
@media (min-width: 768px) {
#navbar-collapse {
position: absolute;
bottom: 0px;
left: 250px;
}
}
My brand image is SVG and I used height: 50px; width: auto
which makes it about 216px wide. It spilled out of its container vertically so I added the min-height: 80px;
to make room for it plus bootstrap's 15px margins. Then I tweaked the navbar-collapse
's left
setting until it looked right.
A simple solution for empty floated divs is to add:
this way you can keep the float functionality and force it to fill space when empty.
I use this technique in page layout columns, to keep every column in its position even if the other columns are empty.
Example:
.left-column
{
width: 200px;
min-height: 1px;
float: left;
}
.right-column
{
width: 500px;
min-height: 1px;
float: left;
}
I had the problem.
This process worked for me:
Ensure that during remove process you choose No to deleting database.
sudo apt-get remove --purge mysql*
sudo apt-get autoremove
sudo apt-get autoclean
sudo apt-get install mysql-server mysql-client
Here is the best solution for this. (ANGULAR All Version)
Addressing solution: To set a default value for @Input variable. If no value passed to that input variable then It will take the default value.
I have provided solution for this kind of similar question. You can find the full solution from here
export class CarComponent implements OnInit {
private _defaultCar: car = {
// default isCar is true
isCar: true,
// default wheels will be 4
wheels: 4
};
@Input() newCar: car = {};
constructor() {}
ngOnInit(): void {
// this will concate both the objects and the object declared later (ie.. ...this.newCar )
// will overwrite the default value. ONLY AND ONLY IF DEFAULT VALUE IS PRESENT
this.newCar = { ...this._defaultCar, ...this.newCar };
// console.log(this.newCar);
}
}
You just have to parse the string using JSON.parse like this :
var json_result = {"AuthenticateUserResult":"{\"PKPersonId\":1234,\"Salutation\":null,\"FirstName\":\"Miqdad\",\"LastName\":\"Kumar\",\"Designation\":null,\"Profile\":\"\",\"PhotoPath\":\"\/UploadFiles\/\"}"};
var parsed = JSON.parse(json_result.AuthenticateUserResult);
console.log(parsed);
Here you will have something like this :
Designation
null
FirstName
"Miqdad"
LastName
"Kumar"
PKPersonId
1234
PhotoPath
"/UploadFiles/"
Profile
""
Salutation
null
And for the request, don't forget to set dataType:'jsonp'
and to add a file in the root directory of your site called crossdomain.xml
and containing :
<?xml version="1.0"?>
<!DOCTYPE cross-domain-policy SYSTEM "http://www.adobe.com/xml/dtds/cross-domain-policy.dtd">
<cross-domain-policy>
<!-- Read this: www.adobe.com/devnet/articles/crossdomain_policy_file_spec.html -->
<!-- Most restrictive policy: -->
<site-control permitted-cross-domain-policies="none"/>
<!-- Least restrictive policy: -->
<!--
<site-control permitted-cross-domain-policies="all"/>
<allow-access-from domain="*" to-ports="*" secure="false"/>
<allow-http-request-headers-from domain="*" headers="*" secure="false"/>
-->
</cross-domain-policy>
EDIT to take care of Sanjay Kumar POST
So you can set the callback function to be called in the JSONP using jsonpCallback
!
$.Ajax({
jsonpCallback : 'your_function_name',
//OR with anonymous function
jsonpCallback : function(data) {
//do stuff
},
...
});
Your function expects a reference to an actual string pointer in the calling scope, not an anonymous string pointer. Thus:
string s;
string* _s = &s;
myfunc(_s);
should compile just fine.
However, this is only useful if you intend to modify the pointer you pass to the function. If you intend to modify the string itself you should use a reference to the string as Sake suggested. With that in mind it should be more obvious why the compiler complains about you original code. In your code the pointer is created 'on the fly', modifying that pointer would have no consequence and that is not what is intended. The idea of a reference (vs. a pointer) is that a reference always points to an actual object.
Use the HTML entity ∞
or ∞
.
Use Java 8 Optional
(no filter needed):
public static String orElse(String defaultValue) {
return Optional.ofNullable(System.getProperty("property")).orElse(defaultValue);
}
When you write .class
after a class name, it references the class literal -
java.lang.Class
object that represents information about given class.
For example, if your class is Print
, then Print.class
is an object that represents the class Print
on runtime. It is the same object that is returned by the getClass()
method of any (direct) instance of Print
.
Print myPrint = new Print();
System.out.println(Print.class.getName());
System.out.println(myPrint.getClass().getName());
You might get the error with the latest android gradle plugin (3.0):
Cannot set the value of read-only property 'outputFile'
According to the migration guide, we should use the following approach now:
applicationVariants.all { variant ->
variant.outputs.all {
outputFileName = "${applicationName}_${variant.buildType.name}_${defaultConfig.versionName}.apk"
}
}
Note 2 main changes here:
all
is used now instead of each
to iterate over the variant outputs.outputFileName
property is used instead of mutating a file reference.Everyone is correct here but writing same query twice is not a good way of programming ... so I have another way to do the full join in mysql which is as follows
SELECT
user_id , user_name, user_department
FROM
(SELECT
user_id , user_name , NULL as user_department
FROM
tb_users
UNION
SELECT
user_id ,NULL as user_name , user_department
FROM
tb_departments
) as t group by user_id
You could use componentDidMount and componentWillUnmount methods:
import React, { Component } from 'react';
import ReactDOM from 'react-dom';
class MovieItem extends Component
{
_handleNVEvent = event => {
...
};
componentDidMount() {
ReactDOM.findDOMNode(this).addEventListener('nv-event', this._handleNVEvent);
}
componentWillUnmount() {
ReactDOM.findDOMNode(this).removeEventListener('nv-event', this._handleNVEvent);
}
[...]
}
export default MovieItem;
Does the column allow null?
Seems to work. Just tested with phpMyAdmin, the column is of type int that allows nulls:
INSERT INTO `database`.`table` (`column`) VALUES (NULL);
cp `ls -ltr | grep 'Jun 14' | perl -wne 's/^.*\s+(\S+)$/$1/; print $1 . "\n";'` /some_destination_dir
You can also use the User Defined Runtime Attributes feature of interface builder to set the key path layer.cornerRadius
to a value. Make sure you include the QuartzCore
library though.
This trick also works for setting layer.borderWidth however it will not work for layer.borderColor
as this expects a CGColor
not a UIColor
.
You will not be able to see the effects in the storyboard because these parameters are evaluated at runtime.
The current Angular Router provides Navigation Events. You can subscribe to these and make UI changes accordingly. Remember to count in other Events such as NavigationCancel
and NavigationError
to stop your spinner in case router transitions fail.
app.component.ts - your root component
...
import {
Router,
// import as RouterEvent to avoid confusion with the DOM Event
Event as RouterEvent,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError
} from '@angular/router'
@Component({})
export class AppComponent {
// Sets initial value to true to show loading spinner on first load
loading = true
constructor(private router: Router) {
this.router.events.subscribe((e : RouterEvent) => {
this.navigationInterceptor(e);
})
}
// Shows and hides the loading spinner during RouterEvent changes
navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
this.loading = true
}
if (event instanceof NavigationEnd) {
this.loading = false
}
// Set loading state to false in both of the below events to hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this.loading = false
}
if (event instanceof NavigationError) {
this.loading = false
}
}
}
app.component.html - your root view
<div class="loading-overlay" *ngIf="loading">
<!-- show something fancy here, here with Angular 2 Material's loading bar or circle -->
<md-progress-bar mode="indeterminate"></md-progress-bar>
</div>
Performance Improved Answer: If you care about performance there is a better method, it is slightly more tedious to implement but the performance improvement will be worth the extra work. Instead of using *ngIf
to conditionally show the spinner, we could leverage Angular's NgZone
and Renderer
to switch on / off the spinner which will bypass Angular's change detection when we change the spinner's state. I found this to make the animation smoother compared to using *ngIf
or an async
pipe.
This is similar to my previous answer with some tweaks:
app.component.ts - your root component
...
import {
Router,
// import as RouterEvent to avoid confusion with the DOM Event
Event as RouterEvent,
NavigationStart,
NavigationEnd,
NavigationCancel,
NavigationError
} from '@angular/router'
import {NgZone, Renderer, ElementRef, ViewChild} from '@angular/core'
@Component({})
export class AppComponent {
// Instead of holding a boolean value for whether the spinner
// should show or not, we store a reference to the spinner element,
// see template snippet below this script
@ViewChild('spinnerElement')
spinnerElement: ElementRef
constructor(private router: Router,
private ngZone: NgZone,
private renderer: Renderer) {
router.events.subscribe(this._navigationInterceptor)
}
// Shows and hides the loading spinner during RouterEvent changes
private _navigationInterceptor(event: RouterEvent): void {
if (event instanceof NavigationStart) {
// We wanna run this function outside of Angular's zone to
// bypass change detection
this.ngZone.runOutsideAngular(() => {
// For simplicity we are going to turn opacity on / off
// you could add/remove a class for more advanced styling
// and enter/leave animation of the spinner
this.renderer.setElementStyle(
this.spinnerElement.nativeElement,
'opacity',
'1'
)
})
}
if (event instanceof NavigationEnd) {
this._hideSpinner()
}
// Set loading state to false in both of the below events to
// hide the spinner in case a request fails
if (event instanceof NavigationCancel) {
this._hideSpinner()
}
if (event instanceof NavigationError) {
this._hideSpinner()
}
}
private _hideSpinner(): void {
// We wanna run this function outside of Angular's zone to
// bypass change detection,
this.ngZone.runOutsideAngular(() => {
// For simplicity we are going to turn opacity on / off
// you could add/remove a class for more advanced styling
// and enter/leave animation of the spinner
this.renderer.setElementStyle(
this.spinnerElement.nativeElement,
'opacity',
'0'
)
})
}
}
app.component.html - your root view
<div class="loading-overlay" #spinnerElement style="opacity: 0;">
<!-- md-spinner is short for <md-progress-circle mode="indeterminate"></md-progress-circle> -->
<md-spinner></md-spinner>
</div>
Embrace the future! Just to be complete, you can also do this the Python 3k way by using the print function:
from __future__ import print_function # Py 2.6+; In Py 3k not needed
mylist = ['10', 12, '14'] # Note that 12 is an int
print(*mylist,sep='\n')
Prints:
10
12
14
Eventually, print
as Python statement will go away... Might as well start to get used to it.
<style>
.form-error {
border: 2px solid #e74c3c;
}
</style>
<div class="form-error">
{!! Form::select('color', $colors->prepend('Please Select Color', ''), ,['class' => 'form-control dropselect form-error'
,'tabindex' => $count++, 'id' => 'color']) !!}
</div>
Also it'd work to just specify ifelse()
twice:
plot(pos,cn, col= ifelse(cn >= 3, "red", ifelse(cn <= 1,"blue", "black")), ylim = c(0, 10))
In February 2017, they merged a PR adding this feature, they released in April 2017.
so to spy on getters/setters you use:
const spy = spyOnProperty(myObj, 'myGetterName', 'get');
where myObj is your instance, 'myGetterName' is the name of that one defined in your class as get myGetterName() {}
and the third param is the type get
or set
.
You can use the same assertions that you already use with the spies created with spyOn
.
So you can for example:
const spy = spyOnProperty(myObj, 'myGetterName', 'get'); // to stub and return nothing. Just spy and stub.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.returnValue(1); // to stub and return 1 or any value as needed.
const spy = spyOnProperty(myObj, 'myGetterName', 'get').and.callThrough(); // Call the real thing.
Here's the line in the github source code where this method is available if you are interested.
Answering the original question, with jasmine 2.6.1, you would:
const spy = spyOnProperty(myObj, 'valueA', 'get').andReturn(1);
expect(myObj.valueA).toBe(1);
expect(spy).toHaveBeenCalled();
You can also do like this:
template <typename T>
class make_vector {
public:
typedef make_vector<T> my_type;
my_type& operator<< (const T& val) {
data_.push_back(val);
return *this;
}
operator std::vector<T>() const {
return data_;
}
private:
std::vector<T> data_;
};
And use it like this:
std::vector<int> v = make_vector<int>() << 1 << 2 << 3;
We can align a view in center of the FrameLayout
by setting the layout_gravity
of the child view.
In XML:
android:layout_gravity="center"
In Java code:
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.CENTER;
Note: use FrameLayout.LayoutParams
not the others existing LayoutParams
Netcat sends one packet per newline. So you're fine. If you do anything more complex then you might need something else.
I was fooling around with Wireshark when I realized this. Don't know if it helps.
You can use DataFrame.loc
:
>>> df.loc[1]
>>> print(df)
result
A B C
1 1 1 6
2 9
2 1 8
2 11
2 1 1 7
2 10
2 1 9
2 12
>>> print(df.loc[1])
result
B C
1 1 6
2 9
2 1 8
2 11
>>> print(df.loc[2, 1])
result
C
1 7
2 10
Just download the apk from talkback website
Drag the downloaded apk to the started emulator, Go to settings on emulator > Search for talkback, you will now find it there
You can get the user's WindowsIdentity object under Windows Authentication by:
WindowsIdentity identity = HttpContext.Current.Request.LogonUserIdentity;
and then you can get the information about the user like identity.Name.
Please note you need to have HttpContext for these code.
I've faced the exactly same problem but I've fixed it with another approache.
Using Ubuntu 18.04, first disable systemd-resolved
service.
sudo systemctl disable systemd-resolved.service
Stop the service
sudo systemctl stop systemd-resolved.service
Then, remove the link to /run/systemd/resolve/stub-resolv.conf
in /etc/resolv.conf
sudo rm /etc/resolv.conf
Add a manually created resolv.conf
in /etc/
sudo vim /etc/resolv.conf
Add your prefered DNS server there
nameserver 208.67.222.222
I've tested this with success.
Seems, css transforms can be used
"‘transform’ property establishes a new local coordinate system at the element",
but ... this is not cross-browser, seems only Opera works correctly
A Linked List, at its core is a bunch of Nodes linked together.
So, you need to start with a simple Node class:
public class Node {
public Node next;
public Object data;
}
Then your linked list will have as a member one node representing the head (start) of the list:
public class LinkedList {
private Node head;
}
Then you need to add functionality to the list by adding methods. They usually involve some sort of traversal along all of the nodes.
public void printAllNodes() {
Node current = head;
while (current != null)
{
Console.WriteLine(current.data);
current = current.next;
}
}
Also, inserting new data is another common operation:
public void Add(Object data) {
Node toAdd = new Node();
toAdd.data = data;
Node current = head;
// traverse all nodes (see the print all nodes method for an example)
current.next = toAdd;
}
This should provide a good starting point.
Perhaps not as Pyhtonic a solution, but easier to read for noobs like me:
charlist = [34, 38, 49, 67, 89, 45, 103, 105, 119, 125]
mystring = ""
for char in charlist:
mystring = mystring + chr(char)
print mystring
As other users explained here about the usage of allowoveride directive, which is used to give permission to .htaccess usage. one thing I want to point out that never use allowoverride all if other users have access to write .htaccess instead use allowoveride as to permit certain modules.
Such as AllowOverride AuthConfig mod_rewrite
Instead of
AllowOverride All
Because module like mod_mime can render your server side files as plain text.
My favourite UI tutorials all come from zetcode.com:
These are tutorials I'd consider to be "starting tutorials". The example tutorial gets you up and going, but doesn't show you anything too advanced or give much explanation. Still, often, I find the big problem is "how do I start?" and these have always proved useful to me.
Usually the problem is not closing brackets (}) or missing semicolon (;)
I found this approach:
If HKLM\Software\WOW6432Node exists then Windows is 64-bit.
If HKLM\Software\WOW6432Node\Microsoft\Office exists, then Office is 32-bit.
If HKLM\Software\WOW6432Node\Microsoft\Office does not exist, but HKLM\Software\Microsoft\Office does exist, then Office is 64-bit.
If HKLM\Software\WOW6432Node does not exist, then Windows and Office are 32-bit.
Source: Technet Forums
You can also use a nested for
loop like shown below
n = 3
arr = []
for x in range(n):
arr.append([])
for y in range(n):
arr[x].append([])
for z in range(n):
arr[x][y].append(0)
print(arr)
Use the -r
option ("use extended regular expressions in the script") to sed
in order to use the {n}
syntax:
$ echo 'pid: 1234'| sed -r 's/^.{5}//'
1234
This is just "hack" style method:
int d[][] = new int[n][n];
static int swap(int a, int b) {
return a;
}
...
in main class -->
d[i][j + 1] = swap(d[i][j], d[i][j] = d[i][j + 1])
function chunk(arr, size) {
var tempAr = [];
var j= 0;
for(var i =0 ;i<arr.length;i++){
if(j==size || j==0){
tempAr.push(arr.slice(i,(i+size)));
j=0;
}j++;
}
return tempAr;
}
I know that question is a bit old but
pipenv --venv
/Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
rm -rf /Users/your_user_name/.local/share/virtualenvs/model-N-S4uBGU
If you're simply sharing a counter, consider using an AtomicInteger or another suitable class from the java.util.concurrent.atomic package:
public class Test {
private final static AtomicInteger count = new AtomicInteger(0);
public void foo() {
count.incrementAndGet();
}
}
The currently top-voted answer by Krzysztof Krason fails with <title>a</title><title>b</title>
. Also, it ignores title tags crossing line boundaries, e.g., for line-length reasons. Finally, it fails with <title >a</title>
(which is valid HTML: White space inside XML/HTML tags).
I therefore propose the following improvement:
import re
def search_title(html):
m = re.search(r"<title\s*>(.*?)</title\s*>", html, re.IGNORECASE | re.DOTALL)
return m.group(1) if m else None
Test cases:
print(search_title("<title >with spaces in tags</title >"))
print(search_title("<title\n>with newline in tags</title\n>"))
print(search_title("<title>first of two titles</title><title>second title</title>"))
print(search_title("<title>with newline\n in title</title\n>"))
Output:
with spaces in tags
with newline in tags
first of two titles
with newline
in title
Ultimately, I go along with others recommending an HTML parser - not only, but also to handle non-standard use of HTML tags.
Here is some SQL that actually make sense:
SELECT m.id FROM match m LEFT JOIN email e ON e.id = m.id WHERE e.id IS NULL
Simple is always better.
No, abstract class can never be instantiated.
Use this inside of query, no need to create extra variables.
CASE WHEN CreatedDate = '19000101' THEN '' WHEN CreatedDate =
'18000101' THEN '' ELSE CONVERT(CHAR(10), CreatedDate, 120) + ' ' +
CONVERT(CHAR(8), CreatedDate, 108) END as 'Created Date'
Works like a charm.
On *nix, you can use comm. The answer to the question is:
comm -1 -2 file1.sorted file2.sorted
# where file1 and file2 are sorted and piped into *.sorted
Here's the full usage of comm
:
comm [-1] [-2] [-3 ] file1 file2
-1 Suppress the output column of lines unique to file1.
-2 Suppress the output column of lines unique to file2.
-3 Suppress the output column of lines duplicated in file1 and file2.
Also note that it is important to sort the files before using comm, as mentioned in the man pages.
This will take care of the empty td:
<td style="min-width: 20px;"></td>
I just wanted to answer my question properly as some people do not read the comments below an answer. So here it is:
(function($) {
$.fn.nodoubletapzoom = function() {
$(this).bind('touchstart', function preventZoom(e) {
var t2 = e.timeStamp
, t1 = $(this).data('lastTouch') || t2
, dt = t2 - t1
, fingers = e.originalEvent.touches.length;
$(this).data('lastTouch', t2);
if (!dt || dt > 500 || fingers > 1) return; // not double-tap
e.preventDefault(); // double tap - prevent the zoom
// also synthesize click events we just swallowed up
$(this).trigger('click').trigger('click');
});
};
})(jQuery);
I did not write this, i just modified it. I found the iOS-only version here: https://gist.github.com/2047491 (thanks Kablam)
window.addEventListener("scroll",function(){
window.lastScrollTime = new Date().getTime()
});
function is_scrolling() {
return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
}
Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".
(addEventListener
is better than onScroll
because the former can coexist nicely with any other code that uses onScroll
.)
myString.Length; //will get you your result
//alternatively, if you only want the count of letters:
myString.Count(char.IsLetter);
//however, if you want to display the words as ***_***** (where _ is a space)
//you can also use this:
//small note: that will fail with a repeated word, so check your repeats!
myString.Split(' ').ToDictionary(n => n, n => n.Length);
//or if you just want the strings and get the counts later:
myString.Split(' ');
//will not fail with repeats
//and neither will this, which will also get you the counts:
myString.Split(' ').Select(n => new KeyValuePair<string, int>(n, n.Length));
This is my sort. It will do number sort , string sort and date sort .
import { Pipe , PipeTransform } from "@angular/core";
@Pipe({
name: 'sortPipe'
})
export class SortPipe implements PipeTransform {
transform(array: Array<string>, key: string): Array<string> {
console.log("Entered in pipe******* "+ key);
if(key === undefined || key == '' ){
return array;
}
var arr = key.split("-");
var keyString = arr[0]; // string or column name to sort(name or age or date)
var sortOrder = arr[1]; // asc or desc order
var byVal = 1;
array.sort((a: any, b: any) => {
if(keyString === 'date' ){
let left = Number(new Date(a[keyString]));
let right = Number(new Date(b[keyString]));
return (sortOrder === "asc") ? right - left : left - right;
}
else if(keyString === 'name'){
if(a[keyString] < b[keyString]) {
return (sortOrder === "asc" ) ? -1*byVal : 1*byVal;
} else if (a[keyString] > b[keyString]) {
return (sortOrder === "asc" ) ? 1*byVal : -1*byVal;
} else {
return 0;
}
}
else if(keyString === 'age'){
return (sortOrder === "asc") ? a[keyString] - b[keyString] : b[keyString] - a[keyString];
}
});
return array;
}
}
If you want the font you chose to be applied and not the one in bootstrap without modifying the original bootstrap files you can rearrange the tags in your HTML documents so your CSS files that applies the font called after the bootstrap one. In this way since the browser reads the documents line after line first it will read the bootstrap files and apply it roles then it will read your file and override the roles in the bootstrap and replace it with the ones in your file.
Open the Terminal
->
copy
below command
sudo gem install cocoapods
It will install the latest stable version of cocoapods
.
after that, you need to update pod using below command
pod setup
You can check pod version using below command
pod --version
Just right click on your terminal icon, and select open a new window. Now you'll have two terminal windows open. In the new window, type, mongo and hit enter. Boom, that'll work like it's supposed to.
I had the same issue today using primefaces (primeng) and angular 7. Add the following to your style.css
p-button {
-webkit-appearance: none !important;
}
i am also using a bit of bootstrap which has a reboot.css, that overrides it with (thats why i had to add !important)
button {
-webkit-appearance: button;
}
Casting is necessary to tell that you are calling a child and not a parent method. So it's ever downward. However if the method is already defined in the parent class and overriden in the child class, you don't any cast. Here an example:
class Parent{
void method(){ System.out.print("this is the parent"); }
}
class Child extends Parent{
@override
void method(){ System.out.print("this is the child"); }
}
...
Parent o = new Child();
o.method();
((Child)o).method();
The two method call will both print : "this is the child".
Let us say we have a project social_login. To check the traffic to your repo, you can goto https://github.com//social_login/graphs/traffic
This trick supposed to prevent v = null
kind of typos.
But Java allows only boolean expressions as if()
conditions so that trick does not make much sense, compiler will find those typos anyway.
It is still valuable trick for C/C++ code though.
I think you can use the nrows
parameter. From the docs:
nrows : int, default None
Number of rows of file to read. Useful for reading pieces of large files
which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):
In [1]: import pandas as pd
In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s
In [3]: len(z)
Out[3]: 20
In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s
I wish I had an answer but I only have Part of one. And I cannot take credit for it but the way to get it is below.
This is a more serious issue than it is being given credit for from the sound of the replies. Everyone is automatically assuming that the content that needs protection is for public consumption. This is not always the case. Sometimes there are legal or contractual reasons that require the site owner to take all possible measures to prevent downloading the file. The most obvious one I can think of has already brought up. The “Action Option Bar” presented by the browser to on almost any file you can left click.
Adobe DRM does nothing about that and worse, Adobe Acrobat cannot even have its own abilities to “Save” blocked as part of the “DRM” protection. This option comes up even in Reader no matter what other security selections you have chosen.
In our case, Adobe Acrobat was purchased solely to provide some degree of protection for their own format. It is hard to believe that Adobe will let you prevent printing, prevent editing, prevent even opening without a password or you can really go all out and use a certificate for your encryption. Yet they have no options to prevent saving at any point, anywhere. Instead offering the consolation of telling you “Don’t worry: The copy they download without your permission will also have the same DRM on it as well”. Unfortunately that was not the sole purpose of the purchase and half a solution is no “solution” at all. There are probably 100 programs that are actually sold just to remove the DRM from Adobe documents and even if not, the point was that the client specified that no downloads be allowed even by users who had access to the private site. Therefore the need to prevent the download to start with is not so hard to understand. While conversion to FLASH may give you the download protection, you lose all the rest. Unless I can find a way to prevent opening, saving etc for a Flash File. Next, is it possible to password protect a Flash file from opening when clicked on?
The “partial fix” that I was finally able to get to work as needed still only disables all the “right click” functions but it does include a nice “Warning Box” where I can explain that the User has already agreed NOT to download, print, save and so on just to have access to the page. I am not sure if I could post the code here or whether it is acceptable to paste links either but a Google search for "Maximus right click" will take you to it. And it was one of several examples, it just happened to be the one I could implement the easiest and worked better than the others. Credit where credit is due.
Another option I was given by someone was a product called “Flipping Book”. And the user above suggestions for “Atalasoft” ( I had already found that and have sent a request for more information). Hopefully it will be “The Solution” and I can implement it in time to help. It seems to me that this is a place where there is an obvious need for a one-step packaged solution and usually "The Laws of Nature" take care of such an Imbalance in short order. Yet my research has taken me through many years of posters all asking for the same thing. Looks like someone would be able to make a nice living off a “simple” way to add a little more "protection" to “PDFs” (or other documents, images etc) for the people who obviously are in need of it. If I find it, and it works, I'm buying it. :>)
I wish I had skills as a programmer because I have some pretty good ideas of ways to implement such a product, unfortunately, I do not know how to put these ideas into practical use.
For those looking for the SSMS 2012 solution... see this answer:
Essentially, in 2012 you can delete the server from the server list dropdown which clears all cached logins for that server.
Works also in v17 (build 14.x).
Try this
CSS
.header{
height:30px;
}
.Content{
height: 100%;
overflow: auto;
padding-top: 10px;
padding-bottom: 40px;
}
.Footer{
position: relative;
margin-top: -30px; /* negative value of footer height */
height: 30px;
clear:both;
}
HTML
<body>
<div class="Header">Header</div>
<div class="Content">Content</div>
<div class="Footer">Footer</div>
</body>
Many of these projects mentioned above are dead or dying, lacking activity and interest from author side. Interesting to follow how this area develops.
For the record, in era of plugin based implementations, KDE camp had an attempt to solve this with plugin and non-language specific way and created the Kross https://en.wikipedia.org/wiki/Kross_(software) - in my understanding it never took off even inside the community itself.
During this chicken and egg -problem time, javascript-based implementions are definately way to go. Maybe in the future we seee pure and clean, full Python support natively in browsers.
Preamble: Since Spring-Security 3.2 there is a nice annotation @AuthenticationPrincipal
described at the end of this answer. This is the best way to go when you use Spring-Security >= 3.2.
When you:
HandlerMethodArgumentResolver
or WebArgumentResolver
can solve this in an elegant way, or just want to an learn the background behind @AuthenticationPrincipal
and AuthenticationPrincipalArgumentResolver
(because it is based on a HandlerMethodArgumentResolver
)then keep on reading — else just use @AuthenticationPrincipal
and thank to Rob Winch (Author of @AuthenticationPrincipal
) and Lukas Schmelzeisen (for his answer).
(BTW: My answer is a bit older (January 2012), so it was Lukas Schmelzeisen that come up as the first one with the @AuthenticationPrincipal
annotation solution base on Spring Security 3.2.)
Then you can use in your controller
public ModelAndView someRequestHandler(Principal principal) {
User activeUser = (User) ((Authentication) principal).getPrincipal();
...
}
That is ok if you need it once. But if you need it several times its ugly because it pollutes your controller with infrastructure details, that normally should be hidden by the framework.
So what you may really want is to have a controller like this:
public ModelAndView someRequestHandler(@ActiveUser User activeUser) {
...
}
Therefore you only need to implement a WebArgumentResolver
. It has a method
Object resolveArgument(MethodParameter methodParameter,
NativeWebRequest webRequest)
throws Exception
That gets the web request (second parameter) and must return the User
if its feels responsible for the method argument (the first parameter).
Since Spring 3.1 there is a new concept called HandlerMethodArgumentResolver
. If you use Spring 3.1+ then you should use it. (It is described in the next section of this answer))
public class CurrentUserWebArgumentResolver implements WebArgumentResolver{
Object resolveArgument(MethodParameter methodParameter, NativeWebRequest webRequest) {
if(methodParameter is for type User && methodParameter is annotated with @ActiveUser) {
Principal principal = webRequest.getUserPrincipal();
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
You need to define the Custom Annotation -- You can skip it if every instance of User should always be taken from the security context, but is never a command object.
@Target(ElementType.PARAMETER)
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface ActiveUser {}
In the configuration you only need to add this:
<bean class="org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter"
id="applicationConversionService">
<property name="customArgumentResolver">
<bean class="CurrentUserWebArgumentResolver"/>
</property>
</bean>
@See: Learn to customize Spring MVC @Controller method arguments
It should be noted that if you're using Spring 3.1, they recommend HandlerMethodArgumentResolver over WebArgumentResolver. - see comment by Jay
HandlerMethodArgumentResolver
for Spring 3.1+public class CurrentUserHandlerMethodArgumentResolver
implements HandlerMethodArgumentResolver {
@Override
public boolean supportsParameter(MethodParameter methodParameter) {
return
methodParameter.getParameterAnnotation(ActiveUser.class) != null
&& methodParameter.getParameterType().equals(User.class);
}
@Override
public Object resolveArgument(MethodParameter methodParameter,
ModelAndViewContainer mavContainer,
NativeWebRequest webRequest,
WebDataBinderFactory binderFactory) throws Exception {
if (this.supportsParameter(methodParameter)) {
Principal principal = webRequest.getUserPrincipal();
return (User) ((Authentication) principal).getPrincipal();
} else {
return WebArgumentResolver.UNRESOLVED;
}
}
}
In the configuration, you need to add this
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="CurrentUserHandlerMethodArgumentResolver"/>
</mvc:argument-resolvers>
</mvc:annotation-driven>
@See Leveraging the Spring MVC 3.1 HandlerMethodArgumentResolver interface
Spring Security 3.2 (do not confuse with Spring 3.2) has own build in solution: @AuthenticationPrincipal
(org.springframework.security.web.bind.annotation.AuthenticationPrincipal
) . This is nicely described in Lukas Schmelzeisen`s answer
It is just writing
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
To get this working you need to register the AuthenticationPrincipalArgumentResolver
(org.springframework.security.web.bind.support.AuthenticationPrincipalArgumentResolver
) : either by "activating" @EnableWebMvcSecurity
or by registering this bean within mvc:argument-resolvers
- the same way I described it with may Spring 3.1 solution above.
@See Spring Security 3.2 Reference, Chapter 11.2. @AuthenticationPrincipal
It works like the Spring 3.2 solution, but in Spring 4.0 the @AuthenticationPrincipal
and AuthenticationPrincipalArgumentResolver
was "moved" to an other package:
org.springframework.security.core.annotation.AuthenticationPrincipal
org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver
(But the old classes in its old packges still exists, so do not mix them!)
It is just writing
import org.springframework.security.core.annotation.AuthenticationPrincipal;
ModelAndView someRequestHandler(@AuthenticationPrincipal User activeUser) {
...
}
To get this working you need to register the (org.springframework.security.web.method.annotation.
) AuthenticationPrincipalArgumentResolver
: either by "activating" @EnableWebMvcSecurity
or by registering this bean within mvc:argument-resolvers
- the same way I described it with may Spring 3.1 solution above.
<mvc:annotation-driven>
<mvc:argument-resolvers>
<bean class="org.springframework.security.web.method.annotation.AuthenticationPrincipalArgumentResolver" />
</mvc:argument-resolvers>
</mvc:annotation-driven>
@See Spring Security 5.0 Reference, Chapter 39.3 @AuthenticationPrincipal
in visual 2019, Open Options to show all enter image description here
and multi select: keep Ctrl + Alt
then click position you want
or, keep Shift + Alt
then click position to multi select multi line from start to end line clicked
Use one way flow syntax property binding:
<div [innerHTML]="comment"></div>
From angular docs: "Angular recognizes the value as unsafe and automatically sanitizes it, which removes the <script>
tag but keeps safe content such as the <b>
element."
By definition arrays are fixed size. You can use instead an Arraylist wich is that, a "dynamic size" array. Actually what happens is that the VM "adjust the size"* of the array exposed by the ArrayList.
*using back-copy arrays
...because the .NET environment is designed to support many languages.
System.Boolean (in mscorlib.dll) is designed to be used internally by languages to support a boolean datatype. C# uses all lowercase for its keywords, hence 'bool', 'true', and 'false'.
VB.NET however uses standard casing: hence 'Boolean', 'True', and 'False'.
Since the languages have to work together, you couldn't have true.ToString() (C#) giving a different result to True.ToString() (VB.NET). The CLR designers picked the standard CLR casing notation for the ToString() result.
The string representation of the boolean true is defined to be Boolean.TrueString.
(There's a similar case with System.String: C# presents it as the 'string' type).
I had the same problem and seems like we haven't had an accurate solution. Hope this can help other people.
After take time exploring around, I finally found the answer. This is my code to get file attach with jQuery:
var attach_id = "id_of_attachment_file";
var size = $('#'+attach_id)[0].files[0].size;
alert(size);
This is just the example code for getting the file size. If you want do other stuffs, feel free to change the code to satisfy your needs.
Using ES6 destructuring: (avoiding mutation off the original array)
const newArr = [item, ...oldArr]
I had mostly the same problem and ended up a a different solution that makes this type of problem trivial to query.
I have a table of sensor data (1 minute data from about 30 sensors)
SensorReadings->(timestamp,value,idSensor)
and I have a sensor table that has lots of mostly static stuff about the sensor but the relevant fields are these:
Sensors->(idSensor,Description,tvLastUpdate,tvLastValue,...)
The tvLastupdate and tvLastValue are set in a trigger on inserts to the SensorReadings table. I always have direct access to these values without needing to do any expensive queries. This does denormalize slightly. The query is trivial:
SELECT idSensor,Description,tvLastUpdate,tvLastValue
FROM Sensors
I use this method for data that is queried often. In my case I have a sensor table, and a large event table, that have data coming in at the minute level AND dozens of machines are updating dashboards and graphs with that data. With my data scenario the trigger-and-cache method works well.
ctypes will be the easiest thing to use but (mis)using it makes Python subject to crashing. If you are trying to do something quickly, and you are careful, it's great.
I would encourage you to check out Boost Python. Yes, it requires that you write some C++ code and have a C++ compiler, but you don't actually need to learn C++ to use it, and you can get a free (as in beer) C++ compiler from Microsoft.
You can use qTip for this; However you'd have to code a little for launching it on mouseover event; And in case you want a default watermark on your text fields, you'd have to use the watermark plugin...
I realized that this leads to lot of repetitive code; So I wrote a plugin on top of qTip that makes it really easy to attach informational popup to form fields. You can check it out here: https://bitbucket.org/gautamtandon/jquery.attachinfo
Hope this helps.
Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.
Do you have this:
use Cartalyst\Sentry\Sentry;
In your code?
Ok, but if this line is working for you:
$user = $this->sentry->register(array( 'username' => e($data['username']), 'email' => e($data['email']), 'password' => e($data['password']) ));
So you already have it instantiated and you can surely do:
$adminGroup = $this->sentry->findGroupById(5);
Long press on Google play application
Now again click on Google Play app, It will work now.
npm pack
+ package.json
This is what worked for me:
module project
, execute npm pack
:This will build a <package-name>-<version>.tar.gz
file.
consumer project
Ideally you can put all such files in a tmp
folder in your consumer-project
root:
package.json
:"dependencies": {
"my-package": "file:/./tmp/my-package-1.3.3.tar.gz"
}
Install
the packages:npm install
or npm i
or yarn
consumer-project's node_modules
folder.Good Luck...
Search for setTextAppearance
or also setTextTypeface
. There is similar question on stackoverflow: How to change a TextView's style at runtime
For PyTorch v1.0 and possibly above:
>>> import torch
>>> var = torch.tensor([[1,0], [0,1]])
# Using .size function, returns a torch.Size object.
>>> var.size()
torch.Size([2, 2])
>>> type(var.size())
<class 'torch.Size'>
# Similarly, using .shape
>>> var.shape
torch.Size([2, 2])
>>> type(var.shape)
<class 'torch.Size'>
You can cast any torch.Size object to a native Python list:
>>> list(var.size())
[2, 2]
>>> type(list(var.size()))
<class 'list'>
In PyTorch v0.3 and 0.4:
Simply list(var.size())
, e.g.:
>>> import torch
>>> from torch.autograd import Variable
>>> from torch import IntTensor
>>> var = Variable(IntTensor([[1,0],[0,1]]))
>>> var
Variable containing:
1 0
0 1
[torch.IntTensor of size 2x2]
>>> var.size()
torch.Size([2, 2])
>>> list(var.size())
[2, 2]
it works for me, just change: Provider=Microsoft.Jet.OLEDB.4.0 (VS2013)
OleDbConnection connection = new OleDbConnection(
"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=Z:\\GENERAL\\OFMPTP_PD_SG.MDB");
DataSet DS = new DataSet();
connection.Open();
string query =
@"SELECT * from MONTHLYPROD";
OleDbDataAdapter DBAdapter = new OleDbDataAdapter();
DBAdapter.SelectCommand = new OleDbCommand(query, connection);
DBAdapter.Fill(DS);
Luis Montoya
I have following idea how you can deal with such Access Device ID (ADID):
Gen ADID
Use device
In this approach, as long user use same browser and don't make device reset, the device has access to data. If someone made device-reset then again trusted user need to login and gen ADID.
You can even create some ADID management system for trusted user where on generate ADID he can also input device serial-number and in future in case of device reset he can find this device and regenerate ADID for it (which not increase whitelist size) and he can also drop some ADID from whitelist for devices which he will not longer give access to server data.
In case when sytem use many domains/subdomains te manager after login should see many "Give access from domain xyz.com to this device" buttons - each button will redirect device do proper domain, gent ADID and redirect back.
Simpler approach based on links:
UPDATE : check Peter's answer below for a builtin solution :
This is a helper to set a persistent cookie:
import datetime
def set_cookie(response, key, value, days_expire=7):
if days_expire is None:
max_age = 365 * 24 * 60 * 60 # one year
else:
max_age = days_expire * 24 * 60 * 60
expires = datetime.datetime.strftime(
datetime.datetime.utcnow() + datetime.timedelta(seconds=max_age),
"%a, %d-%b-%Y %H:%M:%S GMT",
)
response.set_cookie(
key,
value,
max_age=max_age,
expires=expires,
domain=settings.SESSION_COOKIE_DOMAIN,
secure=settings.SESSION_COOKIE_SECURE or None,
)
Use the following code before sending a response.
def view(request):
response = HttpResponse("hello")
set_cookie(response, 'name', 'jujule')
return response
UPDATE : check Peter's answer below for a builtin solution :
First off all I would like to thanks @MaximShoustin.
Thanks of you I have really nice table.
I provide some small modification in $scope.range
and $scope.setPage
.
In this way I have now possibility to go to the last page or come back to the first page.
Also when I'm going to next or prev page the navigation is changing when $scope.gap
is crossing. And the current page is not always on first position. For me it's looking more nicer.
Here is the new fiddle example: http://jsfiddle.net/qLBRZ/3/
You can press I
twice to interrupt the kernel.
This only works if you're in Command mode. If not already enabled, press Esc to enable it.
No reason. Maybe the person who coded it came from PHP. It has the same effect as if you had named it "_item" or "item" or "item$$".
As a suffix (like "item$", pronounced "items"), it can signify an observable such as a DOM element as a convention called "Finnish Notation" similar to the Hungarian Notation.
You could refer to column alias but you need to define it using CROSS/OUTER APPLY
:
SELECT s.logcount, s.logUserID, s.maxlogtm, c.daysdiff
FROM statslogsummary s
CROSS APPLY (SELECT DATEDIFF(day, s.maxlogtm, GETDATE()) AS daysdiff) c
WHERE c.daysdiff > 120;
Pros:
WHERE/GROUP BY/ORDER BY
You will want to have a look at setInterval() and setTimeout().
Here is a decent tutorial article.
This website has a concise tutorial on how to use SQL Server Management Studio. As you will see you can open a "Query Window", paste your script and run it. It does not allow you to execute scripts by using the file path. However, you can do this easily by using the command line (cmd.exe):
sqlcmd -S .\SQLExpress -i SqlScript.sql
Where SqlScript.sql
is the script file name located at the current directory. See this Microsoft page for more examples
The latest PowerShell version as of Sept 2015 is PowerShell 4.0. It's bundled with Windows Management Framework 4.0.
Here's the download page for PowerShelll 4.0 for all versions of Windows. For Windows 7, there are 2 links on that page, 1 for x64 and 1 for x86.
A download link would be a link to the resource you want to download. It is constructed in the same way that any other link would be:
<a href="path to resource.name of file">Link</a>
<a href="files/installer.exe">Link to installer</a>
I User this Code in my project, Useful for me.
private void Form1_Resize(object sender, EventArgs e)
{
int w = MainPanel.Width; // you can use form.width when you don't use panels
w = (w - 120)/4; // 120 because set 15px for each side of panels
// and put panels in FlowLayoutPanel
// 4 because i have 4 panel boxes
panel1.Width = w;
panel2.Width = w;
panel3.Width = w;
panel4.Width = w;
}
If you're using rails you can also use in_groups_of:
foo.in_groups_of(3)
One way would be to convert both strings to upper or lower:
test $(echo "string" | /bin/tr '[:upper:]' '[:lower:]') = $(echo "String" | /bin/tr '[:upper:]' '[:lower:]') && echo same || echo different
Another way would be to use grep:
echo "string" | grep -qi '^String$' && echo same || echo different
Standard way:
@RestController
public class Main {
UserService userService;
public Main(){
userService = new UserServiceImpl();
}
@GetMapping("/")
public String index(){
return userService.print("Example test");
}
}
User service interface:
public interface UserService {
String print(String text);
}
UserServiceImpl class:
public class UserServiceImpl implements UserService {
@Override
public String print(String text) {
return text + " UserServiceImpl";
}
}
Output: Example test UserServiceImpl
That is a great example of tight coupled classes, bad design example and there will be problem with testing (PowerMockito is also bad).
Now let's take a look at SpringBoot dependency injection, nice example of loose coupling:
Interface remains the same,
Main class:
@RestController
public class Main {
UserService userService;
@Autowired
public Main(UserService userService){
this.userService = userService;
}
@GetMapping("/")
public String index(){
return userService.print("Example test");
}
}
ServiceUserImpl class:
@Component
public class UserServiceImpl implements UserService {
@Override
public String print(String text) {
return text + " UserServiceImpl";
}
}
Output: Example test UserServiceImpl
and now it's easy to write test:
@RunWith(MockitoJUnitRunner.class)
public class MainTest {
@Mock
UserService userService;
@Test
public void indexTest() {
when(userService.print("Example test")).thenReturn("Example test UserServiceImpl");
String result = new Main(userService).index();
assertEquals(result, "Example test UserServiceImpl");
}
}
I showed @Autowired
annotation on constructor but it can also be used on setter or field.
This one will remove the comma if it is the last character in the string..
var str = $("#ControlId").val();
if(str.substring(str.length-1)==',') {
var stringWithoutLastComma = str.substring(0,str.length-1);
}
You can also use freely Application.StartupPath from System.Windows.Forms, but you must to add reference for System.Windows.Forms assembly!
In the newer distribution you can just type command as blow
su root
dnf update
dnf install gcc-c++
You could also simply link both cells, and have an =Cell formula in each column like, =Sheet2!A2
in Sheet 1 A2 and =Sheet2!B2
in Sheet 1 B2, and drag it down, and then sort those two columns the way you want.
This would be better if your unique items change also, then all you would do is sort and be done.
Sometimes this error comes because it's simply the wrong folder. :-(
It shall be the folder which contains the pom.xml
.
Create below class in base class. Class To get all controls:
public static class ControlExtensions
{
public static IEnumerable<T> GetAllControlsOfType<T>(this Control parent) where T : Control
{
var result = new List<T>();
foreach (Control control in parent.Controls)
{
if (control is T)
{
result.Add((T)control);
}
if (control.HasControls())
{
result.AddRange(control.GetAllControlsOfType<T>());
}
}
return result;
}
}
From Database: Get All Actions IDs (like divAction1,divAction2 ....) dynamic in DATASET (DTActions) allow on specific User.
In Aspx: in HTML Put Action(button,anchor etc) in div or span and give them id like
<div id="divAction1" visible="false" runat="server" clientidmode="Static">
<a id="anchorAction" runat="server">Submit
</a>
</div>
IN CS: Use this function on your page:
private void ShowHideActions()
{
var controls = Page.GetAllControlsOfType<HtmlGenericControl>();
foreach (DataRow dr in DTActions.Rows)
{
foreach (Control cont in controls)
{
if (cont.ClientID == "divAction" + dr["ActionID"].ToString())
{
cont.Visible = true;
}
}
}
}
With get()
method you get a collection (all data that match the query), try to use first()
instead, it return only one element, like this:
$about = Page::where('page', 'about-me')->first();
All major browsers now include native JSON encoding/decoding.
// To encode an object (This produces a string)
var json_str = JSON.stringify(myobject);
// To decode (This produces an object)
var obj = JSON.parse(json_str);
Note that only valid JSON data will be encoded. For example:
var obj = {'foo': 1, 'bar': (function (x) { return x; })}
JSON.stringify(obj) // --> "{\"foo\":1}"
Valid JSON types are: objects, strings, numbers, arrays, true
, false
, and null
.
Some JSON resources:
The method System.Web.UI.Page.RegisterClientScriptBlock has been deprecated for some time (along with the other Page.Register* methods), ever since .NET 2.0 as shown by MSDN.
Instead use the .NET 2.0 Page.ClientScript.Register* methods. - (The ClientScript property expresses an instance of the ClientScriptManager class )
Guessing the problem
If you are saying your JavaScript alert box occurs before the page's content is visibly rendered, and therefore the page remains white (or still unrendered) when the alert box is dismissed by the user, then try using the Page.ClientScript.RegisterStartupScript(..) method instead because it runs the given client-side code when the page finishes loading - and its arguments are similar to what you're using already.
Also check for general JavaScript errors in the page - this is often seen by an error icon in the browser's status bar. Sometimes a JavaScript error will hold up or disturb unrelated elements on the page.
pip install -U websocket
I just use this to fix my problem
You can change the font size in R Markdown with HTML code tags <font size="1"> your text </font>
. This code is added to the R Markdown document and will alter the output of the HTML output.
For example:
<font size="1"> This is my text number1</font> _x000D_
_x000D_
<font size="2"> This is my text number 2 </font>_x000D_
_x000D_
<font size="3"> This is my text number 3</font> _x000D_
_x000D_
<font size="4"> This is my text number 4</font> _x000D_
_x000D_
<font size="5"> This is my text number 5</font> _x000D_
_x000D_
<font size="6"> This is my text number 6</font>
_x000D_
Error with Uncaught SyntaxError: Unexpected token <
using @Mario answer but that was only part of my problem. Another problem is, javascript doesn't get any data from PHP file. That was solved using this code, inside PHP file: header("Content-Type: text/javascript; charset=utf-8");
This answer is found on this link, where I opened another question to solve this issue: Can't receive json data from PHP in Chrome and Opera
Very simple:
Use COUNT_BIG(*) AS NumStreams
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>
Instead of WorksheetFunction.Vlookup
, you can use Application.Vlookup
. If you set a Variant
equal to this it returns Error 2042 if no match is found. You can then test the variant - cellNum
in this case - with IsError
:
Sub test()
Dim ws As Worksheet: Set ws = Sheets("2012")
Dim rngLook As Range: Set rngLook = ws.Range("A:M")
Dim currName As String
Dim cellNum As Variant
'within a loop
currName = "Example"
cellNum = Application.VLookup(currName, rngLook, 13, False)
If IsError(cellNum) Then
MsgBox "no match"
Else
MsgBox cellNum
End If
End Sub
The Application
versions of the VLOOKUP
and MATCH
functions allow you to test for errors without raising the error. If you use the WorksheetFunction
version, you need convoluted error handling that re-routes your code to an error handler, returns to the next statement to evaluate, etc. With the Application
functions, you can avoid that mess.
The above could be further simplified using the IIF
function. This method is not always appropriate (e.g., if you have to do more/different procedure based on the If/Then
) but in the case of this where you are simply trying to determinie what prompt to display in the MsgBox, it should work:
cellNum = Application.VLookup(currName, rngLook, 13, False)
MsgBox IIF(IsError(cellNum),"no match", cellNum)
Consider those methods instead of On Error ...
statements. They are both easier to read and maintain -- few things are more confusing than trying to follow a bunch of GoTo
and Resume
statements.
why does the Text take up the full space of the View, instead of just the space for "Hello"?
Because the View
is a flex container and by default has flexDirection: 'column'
and alignItems: 'stretch'
, which means that its children should be stretched out to fill its width.
(Note, per the docs, that all components in React Native are display: 'flex'
by default and that display: 'inline'
does not exist at all. In this way, the default behaviour of a Text
within a View
in React Native differs from the default behaviour of span
within a div
on the web; in the latter case, the span would not fill the width of the div
because a span
is an inline element by default. There is no such concept in React Native.)
How can the Text be floated / aligned to the right?
The float
property doesn't exist in React Native, but there are loads of options available to you (with slightly different behaviours) that will let you right-align your text. Here are the ones I can think of:
textAlign: 'right'
on the Text
element<View>
<Text style={{textAlign: 'right'}}>Hello, World!</Text>
</View>
(This approach doesn't change the fact that the Text
fills the entire width of the View
; it just right-aligns the text within the Text
.)
alignSelf: 'flex-end'
on the Text
<View>
<Text style={{alignSelf: 'flex-end'}}>Hello, World!</Text>
</View>
This shrinks the Text
element to the size required to hold its content and puts it at the end of the cross direction (the horizontal direction, by default) of the View
.
alignItems: 'flex-end'
on the View
<View style={{alignItems: 'flex-end'}}>
<Text>Hello, World!</Text>
</View>
This is equivalent to setting alignSelf: 'flex-end'
on all the View
's children.
flexDirection: 'row'
and justifyContent: 'flex-end'
on the View
<View style={{flexDirection: 'row', justifyContent: 'flex-end'}}>
<Text>Hello, World!</Text>
</View>
flexDirection: 'row'
sets the main direction of layout to be horizontal instead of vertical; justifyContent
is just like alignItems
, but controls alignment in the main direction instead of the cross direction.
flexDirection: 'row'
on the View
and marginLeft: 'auto'
on the Text
<View style={{flexDirection: 'row'}}>
<Text style={{marginLeft: 'auto'}}>Hello, World!</Text>
</View>
This approach is demonstrated, in the context of the web and real CSS, at https://stackoverflow.com/a/34063808/1709587.
position: 'absolute'
and right: 0
on the Text
:<View>
<Text style={{position: 'absolute', right: 0}}>Hello, World!</Text>
</View>
Like in real CSS, this takes the Text
"out of flow", meaning that its siblings will be able to overlap it and its vertical position will be at the top of the View
by default (although you can explicitly set a distance from the top of the View
using the top
style property).
Naturally, which of these various approaches you want to use - and whether the choice between them even matters at all - will depend upon your precise circumstances.
As Per Java 8, we can use this way.
double[][] arr = new double[20][4];
Arrays.stream(arr).forEach(a -> Arrays.fill(a, 0));
We can initialize a value in multidimensional array in a nicer and smart way.
window.location.replace('http://sidanmor.com');
It's better than using window.location.href = 'http://sidanmor.com';
Using replace()
is better because it does not keep the originating page in the session history, meaning the user won't get stuck in a never-ending back-button fiasco.
If you want to simulate someone clicking on a link, use
window.location.href
If you want to simulate an HTTP redirect, use
window.location.replace
For example:
// similar behavior as an HTTP redirect
window.location.replace("http://sidanmor.com");
// similar behavior as clicking on a link
window.location.href = "http://sidanmor.com";
Taken from here: How to redirect to another page in jQuery?
http://plnkr.co/edit/A2IG03FLYnEYMpZ5RxEm?p=preview
Here is a case sensitive search that also separates your search into words to search in each model as well. Only when it finds a space will it try to split the query into an array and then search each word.
It returns true if every word is at least in one of the models.
$scope.songSearch = function (row) {
var query = angular.lowercase($scope.query);
if (query.indexOf(" ") > 0) {
query_array = query.split(" ");
search_result = false;
for (x in query_array) {
query = query_array[x];
if (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1){
search_result = true;
} else {
search_result = false;
break;
}
}
return search_result;
} else {
return (angular.lowercase(row.model1).indexOf(query || '') !== -1 || angular.lowercase(row.model2).indexOf(query || '') !== -1 || angular.lowercase(row.model3).indexOf(query || '') !== -1);
}
};
Use r.URL.Query()
when you appending to existing query, if you are building new set of params use the url.Values
struct like so
package main
import (
"fmt"
"log"
"net/http"
"net/url"
"os"
)
func main() {
req, err := http.NewRequest("GET","http://api.themoviedb.org/3/tv/popular", nil)
if err != nil {
log.Print(err)
os.Exit(1)
}
// if you appending to existing query this works fine
q := req.URL.Query()
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
// or you can create new url.Values struct and encode that like so
q := url.Values{}
q.Add("api_key", "key_from_environment_or_flag")
q.Add("another_thing", "foo & bar")
req.URL.RawQuery = q.Encode()
fmt.Println(req.URL.String())
// Output:
// http://api.themoviedb.org/3/tv/popularanother_thing=foo+%26+bar&api_key=key_from_environment_or_flag
}
For Typescript 2.x.x
you should do it in a following way(using type guard):
tl;dr
function isDefined<T>(value: T | undefined | null): value is T {
return <T>value !== undefined && <T>value !== null;
}
Why?
In this way isDefined()
will respect variable's type and the following code would know take this check in account.
Example 1 - basic check:
function getFoo(foo: string): void {
//
}
function getBar(bar: string| undefined) {
getFoo(bar); //ERROR: "bar" can be undefined
if (isDefined(bar)) {
getFoo(bar); // Ok now, typescript knows that "bar' is defined
}
}
Example 2 - types respect:
function getFoo(foo: string): void {
//
}
function getBar(bar: number | undefined) {
getFoo(bar); // ERROR: "number | undefined" is not assignable to "string"
if (isDefined(bar)) {
getFoo(bar); // ERROR: "number" is not assignable to "string", but it's ok - we know it's number
}
}
You can use jQuery to achieve this using simple $.get
method. .html
work like innerHtml and replace the content of your div.
$.get("/YourUrl", {},
function (returnedHtml) {
$("#here").html(returnedHtml);
});
And call this using javascript setInterval
method.
Check out this gist. It has snippets for how to get the sharing count for the following services:
I figured it out. The below works in converting it to a 24 hr date format.
select date_parse('7/22/2016 6:05:04 PM','%m/%d/%Y %h:%i:%s %p')
The syntax of the query is as follows:
Alter table <table name> rename column <column name> to <new column name>;
Example:
Alter table employee rename column eName to empName;
To rename a column name without space to a column name with space:
Alter table employee rename column empName to "Emp Name";
To rename a column with space to a column name without space:
Alter table employee rename column "emp name" to empName;
If the application is running in the foreground, iOS won't show a notification banner/alert. That's by design. You have to write some code to deal with the situation of your app receiving a notification while it is in the foreground. You should show the notification in the most appropriate way (for example, adding a badge number to a UITabBar
icon, simulating a Notification Center banner, etc.).
#include <unistd.h>
#include <termios.h>
char getch(void)
{
char buf = 0;
struct termios old = {0};
fflush(stdout);
if(tcgetattr(0, &old) < 0)
perror("tcsetattr()");
old.c_lflag &= ~ICANON;
old.c_lflag &= ~ECHO;
old.c_cc[VMIN] = 1;
old.c_cc[VTIME] = 0;
if(tcsetattr(0, TCSANOW, &old) < 0)
perror("tcsetattr ICANON");
if(read(0, &buf, 1) < 0)
perror("read()");
old.c_lflag |= ICANON;
old.c_lflag |= ECHO;
if(tcsetattr(0, TCSADRAIN, &old) < 0)
perror("tcsetattr ~ICANON");
printf("%c\n", buf);
return buf;
}
Remove the last printf
if you don't want the character to be displayed.
Some answers are correct but convoluted.
I am answering this again, 4 years later, because I still run into overly complex code to solve exactly this question. There IS an elegant solution.
First of all, do not pass in a string as the first parameter when calling setTimeout because it effectively invokes a call to the slow "eval" function.
So how do we pass in a parameter to a timeout function? By using closure:
settopic=function(topicid){
setTimeout(function(){
//thanks to closure, topicid is visible here
postinsql(topicid);
},4000);
}
...
if (xhr.readyState==4){
settopic(xhr.responseText);
}
Some have suggested using anonymous function when calling the timeout function:
if (xhr.readyState==4){
setTimeout(function(){
settopic(xhr.responseText);
},4000);
}
The syntax works out. But by the time settopic is called, i.e. 4 seconds later, the XHR object may not be the same. Therefore it's important to pre-bind the variables.
Because the original question was never answered, and I had to run into this same problem, the solution for the MD5 problem is that S3 doesn't want the Hex encoded MD5 string we normally think about.
Instead, I had to do this.
// content is a passed in InputStream
byte[] resultByte = DigestUtils.md5(content);
String streamMD5 = new String(Base64.encodeBase64(resultByte));
metaData.setContentMD5(streamMD5);
Essentially what they want for the MD5 value is the Base64 encoded raw MD5 byte-array, not the Hex string. When I switched to this it started working great for me.
Add .*
to s
in your first line.
Try:
DELETE s.* FROM spawnlist s
INNER JOIN npc n ON s.npc_templateid = n.idTemplate
WHERE (n.type = "monster");
By using System.Windows.Forms.Timer
class you can achieve what you need.
System.Windows.Forms.Timer t = new System.Windows.Forms.Timer();
t.Interval = 15000; // specify interval time as you want
t.Tick += new EventHandler(timer_Tick);
t.Start();
void timer_Tick(object sender, EventArgs e)
{
//Call method
}
By using stop() method you can stop timer.
t.Stop();
Test this:
DECLARE @result NVARCHAR(MAX)
SELECT @result = STUFF(
( SELECT ',' + CONVERT(NVARCHAR(20), StudentId)
FROM Student
WHERE condition = abc
FOR xml path('')
)
, 1
, 1
, '')
I usually start with something like:
set lines 256
set trimout on
set tab off
Have a look at help set
if you have the help information installed. And then select name,address
rather than select *
if you really only want those two columns.
For a string specifically, the quickest way is to use the StringContent constructor
response.Content = new StringContent("Your response text");
There are a number of additional HttpContent class descendants for other common scenarios.
Impossible. A file descriptor may have multiple names in the filesystem, or it may have no name at all.
Edit: Assuming you are talking about a plain old POSIX system, without any OS-specific APIs, since you didn't specify an OS.