the ON DUPLICATE KEY UPDATE clause is the best solution because: REPLACE does a DELETE followed by an INSERT so for an ever so slight period the record is removed creating the ever so slight possibility that a query could come back having skipped that if the page was viewed during the REPLACE query.
I prefer INSERT ... ON DUPLICATE UPDATE ... for that reason.
jmoz's solution is the best: though I prefer the SET syntax to the parentheses
INSERT INTO cache
SET key = 'key', generation = 'generation'
ON DUPLICATE KEY
UPDATE key = 'key', generation = (generation + 1)
;
Similar error with Glassfish 4.0 and several JDK installed:
SEVERE: GlassFish requires JDK 7, you are using JDK version 6.
There is no AS_JAVA reference in "C:\glassfish\config\asenv.bat" by default. After adding manually
set AS_JAVA=C:\Program Files\Java\jdk1.7.0_25
it works.
You can do this after you validate your data.
if myform.is_valid():
data = myform.cleaned_data
field = data['field']
Also, read the django docs. They are perfect.
Using pstools - in particular psservice and "query" - for example:
psservice query "serviceName"
I improved upon psycho brm's filterByData extension to jQuery.
Where the former extension searched on a key-value pair, with this extension you can additionally search for the presence of a data attribute, irrespective of its value.
(function ($) {
$.fn.filterByData = function (prop, val) {
var $self = this;
if (typeof val === 'undefined') {
return $self.filter(
function () { return typeof $(this).data(prop) !== 'undefined'; }
);
}
return $self.filter(
function () { return $(this).data(prop) == val; }
);
};
})(window.jQuery);
Usage:
$('<b>').data('x', 1).filterByData('x', 1).length // output: 1
$('<b>').data('x', 1).filterByData('x').length // output: 1
// test data_x000D_
function extractData() {_x000D_
log('data-prop=val ...... ' + $('div').filterByData('prop', 'val').length);_x000D_
log('data-prop .......... ' + $('div').filterByData('prop').length);_x000D_
log('data-random ........ ' + $('div').filterByData('random').length);_x000D_
log('data-test .......... ' + $('div').filterByData('test').length);_x000D_
log('data-test=anyval ... ' + $('div').filterByData('test', 'anyval').length);_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
$('#b5').data('test', 'anyval');_x000D_
});_x000D_
_x000D_
// the actual extension_x000D_
(function($) {_x000D_
_x000D_
$.fn.filterByData = function(prop, val) {_x000D_
var $self = this;_x000D_
if (typeof val === 'undefined') {_x000D_
return $self.filter(_x000D_
_x000D_
function() {_x000D_
return typeof $(this).data(prop) !== 'undefined';_x000D_
});_x000D_
}_x000D_
return $self.filter(_x000D_
_x000D_
function() {_x000D_
return $(this).data(prop) == val;_x000D_
});_x000D_
};_x000D_
_x000D_
})(window.jQuery);_x000D_
_x000D_
_x000D_
//just to quickly log_x000D_
function log(txt) {_x000D_
if (window.console && console.log) {_x000D_
console.log(txt);_x000D_
//} else {_x000D_
// alert('You need a console to check the results');_x000D_
}_x000D_
$("#result").append(txt + "<br />");_x000D_
}
_x000D_
#bPratik {_x000D_
font-family: monospace;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="bPratik">_x000D_
<h2>Setup</h2>_x000D_
<div id="b1" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
<div id="b2" data-prop="val">Data added inline :: data-prop="val"</div>_x000D_
<div id="b3" data-prop="diffval">Data added inline :: data-prop="diffval"</div>_x000D_
<div id="b4" data-test="val">Data added inline :: data-test="val"</div>_x000D_
<div id="b5">Data will be added via jQuery</div>_x000D_
<h2>Output</h2>_x000D_
<div id="result"></div>_x000D_
_x000D_
<hr />_x000D_
<button onclick="extractData()">Reveal</button>_x000D_
</div>
_x000D_
Or the fiddle: http://jsfiddle.net/PTqmE/46/
Try to convertValue by Jackson
ObjectMapper mapper = new ObjectMapper()
Integer a = 1;
Long b = mapper.convertValue(a, Long.class)
I've been working on improving the excellent solution from speedplane, and came up with this. It manages the height, including setting the margin such that the text should be centered correctly vertically.
This uses the same function to get the width, as it seems to work the best, but it uses a different function to get the height, as the height isn't provided anywhere. There are some corrections that need to be made, but I figured out a way to do that, while looking pleasing to the eye.
import android.content.Context;
import android.graphics.Paint;
import android.graphics.Rect;
import android.util.AttributeSet;
import android.util.TypedValue;
import android.widget.TextView;
public class FontFitTextView extends TextView {
public FontFitTextView(Context context) {
super(context);
initialize();
}
public FontFitTextView(Context context, AttributeSet attrs) {
super(context, attrs);
initialize();
}
private void initialize() {
mTestPaint = new Paint();
mTestPaint.set(this.getPaint());
//max size defaults to the initially specified text size unless it is too small
}
/* Re size the font so the specified text fits in the text box
* assuming the text box is the specified width.
*/
private void refitText(String text, int textWidth,int textHeight)
{
if (textWidth <= 0)
return;
int targetWidth = textWidth - this.getPaddingLeft() - this.getPaddingRight();
int targetHeight = textHeight - this.getPaddingTop() - this.getPaddingBottom();
float hi = Math.min(targetHeight,100);
float lo = 2;
final float threshold = 0.5f; // How close we have to be
Rect bounds = new Rect();
mTestPaint.set(this.getPaint());
while((hi - lo) > threshold) {
float size = (hi+lo)/2;
mTestPaint.setTextSize(size);
mTestPaint.getTextBounds(text, 0, text.length(), bounds);
if((mTestPaint.measureText(text)) >= targetWidth || (1+(2*(size+(float)bounds.top)-bounds.bottom)) >=targetHeight)
hi = size; // too big
else
lo = size; // too small
}
// Use lo so that we undershoot rather than overshoot
this.setTextSize(TypedValue.COMPLEX_UNIT_PX,(float) lo);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)
{
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int parentWidth = MeasureSpec.getSize(widthMeasureSpec);
int parentHeight = MeasureSpec.getSize(heightMeasureSpec);
int height = getMeasuredHeight();
refitText(this.getText().toString(), parentWidth,height);
this.setMeasuredDimension(parentWidth, height);
}
@Override
protected void onTextChanged(final CharSequence text, final int start, final int before, final int after) {
refitText(text.toString(), this.getWidth(),this.getHeight());
}
@Override
protected void onSizeChanged (int w, int h, int oldw, int oldh) {
if (w != oldw) {
refitText(this.getText().toString(), w,h);
}
}
//Attributes
private Paint mTestPaint;
}
See the docs:
Since PHP 5.3, it is possible to leave out the middle part of the ternary operator. Expression
expr1 ?: expr3
returnsexpr1
ifexpr1
evaluates toTRUE
, andexpr3
otherwise.
When writing CMake scripts there is a lot you need to know about the syntax and how to use variables in CMake.
Strings using set()
:
set(MyString "Some Text")
set(MyStringWithVar "Some other Text: ${MyString}")
set(MyStringWithQuot "Some quote: \"${MyStringWithVar}\"")
Or with string()
:
string(APPEND MyStringWithContent " ${MyString}")
Lists using set()
:
set(MyList "a" "b" "c")
set(MyList ${MyList} "d")
Or better with list()
:
list(APPEND MyList "a" "b" "c")
list(APPEND MyList "d")
Lists of File Names:
set(MySourcesList "File.name" "File with Space.name")
list(APPEND MySourcesList "File.name" "File with Space.name")
add_excutable(MyExeTarget ${MySourcesList})
set()
Commandstring()
Commandlist()
CommandFirst there are the "Normal Variables" and things you need to know about their scope:
CMakeLists.txt
they are set in and everything called from there (add_subdirectory()
, include()
, macro()
and function()
).add_subdirectory()
and function()
commands are special, because they open-up their own scope.
set(...)
there are only visible there and they make a copy of all normal variables of the scope level they are called from (called parent scope).set(... PARENT_SCOPE)
function(xyz _resultVar)
is setting set(${_resultVar} 1 PARENT_SCOPE)
include()
or macro()
scripts will modify variables directly in the scope of where they are called from. Second there is the "Global Variables Cache". Things you need to know about the Cache:
CMakeCache.txt
file in your binary output directory.The values in the Cache can be modified in CMake's GUI application before they are generated. Therefore they - in comparison to normal variables - have a type
and a docstring
. I normally don't use the GUI so I use set(... CACHE INTERNAL "")
to set my global and persistant values.
Please note that the INTERNAL
cache variable type does imply FORCE
In a CMake script you can only change existing Cache entries if you use the set(... CACHE ... FORCE)
syntax. This behavior is made use of e.g. by CMake itself, because it normally does not force Cache entries itself and therefore you can pre-define it with another value.
cmake -D var:type=value
, just cmake -D var=value
or with cmake -C CMakeInitialCache.cmake
.unset(... CACHE)
.The Cache is global and you can set them virtually anywhere in your CMake scripts. But I would recommend you think twice about where to use Cache variables (they are global and they are persistant). I normally prefer the set_property(GLOBAL PROPERTY ...)
and set_property(GLOBAL APPEND PROPERTY ...)
syntax to define my own non-persistant global variables.
To avoid pitfalls you should know the following about variables:
find_...
commands - if successful - do write their results as cached variables "so that no call will search again"set(MyVar a b c)
is "a;b;c"
and set(MyVar "a b c")
is "a b c"
list()
command for handling listsfunctions()
instead of macros()
because you don't want your local variables to show up in the parent scope. project()
and enable_language()
calls. So it could get important to set some variables before those commands are used.Sometimes only debugging variables helps. The following may help you:
printf
debugging style by using the message()
command. There also some ready to use modules shipped with CMake itself: CMakePrintHelpers.cmake, CMakePrintSystemInformation.cmakeCMakeCache.txt
file in your binary output directory. This file is even generated if the actual generation of your make environment fails.cmake --trace ...
to see the CMake's complete parsing process. That's sort of the last reserve, because it generates a lot of output.$ENV{...}
and write set(ENV{...} ...)
environment variables$<...>
are only evaluated when CMake's generator writes the make environment (it comparison to normal variables that are replaced "in-place" by the parser)${${...}}
you can give variable names in a variable and reference its content.if()
command)
if(MyVariable)
you can directly check a variable for true/false (no need here for the enclosing ${...}
)1
, ON
, YES
, TRUE
, Y
, or a non-zero number. 0
, OFF
, NO
, FALSE
, N
, IGNORE
, NOTFOUND
, the empty string, or ends in the suffix -NOTFOUND
.if(MSVC)
, but it can be confusing for someone who does not know this syntax shortcut.set(CMAKE_${lang}_COMPILER ...)
if()
commands. Here is an example where CMAKE_CXX_COMPILER_ID
is "MSVC"
and MSVC
is "1"
:
if("${CMAKE_CXX_COMPILER_ID}" STREQUAL "MSVC")
is true, because it evaluates to if("1" STREQUAL "1")
if(CMAKE_CXX_COMPILER_ID STREQUAL "MSVC")
is false, because it evaluates to if("MSVC" STREQUAL "1")
if(MSVC)
cmake_policy(SET CMP0054 NEW)
to "only interpret if()
arguments as variables or keywords when unquoted."option()
command
ON
or OFF
and they allow some special handling like e.g. dependenciesoption
with the set
command. The value given to option
is really only the "initial value" (transferred once to the cache during the first configuration step) and is afterwards meant to be changed by the user through CMake's GUI.You will need to use any javascript html calendar widget.
try this calendar view widget, just copy-paste some code shown in example there and thats it what you want.
Here is the link to Jquery Mobile date box - JQM datebox
You could also do this by adding (object) on left of variable to create a new object.
<?php
$a = Array
( 'status' => " text" );
var_dump($a);
$b = (object)$a;
var_dump($b);
var_dump($b->status);
Add
[config]="{backdrop: 'static'}"
to the model code.
I'm trying to sort of get my head around what's going on over there. Is there anything IN your "example" folder? Git doesn't track empty folders.
If you branched and switched to your new branch then made a new folder and left it empty, and then did "git commit -a", you wouldn't get that new folder in the commit.
Which means it's untracked, which means checking out a different branch wouldn't remove it.
The same situation was with the previous versions. It's annoing that new versions com.google.android.gms libraries are always releasing before plugin, and it's impossible to use new version because is incompatible with old plugin. I don't know if plugin is now required (google docs sucks). I remember times when it wasn't. The only way is wait for new plugin version, or you can try to remove plugin dependencies, but as I said I'am not sure if gcm will work without it. What I know the main feature of 9.2.0 version is new Awareness API https://inthecheesefactory.com/blog/google-awareness-api-in-action/en, if you didn't need it, you can use 9.0.0 version without any trouble.
Instead of editing the bringup service, add a post-start delay to the service which it depends on. Edit cassandra.service
like so:
ExecStartPost=/bin/sleep 30
This way the added sleep shouldn't slow down restarts of starting services that depend on it (though does slow down its own start, maybe that's desirable?).
Maybe just another thing about LEA instruction. You can also use LEA for fast multiplying registers by 3, 5 or 9.
LEA EAX, [EAX * 2 + EAX] ;EAX = EAX * 3
LEA EAX, [EAX * 4 + EAX] ;EAX = EAX * 5
LEA EAX, [EAX * 8 + EAX] ;EAX = EAX * 9
As far as I am concerned, I prefer to externalize the error messages in a properties files. This will be really helpful in case of internationalization of your application (one properties file per language). It is also easier to modify an error message, and it won't need any re-compilation of the Java sources.
On my projects, generally I have an interface that contains errors codes (String or integer, it doesn't care much), which contains the key in the properties files for this error:
public interface ErrorCodes {
String DATABASE_ERROR = "DATABASE_ERROR";
String DUPLICATE_USER = "DUPLICATE_USER";
...
}
in the properties file:
DATABASE_ERROR=An error occurred in the database.
DUPLICATE_USER=The user already exists.
...
Another problem with your solution is the maintenability: you have only 2 errors, and already 12 lines of code. So imagine your Enumeration file when you will have hundreds of errors to manage!
Assuming you're the administrator of the machine, Ubuntu has granted you the right to sudo to run any command as any user.
Also assuming you did not restrict the rights in the pg_hba.conf
file (in the /etc/postgresql/9.1/main
directory), it should contain this line as the first rule:
# Database administrative login by Unix domain socket
local all postgres peer
(About the file location: 9.1
is the major postgres version and main
the name of your "cluster". It will differ if using a newer version of postgres or non-default names. Use the pg_lsclusters
command to obtain this information for your version/system).
Anyway, if the pg_hba.conf
file does not have that line, edit the file, add it, and reload the service with sudo service postgresql reload
.
Then you should be able to log in with psql
as the postgres superuser with this shell command:
sudo -u postgres psql
Once inside psql, issue the SQL command:
ALTER USER postgres PASSWORD 'newpassword';
In this command, postgres
is the name of a superuser. If the user whose password is forgotten was ritesh
, the command would be:
ALTER USER ritesh PASSWORD 'newpassword';
References: PostgreSQL 9.1.13 Documentation, Chapter 19. Client Authentication
Keep in mind that you need to type postgres with a single S at the end
If leaving the password in clear text in the history of commands or the server log is a problem, psql provides an interactive meta-command to avoid that, as an alternative to ALTER USER ... PASSWORD
:
\password username
It asks for the password with a double blind input, then hashes it according to the password_encryption
setting and issue the ALTER USER
command to the server with the hashed version of the password, instead of the clear text version.
You may try to put the right database name in connection url in the configuration file. As I had the same error while run the POJO class file and it has been solved by this.
This one also works
Remove the "php.executablePath" line from the VS code settings.
Then add the xampp php path to the System variables
After that restart the Visual Studio Code
The straightforward way to do this correctly and securely is to use Open3.capture2()
, Open3.capture2e()
, or Open3.capture3()
.
Using ruby's backticks and its %x
alias are NOT SECURE UNDER ANY CIRCUMSTANCES if used with untrusted data. It is DANGEROUS, plain and simple:
untrusted = "; date; echo"
out = `echo #{untrusted}` # BAD
untrusted = '"; date; echo"'
out = `echo "#{untrusted}"` # BAD
untrusted = "'; date; echo'"
out = `echo '#{untrusted}'` # BAD
The system
function, in contrast, escapes arguments properly if used correctly:
ret = system "echo #{untrusted}" # BAD
ret = system 'echo', untrusted # good
Trouble is, it returns the exit code instead of the output, and capturing the latter is convoluted and messy.
The best answer in this thread so far mentions Open3, but not the functions that are best suited for the task. Open3.capture2
, capture2e
and capture3
work like system
, but returns two or three arguments:
out, err, st = Open3.capture3("echo #{untrusted}") # BAD
out, err, st = Open3.capture3('echo', untrusted) # good
out_err, st = Open3.capture2e('echo', untrusted) # good
out, st = Open3.capture2('echo', untrusted) # good
p st.exitstatus
Another mentions IO.popen()
. The syntax can be clumsy in the sense that it wants an array as input, but it works too:
out = IO.popen(['echo', untrusted]).read # good
For convenience, you can wrap Open3.capture3()
in a function, e.g.:
#
# Returns stdout on success, false on failure, nil on error
#
def syscall(*cmd)
begin
stdout, stderr, status = Open3.capture3(*cmd)
status.success? && stdout.slice!(0..-(1 + $/.size)) # strip trailing eol
rescue
end
end
Example:
p system('foo')
p syscall('foo')
p system('which', 'foo')
p syscall('which', 'foo')
p system('which', 'which')
p syscall('which', 'which')
Yields the following:
nil
nil
false
false
/usr/bin/which <— stdout from system('which', 'which')
true <- p system('which', 'which')
"/usr/bin/which" <- p syscall('which', 'which')
A 1 to 1 relationship is very much possible. Even if the relationship diagram doesn't show the 1 to 1 relationship explicitly. If you implement it as below, it will function as a one to one relationship.
I will use a basic example to explain the concept where a single person can only have a single passport. This example works perfectly in MS Access. For the SQL Server version follow this link.
Remember that in MS Access, SQL scripts can only be run one at a time and not as displayed here in sequence.
CREATE TABLE Person
(
Pk_Person_Id INT PRIMARY KEY,
Name VARCHAR(255),
EmailId VARCHAR(255),
);
CREATE TABLE PassportDetails
(
Pk_Passport_Id INT PRIMARY KEY,
Passport_Number VARCHAR(255),
Fk_Person_Id INT NOT NULL UNIQUE,
FOREIGN KEY(Fk_Person_Id) REFERENCES Person(Pk_Person_Id)
);
You need to manually filter input to constructors and setters. Well... you could use reflection but I wouldn't advise it. Part of the job of constructors and setters is to validate input. That can include things like:
public void setPrice(double price) {
if (price < 0.0d) {
throw new IllegalArgumentException("price cannot be negative " + price);
}
this.price = price;
}
and
public void setName(String name) {
if (name == null) {
throw new NullPointerException("name cannot be null");
}
this.name = name;
}
You could use wrapper functions for the actual check and throwing the exception.
As user2357112 mentioned in the comments, you cannot use chained comparisons here. For elementwise comparison you need to use &
. That also requires using parentheses so that &
wouldn't take precedence.
It would go something like this:
mask = ((50 < df['heart rate']) & (101 > df['heart rate']) & (140 < df['systolic...
In order to avoid that, you can build series for lower and upper limits:
low_limit = pd.Series([90, 50, 95, 11, 140, 35], index=df.columns)
high_limit = pd.Series([160, 101, 100, 19, 160, 39], index=df.columns)
Now you can slice it as follows:
mask = ((df < high_limit) & (df > low_limit)).all(axis=1)
df[mask]
Out:
dyastolic blood pressure heart rate pulse oximetry respiratory rate \
17 136 62 97 15
69 110 85 96 18
72 105 85 97 16
161 126 57 99 16
286 127 84 99 12
435 92 67 96 13
499 110 66 97 15
systolic blood pressure temperature
17 141 37
69 155 38
72 154 36
161 153 36
286 156 37
435 155 36
499 149 36
And for assignment you can use np.where:
df['class'] = np.where(mask, 'excellent', 'critical')
I agree with many here, but I also think it depends.
Recently I did this code:
private void animate(FlowLayoutPanel element, int start, int end)
{
bool asc = end > start;
element.Show();
while (start != end) {
start += asc ? 1 : -1;
element.Height = start;
Thread.Sleep(1);
}
if (!asc)
{
element.Hide();
}
element.Focus();
}
It was a simple animate-function, and I used Thread.Sleep
on it.
My conclusion, if it does the job, use it.
$[] operator selects all nested array ..You can update all array items with '$[]'
.update({"events.profile":10},{$set:{"events.$[].handled":0}},false,true)
I have resolved this problem in my way. Try connection string in this way:
<add name="MFCConnectionString" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\MFC.mdf;Initial Catalog=MFC;Integrated Security=false;User ID=sa;Password=123"
providerName="System.Data.SqlClient" />
remember to set default db from master to MFC (in your case, aspnet-test-2012615153521).
tl;dr What to do in modern (2018) times? Assume tel:
is supported, use it and forget about anything else.
The tel:
URI scheme RFC5431 (as well as sms:
but also feed:
, maps:
, youtube:
and others) is handled by protocol handlers (as mailto:
and http:
are).
They're unrelated to HTML5 specification (it has been out there from 90s and documented first time back in 2k with RFC2806) then you can't check for their support using tools as modernizr. A protocol handler may be installed by an application (for example Skype installs a callto:
protocol handler with same meaning and behaviour of tel:
but it's not a standard), natively supported by browser or installed (with some limitations) by website itself.
What HTML5 added is support for installing custom web based protocol handlers (with registerProtocolHandler()
and related functions) simplifying also the check for their support through isProtocolHandlerRegistered()
function.
There is some easy ways to determine if there is an handler or not:" How to detect browser's protocol handlers?).
In general what I suggest is:
tel:
is supported (yes, it's not true for very old devices but IMO you can ignore them).tel:
isn't supported then change links to use callto:
and repeat check desctibed in 3.tel:
and callto:
aren't supported (or - in a desktop browser - you can't detect their support) then simply remove that link replacing URL in href
with javascript:void(0)
and (if number isn't repeated in text span) putting, telephone number in title
. Here HTML5 microdata won't help users (just search engines). Note that newer versions of Skype handle both callto:
and tel:
.Please note that (at least on latest Windows versions) there is always a - fake - registered protocol handler called App Picker (that annoying window that let you choose with which application you want to open an unknown file). This may vanish your tests so if you don't want to handle Windows environment as a special case you can simplify this process as:
tel:
is supported.tel:
with callto:
.tel:
or leave it as is (assuming there are good chances Skype is installed).You shouldn't use ${varName}
when you're outside of strings, you should just use varName
. Inside strings you use it like this; echo "this is a string ${someVariable}";
. Infact you can place an general java expression inside of ${...}
; echo "this is a string ${func(arg1, arg2)}
.
If you're fine with using ES6. Arrays now have the findIndex function. Which means you can do something like this:
const index = Data.findIndex(item => item.name === 'John');
You could use bc by the -l
option (the L letter)
RESULT=$(echo "$IMG_WIDTH/$IMG2_WIDTH" | bc -l)
You can get the all record of the date '2016-07-14' by using it
whereDate('date','=','2016-07-14')
Or use the another code for dynamic date
whereDate('date',$date)
Alternate approach : without installation of Redistributable package.
Check out in some github for the relevant dll, some people upload the reference dll for their application dependency.
you can download and use them in your project , I have used and run them successfully.
example : https://github.com/Emotiv/community-sdk/find/master
I know this is an old question, a few of these methods didn't work for me so for anyone looking in the future or having my troubles this worked for me
I overrode onPause
and called finish()
inside that method.
Copied from MSDN:
At compile time, verbatim strings are converted to ordinary strings with all the same escape sequences. Therefore, if you view a verbatim string in the debugger watch window, you will see the escape characters that were added by the compiler, not the verbatim version from your source code. For example, the verbatim string
@"C:\files.txt"
will appear in the watch window as"C:\\files.txt"
.
$(".input1").on('keyup', function (e) {
if (e.key === 'Enter' || e.keyCode === 13) {
// Do something
}
});
// e.key is the modern way of detecting keys
// e.keyCode is deprecated (left here for for legacy browsers support)
// keyup is not compatible with Jquery select(), Keydown is.
$("#idofBtn").click(function(){
$('#idofdropdown').empty(); //remove all child nodes
var newOption = $('<option value="1">test</option>');
$('#idofdropdown').append(newOption);
$('#idofdropdown').trigger("chosen:updated");
});
Try with an API lvl 28 emulator (Android 9). I was trying with api lvl 29 and kept getting errors.
The difference between them is that they use different pins. Seriously, that's it. The reason they both exist is that RTS/CTS wasn't supposed to ever be a flow control mechanism, originally; it was for half-duplex modems to coordinate who was sending and who was receiving. RTS and CTS got misused for flow control so often that it became standard.
The following query will help to find out free space of tablespaces in MB:
select tablespace_name , sum(bytes)/1024/1024 from dba_free_space group by tablespacE_name order by 1;
Since everyone answering this question has problems due to the 500 video limit here's an alternate solution using youtube_dl in Python 3. Also, no API key is needed.
sudo pip3 install youtube-dl
Example (warning -- takes tens of minutes):
import youtube_dl, pickle
# UCVTyTA7-g9nopHeHbeuvpRA is the channel id (1517+ videos)
PLAYLIST_ID = 'UUVTyTA7-g9nopHeHbeuvpRA' # Late Night with Seth Meyers
with youtube_dl.YoutubeDL({'ignoreerrors': True}) as ydl:
playd = ydl.extract_info(PLAYLIST_ID, download=False)
with open('playlist.pickle', 'wb') as f:
pickle.dump(playd, f, pickle.HIGHEST_PROTOCOL)
vids = [vid for vid in playd['entries'] if 'A Closer Look' in vid['title']]
print(sum('Trump' in vid['title'] for vid in vids), '/', len(vids))
If you like me work from commandline the quick answer is executing
export ANT_OPTS=-Dbuild.sysclasspath=ignore
And then run your ant script again.
1) Direct Answer: Try this:
sudo updatedb
locate OpenCVConfig.cmake
For me, I get:
/home/pkarasev3/source/opencv/build/OpenCVConfig.cmake
To see the version, you can try:
cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake
giving
....
SET(OpenCV_VERSION 2.3.1)
....
2) Better Answer:
"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).
Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.
I tried using a CLR function and it was more than twice as fast as BCP. Here's my code.
Original Method:
SET @bcpCommand = 'bcp "SELECT blobcolumn FROM blobtable WHERE ID = ' + CAST(@FileID AS VARCHAR(20)) + '" queryout "' + @FileName + '" -T -c'
EXEC master..xp_cmdshell @bcpCommand
CLR Method:
declare @file varbinary(max) = (select blobcolumn from blobtable WHERE ID = @fileid)
declare @filepath nvarchar(4000) = N'c:\temp\' + @FileName
SELECT Master.dbo.WriteToFile(@file, @filepath, 0)
C# Code for the CLR function
using System;
using System.Data;
using System.Data.SqlTypes;
using System.IO;
using Microsoft.SqlServer.Server;
namespace BlobExport
{
public class Functions
{
[SqlFunction]
public static SqlString WriteToFile(SqlBytes binary, SqlString path, SqlBoolean append)
{
try
{
if (!binary.IsNull && !path.IsNull && !append.IsNull)
{
var dir = Path.GetDirectoryName(path.Value);
if (!Directory.Exists(dir))
Directory.CreateDirectory(dir);
using (var fs = new FileStream(path.Value, append ? FileMode.Append : FileMode.OpenOrCreate))
{
byte[] byteArr = binary.Value;
for (int i = 0; i < byteArr.Length; i++)
{
fs.WriteByte(byteArr[i]);
};
}
return "SUCCESS";
}
else
"NULL INPUT";
}
catch (Exception ex)
{
return ex.Message;
}
}
}
}
Apart from other answer There are calculator provided by Youtube to check your usage. It is good to identify your usage. https://developers.google.com/youtube/v3/determine_quota_cost
Use Integer.toString(tmpInt)
instead.
You can achieve this using a cursor but the performance is much slower than whileloop.. Here's the code:
set nocount on
declare cur cursor local fast_forward for
(select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;
fetch from cur into @fullpath
while @@FETCH_STATUS = 0
begin
exec xp_fileexist @fullpath, @isExists out
if @isExists = 1
print @fullpath + char(9) + char(9) + 'file exists'
else
print @fullpath + char(9) + char(9) + 'file does not exists'
fetch from cur into @fullpath
end
close cur
deallocate cur
or you can put it in a tempTable if you want to integrate it in your frontend..
create proc GetFileStatus as
begin
set nocount on
create table #tempFileStatus(FilePath varchar(300),FileStatus varchar(30))
declare cur cursor local fast_forward for
(select filepath from Directory)
open cur;
declare @fullpath varchar(250);
declare @isExists int;
fetch from cur into @fullpath
while @@FETCH_STATUS = 0
begin
exec xp_fileexist @fullpath, @isExists out
if @isExists = 1
insert into #tempFileStatus values(@fullpath,'File exist')
else
insert into #tempFileStatus values(@fullpath,'File does not exists')
fetch from cur into @fullpath
end
close cur
deallocate cur
select * from #tempFileStatus
drop table #tempFileStatus
end
then call it using:
exec GetFileStatus
Converting my old comment for better visibility: For a "better way to do this" without map
entirely, if your inputs are known to be ASCII ordinals, it's generally much faster to convert to bytes
and decode, a la bytes(list_of_ordinals).decode('ascii')
. That gets you a str
of the values, but if you need a list
for mutability or the like, you can just convert it (and it's still faster). For example, in ipython
microbenchmarks converting 45 inputs:
>>> %%timeit -r5 ordinals = list(range(45))
... list(map(chr, ordinals))
...
3.91 µs ± 60.2 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)
>>> %%timeit -r5 ordinals = list(range(45))
... [*map(chr, ordinals)]
...
3.84 µs ± 219 ns per loop (mean ± std. dev. of 5 runs, 100000 loops each)
>>> %%timeit -r5 ordinals = list(range(45))
... [*bytes(ordinals).decode('ascii')]
...
1.43 µs ± 49.7 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)
>>> %%timeit -r5 ordinals = list(range(45))
... bytes(ordinals).decode('ascii')
...
781 ns ± 15.9 ns per loop (mean ± std. dev. of 5 runs, 1000000 loops each)
If you leave it as a str
, it takes ~20% of the time of the fastest map
solutions; even converting back to list it's still less than 40% of the fastest map
solution. Bulk convert via bytes
and bytes.decode
then bulk converting back to list
saves a lot of work, but as noted, only works if all your inputs are ASCII ordinals (or ordinals in some one byte per character locale specific encoding, e.g. latin-1
).
Using the ES6 findIndex
method, without lodash or any other libraries, you can write:
function deepIndexOf(arr, obj) {
return arr.findIndex(function (cur) {
return Object.keys(obj).every(function (key) {
return obj[key] === cur[key];
});
});
}
This will compare the immediate properties of the object, but not recurse into the properties.
If your implementation doesn't provide findIndex
yet (most don't), you can add a light polyfill that supports this search:
function deepIndexOf(arr, obj) {
function findIndex = Array.prototype.findIndex || function (pred) {
for (let i = 0; i < this.length; ++i) {
if (pred.call(this, this[i], i)) {
return i;
}
}
return -1;
}
return findIndex.call(arr, function (cur) {
return Object.keys(obj).every(function (key) {
return obj[key] === cur[key];
});
});
}
(from my answer on this dupe)
Try to use the DataColumn.SetOrdinal method. For example:
dataTable.Columns["Qty"].SetOrdinal(0);
dataTable.Columns["Unit"].SetOrdinal(1);
UPDATE: This answer received much more attention than I expected. To avoid confusion and make it easier to use I decided to create an extension method for column ordering in DataTable:
Extension method:
public static class DataTableExtensions
{
public static void SetColumnsOrder(this DataTable table, params String[] columnNames)
{
int columnIndex = 0;
foreach(var columnName in columnNames)
{
table.Columns[columnName].SetOrdinal(columnIndex);
columnIndex++;
}
}
}
Usage:
table.SetColumnsOrder("Qty", "Unit", "Id");
or
table.SetColumnsOrder(new string[]{"Qty", "Unit", "Id"});
This is all nicely lined up including the field label. Lining up the field label was the tricky part.
<div class="form-group">
<label class="control-label col-md-5">Create a</label>
<div class="col-md-7">
<label class="radio-inline control-label">
<input checked="checked" id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="2"> Task
</label>
<label class="radio-inline control-label">
<input id="TaskLog_TaskTypeId" name="TaskLog.TaskTypeId" type="radio" value="1"> Note
</label>
</div>
</div>
<div class="form-group">
@Html.Label("Create a", htmlAttributes: new { @class = "control-label col-md-5" })
<div class="col-md-7">
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.TaskTaskTypeId) Task
</label>
<label class="radio-inline control-label">
@Html.RadioButtonFor(model => model.TaskTypeId, Model.NoteTaskTypeId) Note
</label>
</div>
</div>
This is probably not the main reason why the create_all()
method call doesn't work for people, but for me, the cobbled together instructions from various tutorials have it such that I was creating my db in a request context, meaning I have something like:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
def get_db():
if 'db' not in g:
g.db = SQLAlchemy(current_app)
return g.db
I also have a separate cli command that also does the create_all:
# tasks/db.py
from lib.db import get_db
@current_app.cli.command('init-db')
def init_db():
db = get_db()
db.create_all()
I also am using a application factory.
When the cli command is run, a new app context is used, which means a new db is used. Furthermore, in this world, an import model in the init_db method does not do anything, because it may be that your model file was already loaded(and associated with a separate db).
The fix that I came around to was to make sure that the db was a single global reference:
# lib/db.py
from flask import g, current_app
from flask_sqlalchemy import SQLAlchemy
db = None
def get_db():
global db
if not db:
db = SQLAlchemy(current_app)
return db
I have not dug deep enough into flask, sqlalchemy, or flask-sqlalchemy to understand if this means that requests to the db from multiple threads are safe, but if you're reading this you're likely stuck in the baby stages of understanding these concepts too.
It works for me.....
I went to the settings on my phone and deleted my gmail account then re-added and synced the account and it worked for me.
settings>accounts>delete account settings>accounts>add account>sync and follow screen prompts
hope it works for you, i was receiving the df-dferh-01 error as well and couldnt buy in app purchases and this did the trick
Submodules parallel fetch aims at reducing the time required to fetch a repositories and all of its related submodules by enabling the fetching of multiple repositories at once. This can be accomplished by using the new --jobs option, e.g.:
git fetch --recurse-submodules --jobs=4
According to Git team, this can substantially speed up updating repositories that contain many submodules. When using --recurse-submodules without the new --jobs option, Git will fetch submodules one by one.
If you're looking to do a simple round in Angular you can easily set the filter inside your expression. For example:
{{ val | number:0 }}
See this CodePen example & for other number filter options.
If your SQL Server table has a column of type INT IDENTITY
(or BIGINT IDENTITY
), then you can get the latest inserted value using:
INSERT INTO dbo.YourTable(columns....)
VALUES(..........)
SELECT SCOPE_IDENTITY()
This works as long as you haven't inserted another row - it just returns the last IDENTITY
value handed out in this scope here.
There are at least two more options - @@IDENTITY
and IDENT_CURRENT
- read more about how they works and in what way they're different (and might give you unexpected results) in this excellent blog post by Pinal Dave here.
The operators delete
and delete []
are used respectively to destroy the objects created with new
and new[]
, returning to the allocated memory left available to the compiler's memory manager.
Objects created with new
must necessarily be destroyed with delete
, and that the arrays created with new[]
should be deleted with delete[]
.
vector:
list:
In general, use vector when you don't care what type of sequential container that you're using, but if you're doing many insertions or erasures to and from anywhere in the container other than the end, you're going to want to use list. Or if you need random access, then you're going to want vector, not list. Other than that, there are naturally instances where you're going to need one or the other based on your application, but in general, those are good guidelines.
Comment method like pro developers:
Windows/linux:
Line Comment :
Ctrl + /
Block Comment :
Ctrl + Shift
Method Commenting:
Type `/**` and press `Enter Key`
it will add the comment snippet like we see in standard documentation, give it a try this once.
/**
*
* @param addOpacity
*/
public void setOpacityOnUserImage(boolean addOpacity) {
// Your business logic.
}
You could use the tr
instead:
$p =~ tr/fo//d;
will delete every f and every o from $p
. In your case it should be:
$p =~ tr/\$#@~!&*()[];.,:?^ `\\\///d
tr/SEARCHLIST/REPLACEMENTLIST/cdsr
Transliterates all occurrences of the characters found (or not found if the
/c
modifier is specified) in the search list with the positionally corresponding character in the replacement list, possibly deleting some, depending on the modifiers specified.[…]
If the
/d
modifier is specified, any characters specified by SEARCHLIST not found in REPLACEMENTLIST are deleted.
In currently latest JDK6 release/build (b27), the Scanner
has a smaller buffer (1024 chars) as opposed to the BufferedReader
(8192 chars), but it's more than sufficient.
As to the choice, use the Scanner
if you want to parse the file, use the BufferedReader
if you want to read the file line by line. Also see the introductory text of their aforelinked API documentations.
nextXxx()
methods in Scanner
class. You can get By Using this function.
console.log(this.$route.query.test)
I don't think there's ever a reason not to use pull --rebase
-- I added code to Git specifically to allow my git pull
command to always rebase against upstream commits.
When looking through history, it is just never interesting to know when the guy/gal working on the feature stopped to synchronise up. It might be useful for the guy/gal while he/she is doing it, but that's what reflog
is for. It's just adding noise for everyone else.
For Mysql8.0.18:
CURRENT_TIMESTAMP([fsp])
Remove "([fsp])", resolved my problem.
None of these answers really work. As others noted the Cors package will only use the Access-Control-Allow-Origin header if the request had an Origin header. But you can't generally just add an Origin header to the request because browsers may try to regulate that too.
If you want a quick and dirty way to allow cross site requests to a web api, it's really a lot easier to just write a custom filter attribute:
public class AllowCors : ActionFilterAttribute
{
public override void OnActionExecuted(HttpActionExecutedContext actionExecutedContext)
{
if (actionExecutedContext == null)
{
throw new ArgumentNullException("actionExecutedContext");
}
else
{
actionExecutedContext.Response.Headers.Remove("Access-Control-Allow-Origin");
actionExecutedContext.Response.Headers.Add("Access-Control-Allow-Origin", "*");
}
base.OnActionExecuted(actionExecutedContext);
}
}
Then just use it on your Controller action:
[AllowCors]
public IHttpActionResult Get()
{
return Ok("value");
}
I won't vouch for the security of this in general, but it's probably a lot safer than setting the headers in the web.config since this way you can apply them only as specifically as you need them.
And of course it is simple to modify the above to allow only certain origins, methods etc.
var TestClass = function( ) {
var privateProperty = 42;
function privateMethod( ) {
alert( "privateMethod, " + privateProperty );
}
this.public = {
constructor: TestClass,
publicProperty: 88,
publicMethod: function( ) {
alert( "publicMethod" );
privateMethod( );
}
};
};
TestClass.prototype = new TestClass( ).public;
var myTestClass = new TestClass( );
alert( myTestClass.publicProperty );
myTestClass.publicMethod( );
alert( myTestClass.privateMethod || "no privateMethod" );
Similar to georgebrock but a little less verbose (IMHO) Any problems with doing it this way? (I haven't seen it anywhere)
edit: I realised this is kinda useless since every independent instantiation has its own copy of the public methods, thus undermining the use of the prototype.
This is really easy using package lubridate. All you have to do is tell R what format your date is already in. It then converts it into the standard format
nzd$date <- dmy(nzd$date)
that's it.
if (!String.prototype.hasOwnProperty('addSlashes')) {
String.prototype.addSlashes = function() {
return this.replace(/&/g, '&') /* This MUST be the 1st replacement. */
.replace(/'/g, ''') /* The 4 other predefined entities, required. */
.replace(/"/g, '"')
.replace(/\\/g, '\\\\')
.replace(/</g, '<')
.replace(/>/g, '>').replace(/\u0000/g, '\\0');
}
}
Usage: alert(str.addSlashes());
I don't exactly know how the stop stuff works. But I've got a gradient text example. Maybe this will help you out!
_you can also add more colors to the gradient if you want or just select other colors from the color generator
.rainbow2 {_x000D_
background-image: -webkit-linear-gradient(left, #E0F8F7, #585858, #fff); /* For Chrome and Safari */_x000D_
background-image: -moz-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Fx (3.6 to 15) */_x000D_
background-image: -ms-linear-gradient(left, #E0F8F7, #585858, #fff); /* For pre-releases of IE 10*/_x000D_
background-image: -o-linear-gradient(left, #E0F8F7, #585858, #fff); /* For old Opera (11.1 to 12.0) */_x000D_
background-image: linear-gradient(to right, #E0F8F7, #585858, #fff); /* Standard syntax; must be last */_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}_x000D_
.rainbow {_x000D_
_x000D_
background-image: -webkit-gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
background-image: gradient( linear, left top, right top, color-stop(0, #f22), color-stop(0.15, #f2f), color-stop(0.3, #22f), color-stop(0.45, #2ff), color-stop(0.6, #2f2),color-stop(0.75, #2f2), color-stop(0.9, #ff2), color-stop(1, #f22) );_x000D_
color:transparent;_x000D_
-webkit-background-clip: text;_x000D_
background-clip: text;_x000D_
}
_x000D_
<span class="rainbow">Rainbow text</span>_x000D_
<br />_x000D_
<span class="rainbow2">No rainbow text</span>
_x000D_
The MultiModelForm from django-betterforms
is a convenient wrapper to do what is described in Gnudiff's answer. It wraps regular ModelForm
s in a single class which is transparently (at least for basic usage) used as a single form. I've copied an example from their docs below.
# forms.py
from django import forms
from django.contrib.auth import get_user_model
from betterforms.multiform import MultiModelForm
from .models import UserProfile
User = get_user_model()
class UserEditForm(forms.ModelForm):
class Meta:
fields = ('email',)
class UserProfileForm(forms.ModelForm):
class Meta:
fields = ('favorite_color',)
class UserEditMultiForm(MultiModelForm):
form_classes = {
'user': UserEditForm,
'profile': UserProfileForm,
}
# views.py
from django.views.generic import UpdateView
from django.core.urlresolvers import reverse_lazy
from django.shortcuts import redirect
from django.contrib.auth import get_user_model
from .forms import UserEditMultiForm
User = get_user_model()
class UserSignupView(UpdateView):
model = User
form_class = UserEditMultiForm
success_url = reverse_lazy('home')
def get_form_kwargs(self):
kwargs = super(UserSignupView, self).get_form_kwargs()
kwargs.update(instance={
'user': self.object,
'profile': self.object.profile,
})
return kwargs
I had a similar problem and solved it by focusing on the dialog after open:
var $dialog = $("#pnlFiltros")
.dialog({
autoOpen: false,
hide: "puff",
width: dWidth,
height: 'auto',
draggable: true,
resizable: true,
closeOnScape : true,
position: [x,y]
});
$dialog.dialog('open');
$("#pnlFiltros").focus(); //focus on the div being dialogued (is that a word?)
But in my case the first element is an anchor, so I don't know if in your case that will leave the datepicker opened.
EDIT: only works on IE
Actually the orderBy
filter can take as a parameter not only a string but also a function. From the orderBy
documentation: https://docs.angularjs.org/api/ng/filter/orderBy):
function: Getter function. The result of this function will be sorted using the <, =, > operator.
So, you could write your own function. For example, if you would like to compare cards based on a sum of opt1 and opt2 (I'm making this up, the point is that you can have any arbitrary function) you would write in your controller:
$scope.myValueFunction = function(card) {
return card.values.opt1 + card.values.opt2;
};
and then, in your template:
ng-repeat="card in cards | orderBy:myValueFunction"
The other thing worth noting is that orderBy
is just one example of AngularJS filters so if you need a very specific ordering behaviour you could write your own filter (although orderBy
should be enough for most uses cases).
public static int[] strArrayToIntArray(String[] a){
int[] b = new int[a.length];
for (int i = 0; i < a.length; i++) {
b[i] = Integer.parseInt(a[i]);
}
return b;
}
This is a simple function, that should help you. You can use him like this:
int[] arr = strArrayToIntArray(/*YOUR STR ARRAY*/);
Here's a one line example, that uses plain JavaScript to inject a CSS link into the head element based on the filename portion of the URL:
document.head.innerHTML += '<link rel="stylesheet" href="css/style.css">';
Most browsers support it. See the browser compatibility.
UPDATE
This approach is by far the easiest:
http://www.codeproject.com/KB/dotnet/DebugWinServices.aspx
I leave my original answer below for posterity.
My services tend to have a class that encapsulates a Timer as I want the service to check at regular intervals whether there is any work for it to do.
We new up the class and call StartEventLoop() during the service start-up. (This class could easily be used from a console app too.)
The nice side-effect of this design is that the arguments with which you set up the Timer can be used to have a delay before the service actually starts working, so that you have time to attach a debugger manually.
p.s. How to attach the debugger manually to a running process...?
using System;
using System.Threading;
using System.Configuration;
public class ServiceEventHandler
{
Timer _timer;
public ServiceEventHandler()
{
// get configuration etc.
_timer = new Timer(
new TimerCallback(EventTimerCallback)
, null
, Timeout.Infinite
, Timeout.Infinite);
}
private void EventTimerCallback(object state)
{
// do something
}
public void StartEventLoop()
{
// wait a minute, then run every 30 minutes
_timer.Change(TimeSpan.Parse("00:01:00"), TimeSpan.Parse("00:30:00");
}
}
Also I used to do the following (already mentioned in previous answers but with the conditional compiler [#if] flags to help avoid it firing in a Release build).
I stopped doing it this way because sometimes we'd forget to build in Release and have a debugger break in an app running on a client demo (embarrasing!).
#if DEBUG
if (!System.Diagnostics.Debugger.IsAttached)
{
System.Diagnostics.Debugger.Break();
}
#endif
you can do so by using the :before
or :after
pseudo. read more about it here http://astronautweb.co/snippet/font-awesome/
change your code to this
.lb-prev:hover {
filter: progid:DXImageTransform.Microsoft.Alpha(Opacity=100);
opacity: 1;
text-decoration: none;
}
.lb-prev:before {
font-family: FontAwesome;
content: "\f053";
font-size: 30px;
}
do the same for the other icons. you might want to adjust the color and height of the icons too. anyway here is the fiddle hope this helps
You wont be able to do this from the client side because of the Same Origin Policy set by the browsers. You wont be able to get much information from the iFrame other than basic properties like its width and height.
Also, google sets in its response header an 'X-Frame-Options' of SAMEORIGIN.
Even if you did an ajax call to google you wont be able to inspect the response because the browser enforcing Same Origin Policy.
So, the only option is to make the request from your server to see if you can display the site in your IFrame.
So, on your server.. your web app would make a request to www.google.com and then inspect the response to see if it has a header argument of X-Frame-Options. If it does exist then you know the IFrame will error.
I wanted to remove the too-much spaces in a string (also in between the string, not only in the beginning or end). I made this, because I don't know how to do it otherwise:
string = "Name : David Account: 1234 Another thing: something "
ready = False
while ready == False:
pos = string.find(" ")
if pos != -1:
string = string.replace(" "," ")
else:
ready = True
print(string)
This replaces double spaces in one space until you have no double spaces any more
Print the Upper and Lower case alphabets in python using a built-in range function
def upperCaseAlphabets():
print("Upper Case Alphabets")
for i in range(65, 91):
print(chr(i), end=" ")
print()
def lowerCaseAlphabets():
print("Lower Case Alphabets")
for i in range(97, 123):
print(chr(i), end=" ")
upperCaseAlphabets();
lowerCaseAlphabets();
let datestring = "2017-02-14 02:16:28"
let formatter = DateFormatter()
formatter.dateStyle = DateFormatter.Style.full
formatter.timeStyle = DateFormatter.Style.full
formatter.dateFormat = "yyyy-MM-dd hh:mm:ss"
let date = formatter.date(from: datestring)
let date2 = formatter.String(from: date)
You can wrap your query in another SELECT
:
select count(*)
from
(
select count(SID) tot -- add alias
from Test
where Date = '2012-12-10'
group by SID
) src; -- add alias
In order for it to work, the count(SID)
need a column alias and you have to provide an alias to the subquery itself.
if you want to set jvm args on eclipse you can use below:
see below two links to accomplish it:
And for Tomcat you can create a setenv.bat
file in bin folder of Tomcat and add below lines to it :
echo "hello im starting setenv"
set CATALINA_OPTS=-DNLP.home=${NLP.home} -Dhostname=${hostname}
I made a small treatment after the URI object creation
if (url.startsWith("http:/")) {
if (!url.contains("http://")) {
url = url.replaceAll("http:/", "http://");
}
} else {
url = "http://" + url;
}
URI uri = new URI(url);
String domain = uri.getHost();
return domain.startsWith("www.") ? domain.substring(4) : domain;
Lazy loading images using above mentioned plugins uses conventional way of attaching listener to scroll events or by making use of setInterval and is highly non-performant as each call to getBoundingClientRect() forces the browser to re-layout the entire page and will introduce considerable jank to your website.
Use Lozad.js (just 569 bytes with no dependencies), which uses InteractionObserver to lazy load images performantly.
You must build parent module before doing child module.
Since AngularJS does not have directive DOM manipulations as jQuery does, a proper way to modify attributes of one element will be using directive. Through link function of a directive, you have access to both element and its attributes.
Wrapping you whole input inside one directive, you can still introduce ng-model's methods through controller property.
This method will help to decouple the logic of ngmodel with placeholder from controller. If there is no logic between them, you can definitely go as Wagner Francisco said.
64 bit version will allow a single process to use more RAM than 32 bit, however you may find that the memory footprint doubles depending on what you are storing in RAM (Integers in particular).
For example if your app requires > 2GB of RAM, so you switch from 32bit to 64bit you may find that your app is now requiring > 4GB of RAM.
Check whether all of your 3rd party modules are available in 64 bit, otherwise it may be easier to stick to 32bit in the meantime
xrange()
will not work for 3.x.
numpy.random.randint().tolist()
is a great alternative for integers in a specified interval:
#[In]:
import numpy as np
np.random.seed(123) #option for reproducibility
np.random.randint(low=0, high=100, size=10).tolist()
#[Out:]
[66, 92, 98, 17, 83, 57, 86, 97, 96, 47]
You also have np.random.uniform()
for floats:
#[In]:
np.random.uniform(low=0, high=100, size=10).tolist()
#[Out]:
[69.64691855978616,
28.613933495037948,
22.68514535642031,
55.13147690828912,
71.94689697855631,
42.3106460124461,
98.07641983846155,
68.48297385848633,
48.09319014843609,
39.211751819415056]
Actually it depends on what kind of uses. If you want to use it in a test-framework I highly recommend selenium-python. It is a great tool for testing automation related to web-browsers.
from selenium import webdriver
driver = webdriver.Firefox()
driver.get("http://www.python.org")
SELECT user_id
FROM user_logs
WHERE login_date BETWEEN '2014-02-01' AND '2014-03-01'
Between keyword works exceptionally for a date. it assumes the time is at 00:00:00 (i.e. midnight) for dates.
As posted already
All you need to do is to give ownership of the folders to Apache :
but I added -R for chown command:
sudo chown -R www-data:www-data /path/to/your/project/vendor
sudo chown -R www-data:www-data /path/to/your/project/storage
Do you mean something like this?
HTML
<button class="test"></button>
CSS
.test{
height:200px;
width:200px;
}
If you want to use inline CSS instead of an external stylesheet, see this:
<button style="height:200px;width:200px"></button>
In Java type conversions are performed automatically when the type of the expression on the right hand side of an assignment operation can be safely promoted to the type of the variable on the left hand side of the assignment. Thus we can safely assign:
byte -> short -> int -> long -> float -> double.
The same will not work the other way round. For example we cannot automatically convert a long to an int because the first requires more storage than the second and consequently information may be lost. To force such a conversion we must carry out an explicit conversion.
Type - Conversion
Or for what seems like rampant overkill, but is actually simplistic ... Pretty much covers all of your cases, and no empty string or unary concerns.
In the case the first arg is '-v', then do your conditional ps -ef
, else in all other cases throw the usage.
#!/bin/sh
case $1 in
'-v') if [ "$1" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi;;
*) echo "usage: $0 [-v]"
exit 1;; #It is good practice to throw a code, hence allowing $? check
esac
If one cares not where the '-v' arg is, then simply drop the case inside a loop. The would allow walking all the args and finding '-v' anywhere (provided it exists). This means command line argument order is not important. Be forewarned, as presented, the variable arg_match is set, thus it is merely a flag. It allows for multiple occurrences of the '-v' arg. One could ignore all other occurrences of '-v' easy enough.
#!/bin/sh
usage ()
{
echo "usage: $0 [-v]"
exit 1
}
unset arg_match
for arg in $*
do
case $arg in
'-v') if [ "$arg" = -v ]; then
echo "`ps -ef | grep -v '\['`"
else
echo "`ps -ef | grep '\[' | grep root`"
fi
arg_match=1;; # this is set, but could increment.
*) ;;
esac
done
if [ ! $arg_match ]
then
usage
fi
But, allow multiple occurrences of an argument is convenient to use in situations such as:
$ adduser -u:sam -s -f -u:bob -trace -verbose
We care not about the order of the arguments, and even allow multiple -u arguments. Yes, it is a simple matter to also allow:
$ adduser -u sam -s -f -u bob -trace -verbose
On Windows, you can also use the Win32 File Namespace prefixed with \\?\
to refer to your local directories:
\\?\C:\my_dir
You could compare String representations so:
array1.toString() == array2.toString()
array1.toString() !== array3.toString()
but that would also make
array4 = ['1',2,3,4,5]
equal to array1 if that matters to you
MongoDB needs data directory to store data.
Default path is /data/db
When you start MongoDB engine, it searches this directory which is missing in your case. Solution is create this directory and assign rwx
permission to user.
If you want to change the path of your data directory then you should specify it while starting mongod server like,
mongod --dbpath /data/<path> --port <port no>
This should help you start your mongod server with custom path and port.
I use Hibernate 5.2 and @Temporal
is not required anymore.
java.util.date, sql.date, time.LocalDate are stored into DB with appropriate datatype as Date/timestamp.
Here is a performance comparison of the proposed methods in other answers.
> foo <- sapply(letters, function(x){runif(5)}, simplify = FALSE)
> microbenchmark::microbenchmark('k' %in% names(foo),
is.null(foo[['k']]),
exists('k', where = foo))
Unit: nanoseconds
expr min lq mean median uq max neval cld
"k" %in% names(foo) 467 933 1064.31 934 934 10730 100 a
is.null(foo[["k"]]) 0 0 168.50 1 467 3266 100 a
exists("k", where = foo) 6532 6998 7940.78 7232 7465 56917 100 b
If you are planing to use the list as a fast dictionary accessed many times, then the is.null
approach might be the only viable option. I assume it is O(1), while the %in%
approach is O(n)?
No. The HTML 5 spec mentions:
The method and formmethod content attributes are enumerated attributes with the following keywords and states:
The keyword get, mapping to the state GET, indicating the HTTP GET method. The GET method should only request and retrieve data and should have no other effect.
The keyword post, mapping to the state POST, indicating the HTTP POST method. The POST method requests that the server accept the submitted form's data to be processed, which may result in an item being added to a database, the creation of a new web page resource, the updating of the existing page, or all of the mentioned outcomes.
The keyword dialog, mapping to the state dialog, indicating that submitting the form is intended to close the dialog box in which the form finds itself, if any, and otherwise not submit.
The invalid value default for these attributes is the GET state
I.e. HTML forms only support GET and POST as HTTP request methods. A workaround for this is to tunnel other methods through POST by using a hidden form field which is read by the server and the request dispatched accordingly.
However, GET, POST, PUT and DELETE are supported by the implementations of XMLHttpRequest (i.e. AJAX calls) in all the major web browsers (IE, Firefox, Safari, Chrome, Opera).
You shouldn't need a callback for iterating through a list. Just add the end()
call after the loop.
posts.forEach(function(v, i){
res.write(v + ". Index " + i);
});
res.end();
In my case, I had this javascript on the form submit:
$('form').submit(function () {
$('input').prop('disabled', true);
});
This was removing the hidden RequestVerificationToken from the form being submitted. I changed that to:
$('form').submit(function () {
$('input[type=submit]').prop('disabled', true);
$('input[type=text]').prop('readonly', true);
$('input[type=password]').prop('readonly', true);
});
... and it worked fine.
These days, ECMAScript 6 (ECMA-262) is "in the house". Use Number.isInteger(x)
to ask the question you want to ask with respect to the type of x:
js> var x = 3
js> Number.isInteger(x)
true
js> var y = 3.1
js> Number.isInteger(y)
false
The int values are already zero after initialization, as everyone has mentioned. If you have a situation where you actually do need to set array values to zero and want to optimize that, use System.arraycopy
:
static private int[] zeros = new float[64];
...
int[] values = ...
if (zeros.length < values.length) zeros = new int[values.length];
System.arraycopy(zeros, 0, values, 0, values.length);
This uses memcpy
under the covers in most or all JRE implementations. Note the use of a static like this is safe even with multiple threads, since the worst case is multiple threads reallocate zeros
concurrently, which doesn't hurt anything.
You could also use Arrays.fill
as some others have mentioned. Arrays.fill
could use memcpy
in a smart JVM, but is probably just a Java loop and the bounds checking that entails.
Benchmark your optimizations, of course.
use can use
string userid = User.FindFirst("id").Value;
for some reason NameIdentifier now retrieve the username (.net core 2.2)
To display the all details for each news post title ie. "news.id" which is the primary key, you need to use GROUP BY clause for "news.id"
SELECT news.id, users.username, news.title, news.date,
news.body, COUNT(comments.id)
FROM news
LEFT JOIN users
ON news.user_id = users.id
LEFT JOIN comments
ON comments.news_id = news.id
GROUP BY news.id
I got same problem... and I did it.
My code before:
<link rel="stylesheet" href="../css/style.default.css" type="text/css" />
And the problem solved after I changed my code into this:
<link rel="stylesheet" href="css/style.default.css" type="text/css" />
So I think "href=../"
is not allowed, because I don't have problem when I use "../"
in "src=../"
str.replace(/^.+?\"|^.|\".+/, '');
This is sometimes bad to use when you wanna select what else to remove between "" and you cannot use it more than twice in one string. All it does is select whatever is not in between "" and replace it with nothing.
Even for me it is a bit confusing, but ill try to explain it. ^.+?
(not anything OPTIONAL) till first "
then |
Or/stop (still researching what it really means) till/at ^.
has selected nothing until before the 2nd "
using (|
stop/at). And select all that comes after with .+.
I'm fairly certain the answer is: No. You can select options with JavaScript but not open the select. You'd have to use a custom solution.
if(sender is TextBox) {
var text = (sender as TextBox).Text;
}
NUL
works programmatically as well. E.g. the following:
freopen("NUL", "w", stderr);
works as expected without creating a file. (MSVC++ 12.0)
Objective-C is a more perfect superset of C. In C and Objective-C implicit casting from void*
to a struct pointer is allowed.
Foo* bar = malloc(sizeof(Foo));
C++ will not compile unless the void
pointer is explicitly cast:
Foo* bar = (Foo*)malloc(sizeof(Foo));
The relevance of this to every day programming is zero, just a fun trivia fact.
iOS 7 has a new method that allows you to draw a view hierarchy into the current graphics context. This can be used to get an UIImage very fast.
I implemented a category method on UIView
to get the view as an UIImage
:
- (UIImage *)pb_takeSnapshot {
UIGraphicsBeginImageContextWithOptions(self.bounds.size, NO, [UIScreen mainScreen].scale);
[self drawViewHierarchyInRect:self.bounds afterScreenUpdates:YES];
// old style [self.layer renderInContext:UIGraphicsGetCurrentContext()];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return image;
}
It is considerably faster then the existing renderInContext:
method.
Reference: https://developer.apple.com/library/content/qa/qa1817/_index.html
UPDATE FOR SWIFT: An extension that does the same:
extension UIView {
func pb_takeSnapshot() -> UIImage {
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.mainScreen().scale)
drawViewHierarchyInRect(self.bounds, afterScreenUpdates: true)
// old style: layer.renderInContext(UIGraphicsGetCurrentContext())
let image = UIGraphicsGetImageFromCurrentImageContext()
UIGraphicsEndImageContext()
return image
}
}
UPDATE FOR SWIFT 3
UIGraphicsBeginImageContextWithOptions(bounds.size, false, UIScreen.main.scale)
drawHierarchy(in: self.bounds, afterScreenUpdates: true)
let image = UIGraphicsGetImageFromCurrentImageContext()!
UIGraphicsEndImageContext()
return image
You can use Task Scheduler Managed Wrapper:
using System;
using Microsoft.Win32.TaskScheduler;
class Program
{
static void Main(string[] args)
{
// Get the service on the local machine
using (TaskService ts = new TaskService())
{
// Create a new task definition and assign properties
TaskDefinition td = ts.NewTask();
td.RegistrationInfo.Description = "Does something";
// Create a trigger that will fire the task at this time every other day
td.Triggers.Add(new DailyTrigger { DaysInterval = 2 });
// Create an action that will launch Notepad whenever the trigger fires
td.Actions.Add(new ExecAction("notepad.exe", "c:\\test.log", null));
// Register the task in the root folder
ts.RootFolder.RegisterTaskDefinition(@"Test", td);
// Remove the task we just created
ts.RootFolder.DeleteTask("Test");
}
}
}
Alternatively you can use native API or go for Quartz.NET. See this for details.
I think a nice solution is with the function filter of pandas and regex (match everything except "b"):
df.filter(regex="^(?!b$)")
EDIT: I am maintaining a similar, but more in-depth answer at: https://stackoverflow.com/a/28380690/895245
To see exactly what is happening, use nc -l
and an user agent like a browser or cURL.
Save the form to an .html
file:
<form action="http://localhost:8000" method="post" enctype="multipart/form-data">
<p><input type="text" name="text" value="text default">
<p><input type="file" name="file1">
<p><input type="file" name="file2">
<p><button type="submit">Submit</button>
</form>
Create files to upload:
echo 'Content of a.txt.' > a.txt
echo '<!DOCTYPE html><title>Content of a.html.</title>' > a.html
Run:
nc -l localhost 8000
Open the HTML on your browser, select the files and click on submit and check the terminal.
nc
prints the request received. Firefox sent:
POST / HTTP/1.1
Host: localhost:8000
User-Agent: Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:29.0) Gecko/20100101 Firefox/29.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Cookie: __atuvc=34%7C7; permanent=0; _gitlab_session=226ad8a0be43681acf38c2fab9497240; __profilin=p%3Dt; request_method=GET
Connection: keep-alive
Content-Type: multipart/form-data; boundary=---------------------------9051914041544843365972754266
Content-Length: 554
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="text"
text default
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file1"; filename="a.txt"
Content-Type: text/plain
Content of a.txt.
-----------------------------9051914041544843365972754266
Content-Disposition: form-data; name="file2"; filename="a.html"
Content-Type: text/html
<!DOCTYPE html><title>Content of a.html.</title>
-----------------------------9051914041544843365972754266--
Aternativelly, cURL should send the same POST request as your a browser form:
nc -l localhost 8000
curl -F "text=default" -F "[email protected]" -F "[email protected]" localhost:8000
You can do multiple tests with:
while true; do printf '' | nc -l localhost 8000; done
We can collect the form params submitted using POST with using serialize concept.
Try this:
$('form').serialize();
Just enclose it alert, it displays all the parameters including hidden.
You can do it using write() :
#open file with *.html* extension to write html
file= open("my.html","w")
#write then close file
file.write(html)
file.close()
You can check console output. It prints error:
The following assertion was thrown during performResize(): Horizontal viewport was given unbounded height. Viewports expand in the cross axis to fill their container and constrain their children to match their extent in the cross axis. In this case, a horizontal viewport was given an unlimited amount of vertical space in which to expand.
You need to add height constraint to your horizontal list. E.g. wrap in Container with height:
Container(
height: 44.0,
child: ListView(
scrollDirection: Axis.horizontal,
children: <Widget>[
RaisedButton(
onPressed: null,
child: Text("Facebook"),
),
Padding(padding: EdgeInsets.all(5.00)),
RaisedButton(
onPressed: null,
child: Text("Google"),
)
],
),
)
In getview method put listener outside checking the view..try to follow this..it worked in my case..How to Increase or decrease value of edittext in listview's each row?
One option would be to create a symbolic link between a subfolder in your storage directory and public directory.
For example
ln -s /path/to/laravel/storage/avatars /path/to/laravel/public/avatars
This is also the method used by Envoyer, a deployment manager built by Taylor Otwell, the developer of Laravel.
I always use pseudo elements :before
and :after
for changing the appearance of checkboxes and radio buttons. it's works like a charm.
Refer this link for more info
Steps
visibility:hidden
or opacity:0
or position:absolute;left:-9999px
etc.:before
element and pass either an empty or a non-breaking space '\00a0'
;:checked
state, pass the unicode content: "\2713"
, which is a checkmark;:focus
style to make the checkbox accessible.Here is how I did it.
.box {_x000D_
background: #666666;_x000D_
color: #ffffff;_x000D_
width: 250px;_x000D_
padding: 10px;_x000D_
margin: 1em auto;_x000D_
}_x000D_
p {_x000D_
margin: 1.5em 0;_x000D_
padding: 0;_x000D_
}_x000D_
input[type="checkbox"] {_x000D_
visibility: hidden;_x000D_
}_x000D_
label {_x000D_
cursor: pointer;_x000D_
}_x000D_
input[type="checkbox"] + label:before {_x000D_
border: 1px solid #333;_x000D_
content: "\00a0";_x000D_
display: inline-block;_x000D_
font: 16px/1em sans-serif;_x000D_
height: 16px;_x000D_
margin: 0 .25em 0 0;_x000D_
padding: 0;_x000D_
vertical-align: top;_x000D_
width: 16px;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:before {_x000D_
background: #fff;_x000D_
color: #333;_x000D_
content: "\2713";_x000D_
text-align: center;_x000D_
}_x000D_
input[type="checkbox"]:checked + label:after {_x000D_
font-weight: bold;_x000D_
}_x000D_
_x000D_
input[type="checkbox"]:focus + label::before {_x000D_
outline: rgb(59, 153, 252) auto 5px;_x000D_
}
_x000D_
<div class="content">_x000D_
<div class="box">_x000D_
<p>_x000D_
<input type="checkbox" id="c1" name="cb">_x000D_
<label for="c1">Option 01</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c2" name="cb">_x000D_
<label for="c2">Option 02</label>_x000D_
</p>_x000D_
<p>_x000D_
<input type="checkbox" id="c3" name="cb">_x000D_
<label for="c3">Option 03</label>_x000D_
</p>_x000D_
</div>_x000D_
</div>
_x000D_
Much more stylish using :before
and :after
body{_x000D_
font-family: sans-serif; _x000D_
}_x000D_
_x000D_
.container {_x000D_
margin-top: 50px;_x000D_
margin-left: 20px;_x000D_
margin-right: 20px;_x000D_
}_x000D_
.checkbox {_x000D_
width: 100%;_x000D_
margin: 15px auto;_x000D_
position: relative;_x000D_
display: block;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"] {_x000D_
width: auto;_x000D_
opacity: 0.00000001;_x000D_
position: absolute;_x000D_
left: 0;_x000D_
margin-left: -20px;_x000D_
}_x000D_
.checkbox label {_x000D_
position: relative;_x000D_
}_x000D_
.checkbox label:before {_x000D_
content: '';_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top: 0;_x000D_
margin: 4px;_x000D_
width: 22px;_x000D_
height: 22px;_x000D_
transition: transform 0.28s ease;_x000D_
border-radius: 3px;_x000D_
border: 2px solid #7bbe72;_x000D_
}_x000D_
.checkbox label:after {_x000D_
content: '';_x000D_
display: block;_x000D_
width: 10px;_x000D_
height: 5px;_x000D_
border-bottom: 2px solid #7bbe72;_x000D_
border-left: 2px solid #7bbe72;_x000D_
-webkit-transform: rotate(-45deg) scale(0);_x000D_
transform: rotate(-45deg) scale(0);_x000D_
transition: transform ease 0.25s;_x000D_
will-change: transform;_x000D_
position: absolute;_x000D_
top: 12px;_x000D_
left: 10px;_x000D_
}_x000D_
.checkbox input[type="checkbox"]:checked ~ label::before {_x000D_
color: #7bbe72;_x000D_
}_x000D_
_x000D_
.checkbox input[type="checkbox"]:checked ~ label::after {_x000D_
-webkit-transform: rotate(-45deg) scale(1);_x000D_
transform: rotate(-45deg) scale(1);_x000D_
}_x000D_
_x000D_
.checkbox label {_x000D_
min-height: 34px;_x000D_
display: block;_x000D_
padding-left: 40px;_x000D_
margin-bottom: 0;_x000D_
font-weight: normal;_x000D_
cursor: pointer;_x000D_
vertical-align: sub;_x000D_
}_x000D_
.checkbox label span {_x000D_
position: absolute;_x000D_
top: 50%;_x000D_
-webkit-transform: translateY(-50%);_x000D_
transform: translateY(-50%);_x000D_
}_x000D_
.checkbox input[type="checkbox"]:focus + label::before {_x000D_
outline: 0;_x000D_
}
_x000D_
<div class="container"> _x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox" name="" value="">_x000D_
<label for="checkbox"><span>Checkbox</span></label>_x000D_
</div>_x000D_
_x000D_
<div class="checkbox">_x000D_
<input type="checkbox" id="checkbox2" name="" value="">_x000D_
<label for="checkbox2"><span>Checkbox</span></label>_x000D_
</div>_x000D_
</div>
_x000D_
Code posted by you is correct and should have worked. But check exactly what you have in the char*
. If the correct value is to big to be represented, functions will return a positive or negative HUGE_VAL
. Check what you have in the char*
against maximum values that float
and double
can represent on your computer.
Check this page for strtod
reference and this page for atof
reference.
I have tried the example you provided in both Windows and Linux and it worked fine.
var array = Encoding.ASCII.GetBytes(new string(' ', 100));
This test shows that your second option can perform significantly better. Findings first, then the code:
one filter with predicate of form u -> exp1 && exp2, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=4142, min=29, average=41.420000, max=82}
two filters with predicates of form u -> exp1, list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=13315, min=117, average=133.150000, max=153}
one filter with predicate of form predOne.and(pred2), list size 10000000, averaged over 100 runs: LongSummaryStatistics{count=100, sum=10320, min=82, average=103.200000, max=127}
now the code:
enum Gender {
FEMALE,
MALE
}
static class User {
Gender gender;
int age;
public User(Gender gender, int age){
this.gender = gender;
this.age = age;
}
public Gender getGender() {
return gender;
}
public void setGender(Gender gender) {
this.gender = gender;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
static long test1(List<User> users){
long time1 = System.currentTimeMillis();
users.stream()
.filter((u) -> u.getGender() == Gender.FEMALE && u.getAge() % 2 == 0)
.allMatch(u -> true); // least overhead terminal function I can think of
long time2 = System.currentTimeMillis();
return time2 - time1;
}
static long test2(List<User> users){
long time1 = System.currentTimeMillis();
users.stream()
.filter(u -> u.getGender() == Gender.FEMALE)
.filter(u -> u.getAge() % 2 == 0)
.allMatch(u -> true); // least overhead terminal function I can think of
long time2 = System.currentTimeMillis();
return time2 - time1;
}
static long test3(List<User> users){
long time1 = System.currentTimeMillis();
users.stream()
.filter(((Predicate<User>) u -> u.getGender() == Gender.FEMALE).and(u -> u.getAge() % 2 == 0))
.allMatch(u -> true); // least overhead terminal function I can think of
long time2 = System.currentTimeMillis();
return time2 - time1;
}
public static void main(String... args) {
int size = 10000000;
List<User> users =
IntStream.range(0,size)
.mapToObj(i -> i % 2 == 0 ? new User(Gender.MALE, i % 100) : new User(Gender.FEMALE, i % 100))
.collect(Collectors.toCollection(()->new ArrayList<>(size)));
repeat("one filter with predicate of form u -> exp1 && exp2", users, Temp::test1, 100);
repeat("two filters with predicates of form u -> exp1", users, Temp::test2, 100);
repeat("one filter with predicate of form predOne.and(pred2)", users, Temp::test3, 100);
}
private static void repeat(String name, List<User> users, ToLongFunction<List<User>> test, int iterations) {
System.out.println(name + ", list size " + users.size() + ", averaged over " + iterations + " runs: " + IntStream.range(0, iterations)
.mapToLong(i -> test.applyAsLong(users))
.summaryStatistics());
}
1. Why does the getOne(id) method fail?
See this section in the docs. You overriding the already in place transaction might be causing the issue. However, without more info this one is difficult to answer.
2. When I should use the getOne(id) method?
Without digging into the internals of Spring Data JPA, the difference seems to be in the mechanism used to retrieve the entity.
If you look at the JavaDoc for getOne(ID)
under See Also:
See Also:
EntityManager.getReference(Class, Object)
it seems that this method just delegates to the JPA entity manager's implementation.
However, the docs for findOne(ID)
do not mention this.
The clue is also in the names of the repositories.
JpaRepository
is JPA specific and therefore can delegate calls to the entity manager if so needed.
CrudRepository
is agnostic of the persistence technology used. Look here. It's used as a marker interface for multiple persistence technologies like JPA, Neo4J etc.
So there's not really a 'difference' in the two methods for your use cases, it's just that findOne(ID)
is more generic than the more specialised getOne(ID)
. Which one you use is up to you and your project but I would personally stick to the findOne(ID)
as it makes your code less implementation specific and opens the doors to move to things like MongoDB etc. in the future without too much refactoring :)
Regex.Unescape(string) method converts any escaped characters in the input string.
The Unescape method performs one of the following two transformations:
It reverses the transformation performed by the Escape method by removing the escape character ("\") from each character escaped by the method. These include the \, *, +, ?, |, {, [, (,), ^, $, ., #, and white space characters. In addition, the Unescape method unescapes the closing bracket (]) and closing brace (}) characters.
It replaces the hexadecimal values in verbatim string literals with the actual printable characters. For example, it replaces @"\x07" with "\a", or @"\x0A" with "\n". It converts to supported escape characters such as \a, \b, \e, \n, \r, \f, \t, \v, and alphanumeric characters.
string str = @"a\\b\\c";
var output = System.Text.RegularExpressions.Regex.Unescape(str);
Reference:
If there are multiple launchers in a one package above code has a problem. Eg: on LG Optimus Facebook for LG, MySpace for LG, Twitter for LG contains in a one package name SNS and if you use above SNS will repeat. After hours of research I came with below code. Seems to work well.
private List<String> getInstalledComponentList()
throws NameNotFoundException {
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
List<ResolveInfo> ril = getPackageManager().queryIntentActivities(mainIntent, 0);
List<String> componentList = new ArrayList<String>();
String name = null;
for (ResolveInfo ri : ril) {
if (ri.activityInfo != null) {
Resources res = getPackageManager().getResourcesForApplication(ri.activityInfo.applicationInfo);
if (ri.activityInfo.labelRes != 0) {
name = res.getString(ri.activityInfo.labelRes);
} else {
name = ri.activityInfo.applicationInfo.loadLabel(
getPackageManager()).toString();
}
componentList.add(name);
}
}
return componentList;
}
You can also use ISNULL and a select statement to get this result
SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1
You can use strip binary on object file(eg. executable) to strip all symbols from it.
Note: it changes file itself and don't create copy.
If ASP.NET 4.0 is not registered with IIS
*****Use this step if u cant access using run command*****
Go to
C Drive
-->>windows
-->>Microsoft.Net
-->>Framework
-->>v4.0.30319
(Choose whatever framework to register with IIS me selecting Framework 4)-->>aspnet_regiis
(Double-click or right click & choose run as administrator)
This works in Python 2.x.
For Python 3 look in the docs:
import urllib.request
with urllib.request.urlopen("http://www.python.org") as url:
s = url.read()
# I'm guessing this would output the html source code ?
print(s)
I use the following method in my project
-(NSArray*)networkErrorCodes
{
static NSArray *codesArray;
if (![codesArray count]){
@synchronized(self){
const int codes[] = {
//kCFURLErrorUnknown, //-998
//kCFURLErrorCancelled, //-999
//kCFURLErrorBadURL, //-1000
//kCFURLErrorTimedOut, //-1001
//kCFURLErrorUnsupportedURL, //-1002
//kCFURLErrorCannotFindHost, //-1003
kCFURLErrorCannotConnectToHost, //-1004
kCFURLErrorNetworkConnectionLost, //-1005
kCFURLErrorDNSLookupFailed, //-1006
//kCFURLErrorHTTPTooManyRedirects, //-1007
kCFURLErrorResourceUnavailable, //-1008
kCFURLErrorNotConnectedToInternet, //-1009
//kCFURLErrorRedirectToNonExistentLocation, //-1010
kCFURLErrorBadServerResponse, //-1011
//kCFURLErrorUserCancelledAuthentication, //-1012
//kCFURLErrorUserAuthenticationRequired, //-1013
//kCFURLErrorZeroByteResource, //-1014
//kCFURLErrorCannotDecodeRawData, //-1015
//kCFURLErrorCannotDecodeContentData, //-1016
//kCFURLErrorCannotParseResponse, //-1017
kCFURLErrorInternationalRoamingOff, //-1018
kCFURLErrorCallIsActive, //-1019
//kCFURLErrorDataNotAllowed, //-1020
//kCFURLErrorRequestBodyStreamExhausted, //-1021
kCFURLErrorFileDoesNotExist, //-1100
//kCFURLErrorFileIsDirectory, //-1101
kCFURLErrorNoPermissionsToReadFile, //-1102
//kCFURLErrorDataLengthExceedsMaximum, //-1103
};
int size = sizeof(codes)/sizeof(int);
NSMutableArray *array = [[NSMutableArray alloc] init];
for (int i=0;i<size;++i){
[array addObject:[NSNumber numberWithInt:codes[i]]];
}
codesArray = [array copy];
}
}
return codesArray;
}
Then I just check the error code and show alert if it is in the list
if ([[self networkErrorCodes] containsObject:[NSNumber
numberWithInt:[error code]]]){
// Fire Alert View Here
}
But as you can see I commented out codes that I think does not fit to my definition of NO INTERNET. E.g the code of -1012 (Authentication fail.) You may edit the list as you like.
In my project I use it at username/password entering from user. And in my view (physical) network connection errors could be the only reason to show alert view in your network based app. In any other case (e.g. incorrect username/password pair) I prefer to do some custom user friendly animation, OR just repeat the failed attempt again without any attention of the user. Especially if the user didn't explicitly initiated a network call.
Regards to martinezdelariva for a link to documentation.
It's not that different from uploading one file - $_FILES
is an array containing any and all uploaded files.
There's a chapter in the PHP manual: Uploading multiple files
If you want to enable multiple file uploads with easy selection on the user's end (selecting multiple files at once instead of filling in upload fields) take a look at SWFUpload. It works differently from a normal file upload form and requires Flash to work, though. SWFUpload was obsoleted along with Flash. Check the other, newer answers for the now-correct approach.
Using Bootstrap 3 I create 3 divs of equal width (in 12 column layout 4 columns for each div). This way you can keep your central zone centered even if left/right sections have different widths (if they don't overflow their columns' space).
HTML:
<div id="container">
<div id="left" class="col col-xs-4 text-left">Left</div>
<div id="center" class="col col-xs-4 text-center">Center</div>
<div id="right" class="col col-xs-4 text-right">Right</div>
</div>
CSS:
#container {
border: 1px solid #aaa;
margin: 10px;
padding: 10px;
height: 100px;
}
.col {
border: 1px solid #07f;
padding: 0;
}
To create that structure without libraries I copied some rules from Bootstrap CSS.
HTML:
<div id="container">
<div id="left" class="col">Left</div>
<div id="center" class="col">Center</div>
<div id="right" class="col">Right</div>
</div>
CSS:
* {
box-sizing: border-box;
}
#container {
border: 1px solid #aaa;
margin: 10px;
padding: 10px;
height: 100px;
}
.col {
float: left;
width: 33.33333333%;
border: 1px solid #07f;
padding: 0;
}
#left {
text-align: left;
}
#center {
text-align: center;
}
#right {
text-align: right;
}
The accepted answer does not work in Jupyter (at least when using some libraries).
The Javascript solutions here only hide warnings that are already showing but not warnings that would be shown in the future.
To hide/unhide warnings in Jupyter and JupyterLab I wrote the following script that essentially toggles css to hide/unhide warnings.
%%javascript
(function(on) {
const e=$( "<a>Setup failed</a>" );
const ns="js_jupyter_suppress_warnings";
var cssrules=$("#"+ns);
if(!cssrules.length) cssrules = $("<style id='"+ns+"' type='text/css'>div.output_stderr { } </style>").appendTo("head");
e.click(function() {
var s='Showing';
cssrules.empty()
if(on) {
s='Hiding';
cssrules.append("div.output_stderr, div[data-mime-type*='.stderr'] { display:none; }");
}
e.text(s+' warnings (click to toggle)');
on=!on;
}).click();
$(element).append(e);
})(true);
Very easy trick is using a CSS calc
formula. All modern browsers, IE9, wide range of mobile browsers should support this.
<div style='white-space:nowrap'>
<span style='display:inline-block;width:80px;font-weight:bold'>
<label for='field1'>Field1</label>
</span>
<input id='field1' name='field1' type='text' value='Some text' size='30' style='width:calc(100% - 80px)' />
</div>
You can find the DMGs or XIPs for Xcode and other development tools on https://developer.apple.com/download/more/ (requires Apple ID to login).
You must login to have a valid session before downloading anything below.
*(Newest on top. For each minor version (6.3, 5.1, etc.) only the latest revision is kept in the list.)
*With Xcode 12.2, Apple introduces the term “Release Candidate” (RC) which replaces “GM seed” and indicates this version is near final.
Xcode 12
12.4 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later) (Latest as of 27-Jan-2021)
12.3 (requires a Mac with Apple silicon running macOS Big Sur 11 or later, or an Intel-based Mac running macOS Catalina 10.15.4 or later)
12.0.1 (Requires macOS 10.15.4 or later) (Latest as of 24-Sept-2020)
Xcode 11
11.7 (Latest as of Sept 02 2020)
11.4.1 (Requires macOS 10.15.2 or later)
11 (Requires macOS 10.14.4 or later)
Xcode 10 (unsupported for iTunes Connect)
Xcode 9
Xcode 8
Xcode 7
Xcode 6
Even Older Versions (unsupported for iTunes Connect)
My situation was that I did not have a main function.
Use the accept attribute of the input tag. So to accept only PNG's, JPEG's and GIF's you can use the following code:
<input type="file" name="myImage" accept="image/x-png,image/gif,image/jpeg" />
_x000D_
Or simply:
<input type="file" name="myImage" accept="image/*" />
_x000D_
Note that this only provides a hint to the browser as to what file-types to display to the user, but this can be easily circumvented, so you should always validate the uploaded file on the server also.
It should work in IE 10+, Chrome, Firefox, Safari 6+, Opera 15+, but support is very sketchy on mobiles (as of 2015) and by some reports, this may actually prevent some mobile browsers from uploading anything at all, so be sure to test your target platforms well.
For detailed browser support, see http://caniuse.com/#feat=input-file-accept
All that's needed is that the format specifiers and the types agree, and you can always cast to make that true. long
is at least 32 bits, so %lu
together with (unsigned long)k
is always correct:
uint32_t k;
printf("%lu\n", (unsigned long)k);
size_t
is trickier, which is why %zu
was added in C99. If you can't use that, then treat it just like k
(long
is the biggest type in C89, size_t
is very unlikely to be larger).
size_t sz;
printf("%zu\n", sz); /* C99 version */
printf("%lu\n", (unsigned long)sz); /* common C89 version */
If you don't get the format specifiers correct for the type you are passing, then printf
will do the equivalent of reading too much or too little memory out of the array. As long as you use explicit casts to match up types, it's portable.
Turns out that the post (or rather the whole table) was locked by the very same connection that I tried to update the post with.
I had a opened record set of the post that was created by:
Set RecSet = Conn.Execute()
This type of recordset is supposed to be read-only and when I was using MS Access as database it did not lock anything. But apparently this type of record set did lock something on MS SQL Server 2012 because when I added these lines of code before executing the UPDATE SQL statement...
RecSet.Close
Set RecSet = Nothing
...everything worked just fine.
So bottom line is to be careful with opened record sets - even if they are read-only they could lock your table from updates.
The other answers to this question are outdated, never matched implementation reality, and have officially become incorrect now that the ES6 / ES2015 spec has been published.
See the section on property iteration order in Exploring ES6 by Axel Rauschmayer:
All methods that iterate over property keys do so in the same order:
- First all Array indices, sorted numerically.
- Then all string keys (that are not indices), in the order in which they were created.
- Then all symbols, in the order in which they were created.
So yes, JavaScript objects are in fact ordered, and the order of their keys/properties can be changed.
Here’s how you can sort an object by its keys/properties, alphabetically:
const unordered = {
'b': 'foo',
'c': 'bar',
'a': 'baz'
};
console.log(JSON.stringify(unordered));
// ? '{"b":"foo","c":"bar","a":"baz"}'
const ordered = Object.keys(unordered).sort().reduce(
(obj, key) => {
obj[key] = unordered[key];
return obj;
},
{}
);
console.log(JSON.stringify(ordered));
// ? '{"a":"baz","b":"foo","c":"bar"}'
_x000D_
Use var
instead of const
for compatibility with ES5 engines.
You can use ping -a <ip>
or nbtstat -A <ip>
The error comes when you try to call sum(x)
and x
is a factor.
What that means is that one of your columns, though they look like numbers are actually factors (what you are seeing is the text representation)
simple fix, convert to numeric. However, it needs an intermeidate step of converting to character first. Use the following:
family[, 1] <- as.numeric(as.character( family[, 1] ))
family[, 3] <- as.numeric(as.character( family[, 3] ))
For a detailed explanation of why the intermediate as.character
step is needed, take a look at this question: How to convert a factor to integer\numeric without loss of information?
For security reasons you must avoid providing password on a command line otherwise anyone running ps command can see your password. Better to use sshpass utility like this:
#!/bin/bash
export SSHPASS="your-password"
sshpass -e ssh -oBatchMode=no sshUser@remoteHost
You might be interested in How to run the sftp command with a password from Bash script?
In my case i was using jQuery validation rules with
submitHandler
function and submitting the data as new FormData(form);
Select Option
<select class="selectpicker" id="branch" name="branch" multiple="multiple" title="Of Branch" data-size="6" required>
<option disabled>Multiple Branch Select</option>
<option value="Computer">Computer</option>
<option value="Civil">Civil</option>
<option value="EXTC">EXTC</option>
<option value="ETRX">ETRX</option>
<option value="Mechinical">Mechinical</option>
</select>
<input type="hidden" name="new_branch" id="new_branch">
Get the multiple selected value and set to new_branch
input value & while submitting the form get value from new_branch
Just replace hidden
with text
to view on the output
<input type="text" name="new_branch" id="new_branch">
Script (jQuery / Ajax)
<script>
$(document).ready(function() {
$('#branch').on('change', function(){
var selected = $(this).find("option:selected"); //get current selected value
var arrSelected = []; //Array to store your multiple value in stack
selected.each(function(){
arrSelected.push($(this).val()); //Stack the value
});
$('#new_branch').val(arrSelected); //It will set the multiple selected value to input new_branch
});
});
</script>
You can use the bindParam
or bindValue
methods to help prepare your statement.
It makes things more clear on first sight instead of doing $check->execute(array(':name' => $name));
Especially if you are binding multiple values/variables.
Check the clear, easy to read example below:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname LIMIT 1");
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetch(PDO::FETCH_ASSOC);
$row_id = $check['id'];
// do something
}
If you are expecting multiple rows remove the LIMIT 1
and change the fetch method into fetchAll
:
$q = $db->prepare("SELECT id FROM table WHERE forename = :forename and surname = :surname");// removed limit 1
$q->bindValue(':forename', 'Joe');
$q->bindValue(':surname', 'Bloggs');
$q->execute();
if ($q->rowCount() > 0){
$check = $q->fetchAll(PDO::FETCH_ASSOC);
//$check will now hold an array of returned rows.
//let's say we need the second result, i.e. index of 1
$row_id = $check[1]['id'];
// do something
}
Just to go a little bit further in the matter, you can also set a bitmap directly, like this:
ImageView imageView = new ImageView(this);
Bitmap bImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.my_image);
imageView.setImageBitmap(bImage);
Of course, this technique is only useful if you need to change the image.
PHP does not know these Unicode escape sequences. But as unknown escape sequences remain unaffected, you can write your own function that converts such Unicode escape sequences:
function unicodeString($str, $encoding=null) {
if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', create_function('$match', 'return mb_convert_encoding(pack("H*", $match[1]), '.var_export($encoding, true).', "UTF-16BE");'), $str);
}
Or with an anonymous function expression instead of create_function
:
function unicodeString($str, $encoding=null) {
if (is_null($encoding)) $encoding = ini_get('mbstring.internal_encoding');
return preg_replace_callback('/\\\\u([0-9a-fA-F]{4})/u', function($match) use ($encoding) {
return mb_convert_encoding(pack('H*', $match[1]), $encoding, 'UTF-16BE');
}, $str);
}
Its usage:
$str = unicodeString("\u1000");
First create dir /var/run/mysqld
with command:
mkdir -p /var/run/mysqld
then add rigths to the dir
chown mysql:mysql /var/run/mysqld
after this try
mysql -u root
The current answer is only applicable to versions 3.5.4 and before, where select2 fired blur and focus events (select2-focus
& select2-blur
). It attaches a one-time use handler using $.one
to catch the initial focus, and then reattaches it during blur for subsequent uses.
$('.select2').select2({})
.one('select2-focus', OpenSelect2)
.on("select2-blur", function (e) {
$(this).one('select2-focus', OpenSelect2)
})
function OpenSelect2() {
var $select2 = $(this).data('select2');
setTimeout(function() {
if (!$select2.opened()) { $select2.open(); }
}, 0);
}
I tried both of @irvin-dominin-aka-edward's answers, but also ran into both problems (having to click the dropdown twice, and that Firefox throws 'event is not defined').
I did find a solution that seems to solve the two problems and haven't run into other issue yet. This is based on @irvin-dominin-aka-edward's answers by modifying the select2Focus function so that instead of executing the rest of the code right away, wrap it in setTimeout.
$('.select2').select2({})_x000D_
.one('select2-focus', OpenSelect2)_x000D_
.on("select2-blur", function (e) {_x000D_
$(this).one('select2-focus', OpenSelect2)_x000D_
})_x000D_
_x000D_
function OpenSelect2() {_x000D_
var $select2 = $(this).data('select2');_x000D_
setTimeout(function() {_x000D_
if (!$select2.opened()) { $select2.open(); }_x000D_
}, 0); _x000D_
}
_x000D_
body {_x000D_
margin: 2em;_x000D_
}_x000D_
_x000D_
.form-control {_x000D_
width: 200px; _x000D_
margin-bottom: 1em;_x000D_
padding: 5px;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
select {_x000D_
border: 1px solid #aaa;_x000D_
border-radius: 4px;_x000D_
height: 28px;_x000D_
}
_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.css">_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/select2/3.5.4/select2.js"></script>_x000D_
_x000D_
_x000D_
<div class="form-control">_x000D_
<label for="foods1" >Normal</label>_x000D_
<select id="foods1" >_x000D_
<option value=""></option>_x000D_
<option value="1">Apple</option>_x000D_
<option value="2">Banana</option>_x000D_
<option value="3">Carrot</option>_x000D_
<option value="4">Donut</option>_x000D_
</select>_x000D_
</div>_x000D_
_x000D_
<div class="form-control">_x000D_
<label for="foods2" >Select2</label>_x000D_
<select id="foods2" class="select2" >_x000D_
<option value=""></option>_x000D_
<option value="1">Apple</option>_x000D_
<option value="2">Banana</option>_x000D_
<option value="3">Carrot</option>_x000D_
<option value="4">Donut</option>_x000D_
</select>_x000D_
</div>
_x000D_
That should be considered a very bad programming practice to call PHP code from a database trigger. If you will explain the task you are trying to solve using such "mad" tricks, we might provide a satisfying solution.
ADDED 19.03.2014:
I should have added some reasoning earlier, but only found time to do this now. Thanks to @cmc for an important remark. So, PHP triggers add the following complexities to your application:
Adds a certain degree of security problems to the application (external PHP script calls, permission setup, probably SELinux setup etc) as @Johan says.
Adds additional level of complexity to your application (to understand how database works you now need to know both SQL and PHP, not only SQL) and you will have to debug PHP also, not only SQL.
Adds additional point of failure to your application (PHP misconfiguration for example), which needs to be diagnosied also ( I think trigger needs to hold some debug code which will log somwewhere all insuccessful PHP interpreter calls and their reasons).
Adds additional point of performance analysis. Each PHP call is expensive, since you need to start interpreter, compile script to bytecode, execute it etc. So each query involving this trigger will execute slower. And sometimes it will be difficult to isolate query performance problems since EXPLAIN doesn't tell you anything about query being slower because of trigger routine performance. And I'm not sure how trigger time is dumped into slow query log.
Adds some problems to application testing. SQL can be tested pretty easily. But to test SQL + PHP triggers, you will have to apply some skill.
Don’t need to specify a type
value of “text/css”
Every time you link to a CSS file:
<link rel="stylesheet" type="text/css" href="file.css">
You can simply write:
<link rel="stylesheet" href="file.css">
java.lang.UnsupportedClassVersionError
happens because of a higher JDK during compile time and lower JDK during runtime.
Here's the list of versions:
Java SE 9 = 53,
Java SE 8 = 52,
Java SE 7 = 51,
Java SE 6.0 = 50,
Java SE 5.0 = 49,
JDK 1.4 = 48,
JDK 1.3 = 47,
JDK 1.2 = 46,
JDK 1.1 = 45
In swift 5
,
let font = UIFont.systemFont(ofSize: 16)
UISegmentedControl.appearance().setTitleTextAttributes([NSAttributedString.Key.font: font], for: .normal)
You can easily create a symbolic link as below,
sudo ln -s /opt/flutter/bin/flutter /usr/bin/flutter
I had moved flutter into /opt/ folder after downloading, so replace with the path you have flutter directory.
flutter command should work even after rebooting your machine.
This code creates the file temp.xls in the desktop but it uses the SpecialFolders property, which is very useful sometimes!
set WshShell = WScript.CreateObject("WScript.Shell")
strDesktop = WshShell.SpecialFolders("Desktop")
set objExcel = CreateObject("Excel.Application")
Set objWorkbook = objExcel.Workbooks.Add()
objWorkbook.SaveAs(strDesktop & "\temp.xls")
You could use Timestamp.valueOf(String)
. The documentation states that it understands timestamps in the format yyyy-mm-dd hh:mm:ss[.f...]
, so you might need to change the field separators in your incoming string.
Then again, if you're going to do that then you could just parse it yourself and use the setNanos
method to store the microseconds.
I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).
Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx
If you do "docker attach "container id" you get into the container. To exit from the container without stopping the container you need to enter Ctrl+P+Q
Why not just use the native way of accessing the strings of a enum.
enum e {
WHY,
NOT,
USE,
NATIVE
}
e[e.WHY] // this returns string 'WHY'
Read the Request.Form NameValueCollection and process your logic accordingly:
NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
userName = nvc["txtUserName"];
}
if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
password = nvc["txtPassword"];
}
//Process login
CheckLogin(userName, password);
... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.
you should use the break statement
usually it's use this way
$i = 0;
foreach($data as $key => $row){
if(++$i > 2) break;
}
on the same fashion the continue statement exists if you need to skip some items.
You can use kill -0
for checking whether a particular pid is running or not.
Assuming, you have list of pid
numbers in a file called pid
in pwd
while true;
do
if [ -s pid ] ; then
for pid in `cat pid`
do
echo "Checking the $pid"
kill -0 "$pid" 2>/dev/null || sed -i "/^$pid$/d" pid
done
else
echo "All your process completed" ## Do what you want here... here all your pids are in finished stated
break
fi
done
Something like this would do:
xargs cat <filenames.txt
The xargs
program reads its standard input, and for each line of input runs the cat
program with the input lines as argument(s).
If you really want to do this in a loop, you can:
for fn in `cat filenames.txt`; do
echo "the next file is $fn"
cat $fn
done
Changing the index variable i
from within the loop is unlikely to do what you expect. You may need to use a while
loop instead, and control the incrementing of the loop variable yourself. Each time around the for
loop, i
is reassigned with the next value from range()
. So something like:
i = 2
while i < n:
if(something):
do something
else:
do something else
i = 2 # restart the loop
continue
i += 1
In my example, the continue
statement jumps back up to the top of the loop, skipping the i += 1
statement for that iteration. Otherwise, i
is incremented as you would expect (same as the for
loop).
.joins
will just joins the tables and brings selected fields in return. if you call associations on joins query result, it will fire database queries again
:includes
will eager load the included associations and add them in memory. :includes
loads all the included tables attributes. If you call associations on include query result, it will not fire any queries
My problem was with extra </div>
tag inside the first tab.
Zambri's answer found here is the best.
File.open("out.txt", '<OPTION>') {|f| f.write("write your stuff here") }
where your options for <OPTION>
are:
r
- Read only. The file must exist.
w
- Create an empty file for writing.
a
- Append to a file.The file is created if it does not exist.
r+
- Open a file for update both reading and writing. The file must exist.
w+
- Create an empty file for both reading and writing.
a+
- Open a file for reading and appending. The file is created if it does not exist.
In your case, w
is preferable.
Today I created a jQuery plugin called jQuery Responsive Headlines that does exactly what you want: it adjusts the font size of a headline to fit inside its containing element (a div, the body or whatever). There are some nice options that you can set to customize the behavior of the plugin and I have also taken the precaution to add support for Ben Altmans Throttle/Debounce functionality to increase performance and ease the load on the browser/computer when the user resizes the window. In it's most simple use case the code would look like this:
$('h1').responsiveHeadlines();
...which would turn all h1 on the page elements into responsive one-line headlines that adjust their sizes to the parent/container element.
You'll find the source code and a longer description of the plugin on this GitHub page.
Good luck!
Inspired by cyptus's answer I used
_dbContext.Database.CreateIfNotExists();
on EF6 before the first database contact (before DB seeding).
1 You can use string.Replace
method
var sample = "testtesttesttest#replace#testtesttest";
var result = sample.Replace("#replace#", yourValue);
2 You can also use string.Format
var result = string.Format("your right part {0} Your left Part", yourValue);
3 You can use Regex class
There is more than one way to do this.
Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html
At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.
If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.
In my case, I want to add a column to a Primary key (column4). I used this script to add column4
ALTER TABLE TableA
DROP CONSTRAINT [PK_TableA]
ALTER TABLE TableA
ADD CONSTRAINT [PK_TableA] PRIMARY KEY (
[column1] ASC,
[column2] ASC,
[column3] ASC,
[column4] ASC
)
If you're using Python 3.6 on Amazon Linux (based on RHEL, but the RHEL answers given here didn't work):
sudo yum install python36-devel
You can copy all contents of myhtml
to String
as follows:
Scanner myScanner = null;
try
{
myScanner = new Scanner(myhtml);
String contents = myScanner.useDelimiter("\\Z").next();
}
finally
{
if(myScanner != null)
{
myScanner.close();
}
}
Ofcourse, you can add a catch
block to handle exceptions properly.
On a Unix/Linux box you could just run 'wget' but this is not really an option if you're writing a cross-platform client. Of course this assumes that you don't really want to do much with the data you download between the point of downloading it and it hitting the disk.
It’s less confusing to always use an escaped hyphen, so that it doesn't have to be positionally dependent. That’s a \-
inside the bracketed character class.
But there’s something else to consider. Some of those enumerated characters should possibly be written differently. In some circumstances, they definitely should.
This comparison of regex flavors says that C? can use some of the simpler Unicode properties. If you’re dealing with Unicode, you should probably use the general category \p{L}
for all possible letters, and maybe \p{Nd}
for decimal numbers. Also, if you want to accomodate all that dash punctuation, not just HYPHEN-MINUS, you should use the \p{Pd}
property. You might also want to write that sequence of whitespace characters simply as \s
, assuming that’s not too general for you.
All together, that works out to apattern of [\p{L}\p{Nd}\p{Pd}!$*]
to match any one character from that set.
I’d likely use that anyway, even if I didn’t plan on dealing with the full Unicode set, because it’s a good habit to get into, and because these things often grow beyond their original parameters. Now when you lift it to use in other code, it will still work correctly. If you hard-code all the characters, it won’t.
Alternatively, if you are able to use external libraries, you can use filehound
. It supports callbacks, promises and sync calls.
Using promises:
const Filehound = require('filehound');
Filehound.create()
.path("MyFolder")
.directory() // only search for directories
.find()
.then((subdirectories) => {
console.log(subdirectories);
});
Using callbacks:
const Filehound = require('filehound');
Filehound.create()
.path("MyFolder")
.directory()
.find((err, subdirectories) => {
if (err) return console.error(err);
console.log(subdirectories);
});
Sync call:
const Filehound = require('filehound');
const subdirectories = Filehound.create()
.path("MyFolder")
.directory()
.findSync();
console.log(subdirectories);
For further information (and examples), check out the docs: https://github.com/nspragg/filehound
Disclaimer: I'm the author.
Change the number of @grid-columns
. Then use -offset
. Changing the number of columns will allow you to control the amount of space between columns. E.g.
variables.less (approx line 294).
@grid-columns: 20;
someName.html
<div class="row">
<div class="col-md-4 col-md-offset-1">First column</div>
<div class="col-md-13 col-md-offset-1">Second column</div>
</div>
"Validation injection without submit looping":
I just want to check reCaptcha and some other stuff before HTML5 validation, so I did something like that (the validation function returns true or false):
$(document).ready(function(){
var application_form = $('form#application-form');
application_form.on('submit',function(e){
if(application_form_extra_validation()===true){
return true;
}
e.preventDefault();
});
});
You can use IIF
(I think from SQL Server 2012)
SELECT IIF(B.[STAT] IS NULL, C.[EVENT DATE]+10, '-') AS [DATE]
Write to a file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileOutputStream fos = null;
try {
fos = new FileOutputStream(filepath);
byte[] buffer = "This will be writtent in test.txt".getBytes();
fos.write(buffer, 0, buffer.length);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fos != null)
fos.close();
}
Read from file test.txt:
String filepath ="/mnt/sdcard/test.txt";
FileInputStream fis = null;
try {
fis = new FileInputStream(filepath);
int length = (int) new File(filepath).length();
byte[] buffer = new byte[length];
fis.read(buffer, 0, length);
fis.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}finally{
if(fis != null)
fis.close();
}
Note: don't forget to add these two permission in AndroidManifest.xml
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
File.GetLastWriteTime
to Get last modified
File.CreationTime
to get Created time
I suppose there are applications written in C# running fast, as well as there are more C++ written apps running fast (well C++ just older... and take UNIX too...)
- the question indeed is - what is that thing, users and developers are complaining about ...
Well, IMHO, in case of C# we have very comfort UI, very nice hierarchy of libraries, and whole interface system of CLI. In case of C++ we have templates, ATL, COM, MFC and whole shebang of alreadyc written and running code like OpenGL, DirectX and so on... Developers complains of indeterminably risen GC calls in case of C# (means program runs fast, and in one second - bang! it's stuck).
To write code in C# very simple and fast (not to forget that also increase chance of errors.
In case of C++, developers complains of memory leaks, - means crushes, calls between DLLs, as well as of "DLL hell" - problem with support and replacement libraries by newer ones...
I think more skill you'll have in the programming language, the more quality (and speed) will characterize your software.
1. git remote add origin [email protected]:User/UserRepo.git
git init
.origin
is an alias/alternate name for your remote repository so that you don't have to type the entire path for remote every time and henceforth you are declaring that you will use this name(origin) to refer to your remote. This name could be anything.git remote -v
OR git remote get-url origin
2. git remote set-url origin [email protected]:User/UserRepo.git
This command means that if at any stage you wish to change the location of your repository(i.e if you made a mistake while adding the remote path using the git add
command) the first time, you can easily go back & "reset(update) your current remote repository path" by using the above command.
3. git push -u remote master
This command simply pushes your files to the remote repository.Git has a concept of something known as a "branch", so by default everything is pushed to the master branch unless explicitly specified an alternate branch.
To know about the list of all branches you have in your repository type :git branch
Where ever you use a <button>
element by default it considers that button type="submit"
so if you define the button type="button"
then it won't consider that <button>
as submit button.
You could try a subquery:
SELECT DISTINCT TEST.* FROM (
SELECT rsc.RadioServiceCodeId,
rsc.RadioServiceCode + ' - ' + rsc.RadioService as RadioService
FROM sbi_l_radioservicecodes rsc
INNER JOIN sbi_l_radioservicecodegroups rscg ON rsc.radioservicecodeid = rscg.radioservicecodeid
WHERE rscg.radioservicegroupid IN
(select val from dbo.fnParseArray(@RadioServiceGroup,','))
OR @RadioServiceGroup IS NULL
ORDER BY rsc.RadioServiceCode,rsc.RadioServiceCodeId,rsc.RadioService
) as TEST
Try this:
var classname = ("" + obj.constructor).split("function ")[1].split("(")[0];
In addition to the setCustomSelectionActionModeCallback, and disabled long-click solutions, it's necessary to prevent the PASTE/REPLACE menus from appearing when the text selection handle is clicked, as per the image below:
The solution lies in preventing PASTE/REPLACE menu from appearing in the show()
method of the (non-documented) android.widget.Editor
class. Before the menu appears, a check is done to if (!canPaste && !canSuggest) return;
. The two methods that are used as the basis to set these variables are both in the EditText
class:
isSuggestionsEnabled()
is public, and may thus be overridden.canPaste()
is not, and thus must be hidden by introducing a function of the same name in the derived class.A more complete answer is available here.
Here's a quick sample:
//Create process
System.Diagnostics.Process pProcess = new System.Diagnostics.Process();
//strCommand is path and file name of command to run
pProcess.StartInfo.FileName = strCommand;
//strCommandParameters are parameters to pass to program
pProcess.StartInfo.Arguments = strCommandParameters;
pProcess.StartInfo.UseShellExecute = false;
//Set output of program to be written to process output stream
pProcess.StartInfo.RedirectStandardOutput = true;
//Optional
pProcess.StartInfo.WorkingDirectory = strWorkingDirectory;
//Start the process
pProcess.Start();
//Get program output
string strOutput = pProcess.StandardOutput.ReadToEnd();
//Wait for process to finish
pProcess.WaitForExit();
setTimeout(() => {
this.setState({ position: 1 });
}, 3000);
The above would also work because the ES6 arrow function does not change the context of this
.
We can create such type of array to use this last value will be updated into column or key value and we will get unique value from the array...
$array = array (1,3,4,2,1,7,4,9,7,5,9);
$data=array();
foreach($array as $value ){
$data[$value]= $value;
}
array_keys($data);
OR
array_values($data);
The syntax is as follows :
import urllib3
urllib3.request.urlencode({"user" : "john" })
In another world, in Event Sourcing, an Aggregate(Root) is a different concept. Event Sourcing might be encountered together with CQRS, DDD etc.
In Event Sourcing an Aggregate is an object for which the state (fields) is not mapped to a record in a database as we are used to think in SQL/JPA world.
Is not a group of related entities.
It is a group of related records like in a history table.
GiftCard.amount is one field in a GiftCard Aggregate, but this field is mapped to all the events, like card-redeemed (take money from the card) ever created.
So the source of data for your Aggregate is not a record in a database but the complete list of events ever created for that specific aggregate. We say we event sourced the aggregate.
Now we can ask ourselves how is it done? Who is aggregating these events so we are operating still with one field e.g GiftCard.amount? We might be expecting that amount to be a Collection and not a big-decimal type.
Is the event sourcing engine, doing the work, who might simply replay all the events in the creation order. But this is out of the scope for this thread.
Bjarne Stroustrup's Answer to this question:
That sounds like an interview question. Is it true? How would you know? It is a bad idea to answer questions about efficiency without first doing some measurements, so it is important to know how to measure.
So, I tried with a vector of a million integers and got:
Already sorted 32995 milliseconds
Shuffled 125944 milliseconds
Already sorted 18610 milliseconds
Shuffled 133304 milliseconds
Already sorted 17942 milliseconds
Shuffled 107858 milliseconds
I ran that a few times to be sure. Yes, the phenomenon is real. My key code was:
void run(vector<int>& v, const string& label)
{
auto t0 = system_clock::now();
sort(v.begin(), v.end());
auto t1 = system_clock::now();
cout << label
<< duration_cast<microseconds>(t1 — t0).count()
<< " milliseconds\n";
}
void tst()
{
vector<int> v(1'000'000);
iota(v.begin(), v.end(), 0);
run(v, "already sorted ");
std::shuffle(v.begin(), v.end(), std::mt19937{ std::random_device{}() });
run(v, "shuffled ");
}
At least the phenomenon is real with this compiler, standard library, and optimizer settings. Different implementations can and do give different answers. In fact, someone did do a more systematic study (a quick web search will find it) and most implementations show that effect.
One reason is branch prediction: the key operation in the sort algorithm is “if(v[i] < pivot]) …”
or equivalent. For a sorted sequence that test is always true whereas, for a random sequence, the branch chosen varies randomly.
Another reason is that when the vector is already sorted, we never need to move elements to their correct position. The effect of these little details is the factor of five or six that we saw.
Quicksort (and sorting in general) is a complex study that has attracted some of the greatest minds of computer science. A good sort function is a result of both choosing a good algorithm and paying attention to hardware performance in its implementation.
If you want to write efficient code, you need to know a bit about machine architecture.
Why don't you use a combination of HTML/CSS instead? Image maps are obsolete.
This btw is Search Engine Optimised as well :)
Source code follows:
.image-map {
background: url('https://www.google.com/images/branding/googlelogo/1x/googlelogo_color_272x92dp.png');
width: 272px;
height: 92px;
display: block;
position: relative;
margin-top:10px;
float: left;
}
.image-map > a.map {
position: absolute;
display: block;
border: 1px solid green;
}
_x000D_
<div class="image-map">
<a class="map" rel="G" style="top: 0px; left: 0px; width: 70px; height: 95px;" href="#"></a>
<a class="map" rel="o" style="top: 0px; left: 70px; width: 50px; height: 95px" href="#"></a>
<a class="map" rel="o" style="top: 0px; left: 120px; width: 50px; height: 95px" href="#"></a>
<a class="map" rel="g" style="top: 0px; left: 170px; width: 40px; height: 95px" href="#"></a>
<a class="map" rel="l" style="top: 0px; left: 210px; width: 20px; height: 95px" href="#"></a>
<a class="map" rel="e" style="top: 0px; left: 230px; width: 40px; height: 95px" href="#"></a>
</div>
_x000D_
EDIT:
After the numerous negative points this answer has received I have to come back and say that I can clearly see that you don't agree with my answer, but I personally still believe that is a better option than image maps.
Sure it cannot do polygons, it might have issues on manual page zoom, but personally I feel image maps are obsolete although still on the html5 specification. (It makes make more sense nowadays to try and replicate them using html5 canvas instead)
However I guess the target audience for this question does not agree with me.
You could also check this Are HTML Image Maps still used? and see the most highly voted answer just for reference.