To install specific version of laravel try this & simply command on terminal
composer create-project --prefer-dist laravel/laravel:5.5.0 {dir-name}
Here is an example to move the mysqld tmpdir from /tmp to /run/mysqld which already exists on Ubuntu 13.04 and is a tmpfs (memory/ram):
sudo vim /etc/mysql/conf.d/local.cnf
Add:
[mysqld]
tmpdir = /run/mysqld
Then:
sudo service mysql restart
Verify:
SHOW VARIABLES LIKE 'tmpdir';
==================================================================
If you get an error on MySQL restart, you may have AppArmor enabled:
sudo vim /etc/apparmor.d/local/usr.sbin.mysqld
Add:
# Site-specific additions and overrides for usr.sbin.mysqld.
# For more details, please see /etc/apparmor.d/local/README.
/run/mysqld/ r,
/run/mysqld/** rwk,
Then:
sudo service apparmor reload
sources: http://2bits.com/articles/reduce-your-servers-resource-usage-moving-mysql-temporary-directory-ram-disk.html, https://blogs.oracle.com/jsmyth/entry/apparmor_and_mysql
YOUR-COMMAND &> YOUR-LOG.log &
This should run the command and assign a process id you can simply tail -f YOUR-LOG.log to see results written to it as they happen. you can log out anytime and the process will carry on
Try the code below to prevent the default behaviour scrolling back to the top of the page
$(document).ready(function() {
$('.galleryicon').live("click", function(e) { // the (e) represent the event
$('#mainImage').hide();
$('#cakebox').css('background-image', "url('ajax-loader.gif')");
var i = $('<img />').attr('src',this.href).load(function() {
$('#mainImage').attr('src', i.attr('src'));
$('#cakebox').css('background-image', 'none');
$('#mainImage').fadeIn();
});
e.preventDefault(); //Prevent default click action which is causing the
return false; //page to scroll back to the top
});
});
For more information on event.preventDefault() have a look here at the official documentation.
SELECT
t1.*
FROM
table_name AS t1
LEFT JOIN table_name AS t2 ON (
t2.group_by_column = t1.group_by_column
-- group_by_column is the column you would use in the GROUP BY statement
AND
t2.order_by_column < t1.order_by_column
-- order_by_column is column you would use in the ORDER BY statement
-- usually is the autoincremented key column
)
WHERE
t2.group_by_column IS NULL;
With MySQL v8+ you could use window functions
setting the overflow
should take care of it, but you need to set the height of Content
also. If the height attribute is not set, the div will grow vertically as tall as it needs to, and scrollbars wont be needed.
See Example: http://jsfiddle.net/ftkbL/1/
Tkinter is a GUI module for python. you can use it to make GUI based applications in python. Tkinter provides several GUI widgets like buttons,menu, canvas,text,frame,label etc. to develop desktop applications.Though Tkinter is very popular and is included with windows, macosx install of python, There are also alternative choices like pyQt, wxPython...
In this tutorial we will see how to install it on linux and use it with an example.
First, check if you have python installed and also check its version
Open up your terminal and type python. if its installed then it will show information like version, help... check your version (mine is python 2.7.9)
aman@vostro:~$ python Python 2.7.9 (default, Apr 2 2015, 15:33:21) [GCC 4.9.2] on linux2 Type "help", "copyright", "credits" or "license" for more information.
If you don't have python then install it sudo apt-get install python
If you want to install python 3 then enter the following. If you are a newbie, I would recommend python 2 instead of python 3. Python 2 is still very popular and many apps are made on it. On ubuntu python2 is still the default sudo apt-get install python3
Finally, Install Tkinter
sudo apt-get install python-tk
for python 3
sudo apt-get install python3-tk
How to Use it
Now, lets check if Tkinter is working well with this little example
open your terminal and enter into your python shell. python
for python3 python3
if python was installed correctly you will get a >>> prompt. aman@vostro:~$ python
Python 2.7.9 (default, Apr 2 2015, 15:33:21)
[GCC 4.9.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>>
Now import Tkinter module. it wont show any error if it got imported correctly. NOTE: Make sure you type Tkinter (not tkinter) in python2 and tkinter (not Tkinter) in python3.
>>>import Tkinter
Now, just to check you can create an empty window using Tkinter.
>>>Tkinter.Tk()
$('.formData').attr('value','YOUR_VALUE')
Based on the workflow described by @tschundeee and @Debilski’s update 1, I automated the procedure and added cleanup in this script.
Download it, put it in your path and brewv <formula_name> <wanted_version>
. For the specific OP, it would be:
cd path/to/downloaded/script/
./brewv postgresql 8.4.4
:)
NaN
means "Not a number." It's a special floating point value that means that the result of an operation was not defined or not representable as a real number.
See here for more explanation of this value.
If you get 'Access violation at address 00000000.', you are calling a function pointer that hasn't been assigned - possibly an event handler or a callback function.
for example
type
TTest = class(TForm);
protected
procedure DoCustomEvent;
public
property OnCustomEvent : TNotifyEvent read FOnCustomEvent write FOnCustomEvent;
end;
procedure TTest.DoCustomEvent;
begin
FOnCustomEvent(Self);
end;
Instead of
procedure TTest.DoCustomEvent;
begin
if Assigned(FOnCustomEvent) then // need to check event handler is assigned!
FOnCustomEvent(Self);
end;
If the error is in a third party component, and you can track the offending code down, use an empty event handler to prevent the AV.
Regarding coding style:
Most coding standards no matter language ban multiple return statements from a single function as bad practice.
(Although personally I would say there are several cases where multiple return statements do make sense: text/data protocol parsers, functions with extensive error handling etc)
The consensus from all those industry coding standards is that the expression should be written as:
int result;
if(A > B)
{
result = A+1;
}
else
{
result = A-1;
}
return result;
Regarding efficiency:
The above example and the two examples in the question are all completely equivalent in terms of efficiency. The machine code in all these cases have to compare A > B, then branch to either the A+1 or the A-1 calculation, then store the result of that in a CPU register or on the stack.
EDIT :
Sources:
See svn diff
in the manual:
svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php
Updated for the release of Xcode 7 GM. It works as one would hope now--thanks Apple!
enum Rank:Int {
case Ace = 1, Two, Three, Four, Five, Six, Seven, Eight, Nine, Ten, Jack, Queen, King
}
let r = Rank.Ace
print(r) // prints "Ace"
print("Rank: \(r)!") // prints "Rank: Ace!"
For JQuery UI versions before 1.9: ui.index
from the event
is what you want.
For JQuery UI 1.9 or later: see the answer by Giorgio Luparia, below.
I tried this commands in my PC.It is working fine....
To open notepad in minimized mode:
start /min "" "C:\Windows\notepad.exe"
To open MS word in minimized mode:
start /min "" "C:\Program Files\Microsoft Office\Office14\WINWORD.EXE"
According to official documentation, you can set or remove the "executable" flag on any tracked file using update-index
sub-command.
To set the flag, use following command:
git update-index --chmod=+x path/to/file
To remove it, use:
git update-index --chmod=-x path/to/file
Under the hood
While this looks like the regular unix files permission system, actually it is not. Git maintains a special "mode" for each file in its internal storage:
100644
for regular files100755
for executable onesYou can visualize it using ls-file
subcommand, with --stage
option:
$ git ls-files --stage
100644 aee89ef43dc3b0ec6a7c6228f742377692b50484 0 .gitignore
100755 0ac339497485f7cc80d988561807906b2fd56172 0 my_executable_script.sh
By default, when you add a file to a repository, Git will try to honor its filesystem attributes and set the correct filemode accordingly. You can disable this by setting core.fileMode
option to false:
git config core.fileMode false
Troubleshooting
If at some point the Git filemode is not set but the file has correct filesystem flag, try to remove mode and set it again:
git update-index --chmod=-x path/to/file
git update-index --chmod=+x path/to/file
Bonus
Starting with Git 2.9, you can stage a file AND set the flag in one command:
git add --chmod=+x path/to/file
you can also print the data onto your HTML/JSP document. like:-
<!DOCTYPE html>
<html>
<head>
<title>Jsp Sample</title>
<%@page import="java.sql.*;"%>
</head>
<body bgcolor=yellow>
<%
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=(Connection)DriverManager.getConnection(
"jdbc:mysql://localhost:3306/forum","root","root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from student;");
%><table border=1 align=center style="text-align:center">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>SKILL</th>
<th>ACTION</th>
</tr>
</thead>
<tbody>
<%while(rs.next())
{
%>
<tr>
<td><%=rs.getString("id") %></td>
<td><%=rs.getString("name") %></td>
<td><%=rs.getString("skill") %></td>
<td><%=rs.getString("action") %></td>
</tr>
<%}%>
</tbody>
</table><br>
<%}
catch(Exception e){
out.print(e.getMessage());%><br><%
}
finally{
st.close();
con.close();
}
%>
</body>
</html>
<!--executeUpdate() mainupulation and executeQuery() for retriving-->
Here's a runnable snippet to help you generate mailto: links with optional subject and body.
function generate() {_x000D_
var email = $('#email').val();_x000D_
var subject = $('#subject').val();_x000D_
var body = $('#body').val();_x000D_
_x000D_
var mailto = 'mailto:' + email;_x000D_
var params = {};_x000D_
if (subject) {_x000D_
params.subject = subject;_x000D_
}_x000D_
if (body) {_x000D_
params.body = body;_x000D_
}_x000D_
if (params) {_x000D_
mailto += '?' + $.param(params);_x000D_
}_x000D_
_x000D_
var $output = $('#output');_x000D_
$output.val(mailto);_x000D_
$output.focus();_x000D_
$output.select();_x000D_
document.execCommand('copy');_x000D_
}_x000D_
_x000D_
$(document).ready(function() {_x000D_
$('#generate').on('click', generate);_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="text" id="email" placeholder="email address" /><br/>_x000D_
<input type="text" id="subject" placeholder="Subject" /><br/>_x000D_
<textarea id="body" placeholder="Body"></textarea><br/>_x000D_
<button type="button" id="generate">Generate & copy to clipboard</button><br/>_x000D_
<textarea id="output">Output</textarea>
_x000D_
It can enable some new optimisations. const
traditionally is a hint for the type system, and cannot be used for optimisation (e.g. a const
member function can const_cast
and modify the object anyway, legally, so const
cannot be trusted for optimisation).
constexpr
means the expression really is constant, provided the inputs to the function are const. Consider:
class MyInterface {
public:
int GetNumber() const = 0;
};
If this is exposed in some other module, the compiler can't trust that GetNumber()
won't return different values each time it's called - even consecutively with no non-const calls in between - because const
could have been cast away in the implementation. (Obviously any programmer who did this ought to be shot, but the language permits it, therefore the compiler must abide by the rules.)
Adding constexpr
:
class MyInterface {
public:
constexpr int GetNumber() const = 0;
};
The compiler can now apply an optimisation where the return value of GetNumber()
is cached and eliminate additional calls to GetNumber()
, because constexpr
is a stronger guarantee that the return value won't change.
To extract number :
var arrNumber = new Array();
$('input[type=number]').each(function(){
arrNumber.push($(this).val());
})
To extract text:
var arrText= new Array();
$('input[type=text]').each(function(){
arrText.push($(this).val());
})
.map
implementationvar arrText= $('input[type=text]').map(function(){
return this.value;
}).get();
I looked over everyone's input above, which was very useful, and made a function which was appropriate for my own application. The function is really only evaluating that the user's input is not a "0", but it was good enough for my purpose. Hope this helps!
#include<stdio.h>
int iFunctErrorCheck(int iLowerBound, int iUpperBound){
int iUserInput=0;
while (iUserInput==0){
scanf("%i", &iUserInput);
if (iUserInput==0){
printf("Please enter an integer (%i-%i).\n", iLowerBound, iUpperBound);
getchar();
}
if ((iUserInput!=0) && (iUserInput<iLowerBound || iUserInput>iUpperBound)){
printf("Please make a valid selection (%i-%i).\n", iLowerBound, iUpperBound);
iUserInput=0;
}
}
return iUserInput;
}
I faced the same problem while executing a curl.
I got it right when I changed the following in the php.ini
file:
max_execution_time = 1000 ;
and also
max_input_time = 1000 ;
Probably your problem should be solved by making above two changes and restarting the apache server.
Even after changing the above the problem persists and if you think it's because of some database operation using mysql you can try changing this also:
mysql.connect_timeout = 1000 ; // this is not neccessary
All this should be changed in php.ini file and apache server should be restarted to see the changes.
If you like HTML tags more than markdown + center alignment:
<div align="center">_x000D_
<a href="https://www.youtube.com/watch?v=YOUTUBE_VIDEO_ID_HERE"><img src="https://img.youtube.com/vi/YOUTUBE_VIDEO_ID_HERE/0.jpg" alt="IMAGE ALT TEXT"></a>_x000D_
</div>
_x000D_
I solve with this:
Startup.cs
public void ConfigureServices(IServiceCollection services)
{
services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
{
ClientCertificateOptions = ClientCertificateOption.Manual,
ServerCertificateCustomValidationCallback =
(httpRequestMessage, cert, cetChain, policyErrors) =>
{
return true;
}
});
YourService.cs
public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)
{
_appSettings = appSettings.Value;
_clientFactory = clientFactory;
}
var request = new HttpRequestMessage(...
var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");
HttpResponseMessage response = await client.SendAsync(request);
It's very fast to encode, decode and compact
Speed comparison (java based but meaningful nevertheless): https://github.com/eishay/jvm-serializers/wiki/
Also it's an extension to JSON that allow you to skip base64 encoding for byte arrays
Smile encoded strings can be gzipped when space is critical
I have the same issue, where I want to replace the white space in any pdf file to a dash
-
.
But the files were in multiple sub-directories. So, I had to use os.walk()
.
In your case for multiple sub-directories, it could be something like this:
import os
for dpath, dnames, fnames in os.walk('/path/to/directory'):
for f in fnames:
os.chdir(dpath)
if f.startswith('cheese_'):
os.rename(f, f.replace('cheese_', ''))
Date.now() returns a unix timestamp in milliseconds.
const now = Date.now(); // Unix timestamp in milliseconds_x000D_
console.log( now );
_x000D_
Prior to ECMAScript5 (I.E. Internet Explorer 8 and older) you needed to construct a Date object, from which there are several ways to get a unix timestamp in milliseconds:
console.log( +new Date );_x000D_
console.log( (new Date).getTime() );_x000D_
console.log( (new Date).valueOf() );
_x000D_
>>> 2 == 2.0
True
>>> 2 is 2.0
False
Use ==
I had a CASE statement with WHEN column = 'sometext & more text' THEN ....
I replaced it with WHEN column = 'sometext ' || CHR(38) || ' more text' THEN ...
you could also use WHEN column LIKE 'sometext _ more text' THEN ...
(_ is the wildcard for a single character)
my_string = "hello, World"
my_string.sub(/\S/, &:upcase) # => "Hello, World"
I faced the same problem and struggled for an hour to get pass through by reading the documents and the other issues reported in Stack Overflow but I didn't find any answer to it. So, here is the guide to successfully run the phonegap/cordova in Windows Machine.
npm install -g phonegap
(in case of phonegap installation) or run the command npm install -g cordova
(in case of Cordova installation).As the installation gets completed you can notice this:
C:\Users\binaryuser\AppData\Roaming\npm\cordova -> C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova\bin\cordova [email protected] C:\Users\binaryuser\AppData\Roaming\npm\node_modules\cordova +-- [email protected] +-- [email protected] +-- [email protected] +-- [email protected] +-- [email protected] +-- [email protected] ([email protected]) +-- [email protected] ([email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected]) +-- [email protected] +-- [email protected] ([email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected], [email protected])
Notice the above line you can see the path were the file is mentioned. Copy that path. In my case it is C:\Users\binaryuser\AppData\Roaming\npm\cordova
so use cd C:\Users\binaryuser\AppData\Roaming\npm\
and type cordova
. There it is, it finally works.
-g
key value isn't working you have set the Environment Variables path:
Computer
and choose Properties
.Advanced system settings
on the left.Environment Variables
under the Advanced
tab.PATH
variable and click Edit
.OK
.I've faced the same problem because of a cable. I changed my third party USB/lighting cable into original Apple cable, and it worked.
In JavaScript (via jQuery):
$(function() {_x000D_
$("body").click(function(e) {_x000D_
if (e.target.id == "myDiv" || $(e.target).parents("#myDiv").length) {_x000D_
alert("Inside div");_x000D_
} else {_x000D_
alert("Outside div");_x000D_
}_x000D_
});_x000D_
})
_x000D_
#myDiv {_x000D_
background: #ff0000;_x000D_
width: 25vw;_x000D_
height: 25vh;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="myDiv"></div>
_x000D_
Implement the UITextFieldDelegate method like this:
- (BOOL)textFieldShouldReturn:(UITextField *)aTextField
{
[aTextField resignFirstResponder];
return YES;
}
Attributes are static metadata. Assemblies, modules, types, members, parameters, and return values aren't first-class objects in C# (e.g., the System.Type
class is merely a reflected representation of a type). You can get an instance of an attribute for a type and change the properties if they're writable but that won't affect the attribute as it is applied to the type.
Addendum regarding UN*X platforms.
According to the signal(2)
man page on GNU/Linux, the behavior of signal
is not as portable as behavior of sigaction
:
The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.
On System V, system did not block delivery of further instances of the signal and delivery of a signal would reset the handler to the default one. In BSD the semantics changed.
The following variation of previous answer by Dirk Eddelbuettel uses sigaction
instead of signal
:
#include <signal.h>
#include <stdlib.h>
static bool keepRunning = true;
void intHandler(int) {
keepRunning = false;
}
int main(int argc, char *argv[]) {
struct sigaction act;
act.sa_handler = intHandler;
sigaction(SIGINT, &act, NULL);
while (keepRunning) {
// main loop
}
}
You could use "typeof".
if(typeof maybeObject != "undefined")
alert("GOT HERE");
After reading your comment on my previous answer I thought I might put this as a separate answer.
Although I appreciate your approach of trying to do it manually to get a better grasp on jQuery I do still emphasise the merit in using existing frameworks.
That said, here is a solution. I've modified some of your css and and HTML just to make it easier for me to work with
WORKING JS FIDDLE - http://jsfiddle.net/HsEne/15/
This is the jQuery
$(document).ready(function(){
$('.sp').first().addClass('active');
$('.sp').hide();
$('.active').show();
$('#button-next').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':last-child')) {
$('.sp').first().addClass('active');
}
else{
$('.oldActive').next().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
$('#button-previous').click(function(){
$('.active').removeClass('active').addClass('oldActive');
if ( $('.oldActive').is(':first-child')) {
$('.sp').last().addClass('active');
}
else{
$('.oldActive').prev().addClass('active');
}
$('.oldActive').removeClass('oldActive');
$('.sp').fadeOut();
$('.active').fadeIn();
});
});
So now the explanation.
Stage 1
1) Load the script on document ready.
2) Grab the first slide and add a class 'active' to it so we know which slide we are dealing with.
3) Hide all slides and show active slide. So now slide #1 is display block and all the rest are display:none;
Stage 2
Working with the button-next click event.
1) Remove the current active class from the slide that will be disappearing and give it the class oldActive so we know that it is on it's way out.
2) Next is an if statement to check if we are at the end of the slideshow and need to return to the start again. It checks if oldActive (i.e. the outgoing slide) is the last child. If it is, then go back to the first child and make it 'active'. If it's not the last child, then just grab the next element (using .next() ) and give it class active.
3) We remove the class oldActive because it's no longer needed.
4) fadeOut all of the slides
5) fade In the active slides
Step 3
Same as in step two but using some reverse logic for traversing through the elements backwards.
It's important to note there are thousands of ways you can achieve this. This is merely my take on the situation.
SELECT *
FROM
(First_query) AS ONE
LEFT OUTER JOIN
(Second_query ) AS TWO ON ONE.First_query_ID = TWO.Second_Query_ID;
The top answer [[ $b = 5 ]] && a="$c" || a="$d"
should only be used if you are certain there will be no error after the &&
, otherwise it will incorrectly excute the part after the ||
.
To solve that problem I wrote a ternary function that behaves as it should and it even uses the ?
and :
operators:
Edit - new solution
Here is my new solution that does not use $IFS
nor ev(a/i)l
.
function executeCmds()
{
declare s s1 s2 i j k
declare -A cmdParts
declare pIFS=$IFS
IFS=$'\n'
declare results=($(echo "$1" | grep -oP '{ .*? }'))
IFS=$pIFS
s="$1"
for ((i=0; i < ${#results[@]}; i++)); do
s="${s/${results[$i]}/'\0'}"
results[$i]="${results[$i]:2:${#results[$i]}-3}"
results[$i]=$(echo ${results[$i]%%";"*})
done
s="$s&&"
let cmdParts[t]=0
while :; do
i=${cmdParts[t]}
let cmdParts[$i,t]=0
s1="${s%%"&&"*}||"
while :; do
j=${cmdParts[$i,t]}
let cmdParts[$i,$j,t]=0
s2="${s1%%"||"*};"
while :; do
cmdParts[$i,$j,${cmdParts[$i,$j,t]}]=$(echo ${s2%%";"*})
s2=${s2#*";"}
let cmdParts[$i,$j,t]++
[[ $s2 ]] && continue
break
done
s1=${s1#*"||"}
let cmdParts[$i,t]++
[[ $s1 ]] && continue
break
done
let cmdParts[t]++
s=${s#*"&&"}
[[ $s ]] && continue
break
done
declare lastError=0
declare skipNext=false
for ((i=0; i < ${cmdParts[t]}; i++ )) ; do
let j=0
while :; do
let k=0
while :; do
if $skipNext; then
skipNext=false
else
if [[ "${cmdParts[$i,$j,$k]}" == "\0" ]]; then
executeCmds "${results[0]}" && lastError=0 || lastError=1
results=("${results[@]:1}")
elif [[ "${cmdParts[$i,$j,$k]:0:1}" == "!" || "${cmdParts[$i,$j,$k]:0:1}" == "-" ]]; then
[ ${cmdParts[$i,$j,$k]} ] && lastError=0 || lastError=1
else
${cmdParts[$i,$j,$k]}
lastError=$?
fi
if (( k+1 < cmdParts[$i,$j,t] )); then
skipNext=false
elif (( j+1 < cmdParts[$i,t] )); then
(( lastError==0 )) && skipNext=true || skipNext=false
elif (( i+1 < cmdParts[t] )); then
(( lastError==0 )) && skipNext=false || skipNext=true
fi
fi
let k++
[[ $k<${cmdParts[$i,$j,t]} ]] || break
done
let j++
[[ $j<${cmdParts[$i,t]} ]] || break
done
done
return $lastError
}
function t()
{
declare commands="$@"
find="$(echo ?)"
replace='?'
commands="${commands/$find/$replace}"
readarray -d '?' -t statement <<< "$commands"
condition=${statement[0]}
readarray -d ':' -t statement <<< "${statement[1]}"
success="${statement[0]}"
failure="${statement[1]}"
executeCmds "$condition" || { executeCmds "$failure"; return; }
executeCmds "$success"
}
executeCmds
separates each command individually, apart from the ones that should be skipped due to the &&
and ||
operators. It uses []
whenever a command starts with !
or a flag.
There are two ways to pass commands to it:
;
, &&
, and ||
operators.t ls / ? ls qqq '||' echo aaa : echo bbb '&&' ls qq
t 'ls /a ? ls qqq || echo aaa : echo bbb && ls qq'
NB I found no way to pass in &&
and ||
operators as parameters unquoted, as they are illegal characters for function names and aliases, and I found no way to override bash operators.
Old solution - uses ev(a/i)l
function t()
{
pIFS=$IFS
IFS="?"
read condition success <<< "$@"
IFS=":"
read success failure <<< "$success"
IFS=$pIFS
eval "$condition" || { eval "$failure" ; return; }
eval "$success"
}
t ls / ? ls qqq '||' echo aaa : echo bbb '&&' ls qq
t 'ls /a ? ls qqq || echo aaa : echo bbb && ls qq'
there are packages that can simulate interfaces .
you can use es6-interface
I got the same issue and It got solved by installing Oracle 11g client in my machine..
I have not installed any excclusive drivers for it. I am using windows7 with 64 bit. Interestignly, when I navigate into the path Start > Settings > Control Panel > Administrative Tools > DataSources(ODBC) > Drivers. I found only SQL server in it
This solution worked well for me: http://www.apachefriends.org/f/viewtopic.php?f=17&t=50902&p=196185#p196185
Edit /opt/lampp/etc/extra/httpd-xampp.conf and adding Require all granted line at bottom of block <Directory "/opt/lampp/phpmyadmin">
to have the following code:
<Directory "/opt/lampp/phpmyadmin">
AllowOverride AuthConfig Limit
Order allow,deny
Allow from all
Require all granted
</Directory>
As a followup to mouviciel's answer, you could also do this as a for loop, instead of using xargs. I often find xargs cumbersome, especially if I need to do something more complicated in each iteration.
for f in $(find /tmp -name '*.pdf' -or -name '*.doc'); do rm $f; done
As a number of people have commented, this will fail if there are spaces in filenames. You can work around this by temporarily setting the IFS (internal field seperator) to the newline character. This also fails if there are wildcard characters \[?*
in the file names. You can work around that by temporarily disabling wildcard expansion (globbing).
IFS=$'\n'; set -f
for f in $(find /tmp -name '*.pdf' -or -name '*.doc'); do rm "$f"; done
unset IFS; set +f
If you have newlines in your filenames, then that won't work either. You're better off with an xargs based solution:
find /tmp \( -name '*.pdf' -or -name '*.doc' \) -print0 | xargs -0 rm
(The escaped brackets are required here to have the -print0
apply to both or
clauses.)
GNU and *BSD find also has a -delete
action, which would look like this:
find /tmp \( -name '*.pdf' -or -name '*.doc' \) -delete
I know that its a bit of a dead post but I just noticed that this works. It removed both clean-up and cleanup from my output.
> grep -v -e 'clean\-\?up'
> grep --version grep (GNU grep) 2.20
-Wall
and -Wextra
sets the stage in GCC and the subsequent -Wno-unused-variable
may not take effect. For example, if you have:
CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \
-fno-strict-overflow -fno-strict-aliasing \
-Wall -Wextra \
-pthread \
-Wno-unused-label \
-Wno-unused-function \
-Wno-unused-parameter \
-Wno-unused-variable \
$(INC)
then GCC sees the instruction -Wall -Wextra
and seems to ignore -Wno-unused-variable
This can instead look like this below and you get the desired effect of not being stopped in your compile on the unused variable:
CFLAGS += -std=c99 -pedantic -pedantic-errors -Werror -g0 -Os \
-fno-strict-overflow -fno-strict-aliasing \
-pthread \
-Wno-unused-label \
-Wno-unused-function \
$(INC)
There is a good reason it is called a "warning" vs an "error". Failing the compile just because you code is not complete (say you are stubbing the algorithm out) can be defeating.
For simple CRUD operations with a single data access point, I would say go for LINQ if you feel comfortable with the syntax. For more complicated logic I think sprocs are more efficiant performance-wise if you are good at T-SQL and its more advanced operations. You also have the help from Tuning Advisor, SQL Server Profiler, debugging your queries from SSMS etc.
It may be time consuming to get all the application Ids from YARN and kill them one by one. You can use a Bash for loop to accomplish this repetitive task quickly and more efficiently as shown below:
Kill all applications on YARN which are in ACCEPTED state:
for x in $(yarn application -list -appStates ACCEPTED | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
Kill all applications on YARN which are in RUNNING state:
for x in $(yarn application -list -appStates RUNNING | awk 'NR > 2 { print $1 }'); do yarn application -kill $x; done
For Go 1.13+:
go env -w GOPATH=$HOME/go
To set the GOPATH regardless of the GO version add the following line to your ~/.bashrc
:
export GOPATH=$HOME/go
and don't forget to source your .bashrc
file:
source ~/.bashrc
More options on the golang
official wiki:
https://github.com/golang/go/wiki/SettingGOPATH
From the man
page:
-d delim The first character of delim is used to terminate the input line, rather than newline.
You are using -d,
which will terminate the input line on the comma. It will not read the rest of the line. That's why $y is empty.
Full answer to the original question that was talking about a possible different path on local and remote is below
git fetch origin
git diff master -- [local-path] origin/master -- [remote-path]
Assuming the local path is docs/file1.txt and remote path is docs2/file1.txt, use git diff master -- docs/file1.txt origin/master -- docs2/file1.txt
This is adapted from GitHub help page here and Code-Apprentice answer above
There is no "best way" to create an object. Each way has benefits depending on your use case.
The constructor pattern (a function paired with the new
operator to invoke it) provides the possibility of using prototypal inheritance, whereas the other ways don't. So if you want prototypal inheritance, then a constructor function is a fine way to go.
However, if you want prototypal inheritance, you may as well use Object.create
, which makes the inheritance more obvious.
Creating an object literal (ex: var obj = {foo: "bar"};
) works great if you happen to have all the properties you wish to set on hand at creation time.
For setting properties later, the NewObject.property1
syntax is generally preferable to NewObject['property1']
if you know the property name. But the latter is useful when you don't actually have the property's name ahead of time (ex: NewObject[someStringVar]
).
Hope this helps!
Try to add export PATH=$PATH:/home/me/play
in ~/.bashrc file.
You can try
echo implode(', ', (array)$ret);
Here's the GNU version of printf
... you can see it passing in stdout
to vfprintf
:
__printf (const char *format, ...)
{
va_list arg;
int done;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
return done;
}
Here's a link to vfprintf
... all the formatting 'magic' happens here.
The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf
equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)
Working locally... I couldn't get the feeds api to work, but the share api worked pretty much straight away with no problems.
now you can use the last 1.0.0-rc1 this way :
classpath 'com.android.tools.build:gradle:1.0.0-rc1'
This needs Gradle 2.0 if you don't have it Android Studio will ask you to download it
You could use the DirectoryInfo and FileInfo classes.
//GetFiles on DirectoryInfo returns a FileInfo object.
var pdfFiles = new DirectoryInfo("C:\\Documents").GetFiles("*.pdf");
//FileInfo has a Name property that only contains the filename part.
var firstPdfFilename = pdfFiles[0].Name;
Edit
For angular 6.1 and newer, use the KeyValuePipe as suggested by Londeren.
For angular 6.0 and older
To make things easier, you can create a pipe.
import {Pipe, PipeTransform} from '@angular/core';
@Pipe({name: 'getValues'})
export class GetValuesPipe implements PipeTransform {
transform(map: Map<any, any>): any[] {
let ret = [];
map.forEach((val, key) => {
ret.push({
key: key,
val: val
});
});
return ret;
}
}
<li *ngFor="let recipient of map |getValues">
As it it pure, it will not be triggered on every change detection, but only if the reference to the map
variable changes
my two cents for VS 2017:
I can confirm it works in stdafx.h both in these styles:
a)
#pragma once
#define _CRT_SECURE_NO_WARNINGS 1
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
b)
#define _CRT_SECURE_NO_WARNINGS 1
#define _WINSOCK_DEPRECATED_NO_WARNINGS 1
#pragma once
(I have added another define for MSDN network calls..) Of course I do prefer a).
I can confirm that: #define _CRT_SECURE_NO_WARNINGS (without a value) DOES NOT WORK.
PS the real point is to put these defines BEFORE declarations of functions, i.e. before *.h
Change modifier from public to internal. .Net deliberately uses private modifier instead of the public, due to preventing any illegal access to your methods/properties/controls out of your project. In fact, public modifier can accessible wherever, so They are really dangerous. Any body out of your project can access to your methods/properties. But In internal modifier no body (other of your current project) can access to your methods/properties.
Suppose you are creating a project, which has some secret fields. So If these fields being accessible out of your project, it can be dangerous, and against to your initial ideas. As one good recommendation, I can say always use internal modifier instead of public modifier.
But some strange!
I must tell also in VB.Net while our methods/properties are still private, it can be accessible from other forms/class by calling form as a variable with no any problem else.
I don't know why in this programming language behavior is different from C#. As we know both are using same Platform and they claim they are almost same Back end Platform, but as you see, they still behave differently.
But I've solved this problem with two approaches. Either; by using Interface (Which is not a recommend, as you know, Interfaces usually need public modifier, and using a public modifier is not recommend (As I told you above)),
Or
Declare your whole Form in somewhere static class and static variable and there is still internal modifier. Then when you suppose to use that form for showing to users, so pass new Form()
construction to that static class/variable. Now It can be Accessible every where as you wish. But you still need some thing more.
You declare your element internal modifier too in Designer File of Form. While your Form is open, it can be accessible everywhere. It can work for you very well.
Consider This Example.
Suppose you want to access to a Form's TextBox.
So the first job is declaration of a static variable in a static class (The reason of static is ease of access without any using new keywork at future).
Second go to designer class of that Form which supposes to be accessed by other Forms. Change its TextBox modifier declaration from private to internal. Don't worry; .Net never change it again to private modifier after your changing.
Third when you want to call that form to open, so pass the new Form Construction to that static variable-->>static class.
Fourth; from any other Forms (wherever in your project) you can access to that form/control while From is open.
Look at code below (We have three object.
1- a static class (in our example we name it A
)
2 - Any Form else which wants to open the final Form (has TextBox, in our example FormB
).
3 - The real Form which we need to be opened, and we suppose to access to its internal TextBox1
(in our example FormC
).
Look at codes below:
internal static class A
{
internal static FormC FrmC;
}
FormB ...
{
'(...)
A.FrmC = new FormC();
'(...)
}
FormC (Designer File) . . .
{
internal System.Windows.Forms.TextBox TextBox1;
}
You can access to that static Variable (here FormC
) and its internal control (here Textbox1
) wherever and whenever as you wish, while FormC
is open.
Any Comment/idea let me know. I glad to hear from you or any body else about this topic more. Honestly I have had some problems regard to this mentioned problem in past. The best way was the second solution that I hope it can work for you. Let me know any new idea/suggestion.
Statement stmt3 = con.createStatement();
ResultSet rs3 = stmt3.executeQuery("SELECT COUNT(*) AS count FROM "+lastTempTable+" ;");
count = rs3.getInt("count");
If your working at a company, they may be preventing you from downloading outside software and installing it. You may need to install the plugins manually or repoint to an internal mirror repository.
try this one : java.net.URL;
JOptionPane.showMessageDialog(null, getDomainName(new URL("https://en.wikipedia.org/wiki/List_of_Internet_top-level_domains")));
public String getDomainName(URL url){
String strDomain;
String[] strhost = url.getHost().split(Pattern.quote("."));
String[] strTLD = {"com","org","net","int","edu","gov","mil","arpa"};
if(Arrays.asList(strTLD).indexOf(strhost[strhost.length-1])>=0)
strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else if(strhost.length>2)
strDomain = strhost[strhost.length-3]+"."+strhost[strhost.length-2]+"."+strhost[strhost.length-1];
else
strDomain = strhost[strhost.length-2]+"."+strhost[strhost.length-1];
return strDomain;}
Clearly many people have answered upon your query of how to make mongoDb work, I'd answer the second part: Regarding an appropriate GUI for mongoDB
My suggestion is, go for MongoChef (now Studio 3T)
You can easily install and use it.
You might want want to refer to (from 03:10- to 08:50): https://www.youtube.com/watch?v=0ws3oIyqieY&index=2&list=PLS1QulWo1RIZtR6bncmSaH8fB81oRl6MP
For a step by step guide to the GUI tool.
If you just want simple parallelism, you can do this:
var bag = new ConcurrentBag<object>();
var tasks = myCollection.Select(async item =>
{
// some pre stuff
var response = await GetData(item);
bag.Add(response);
// some post stuff
});
await Task.WhenAll(tasks);
var count = bag.Count;
If you need something more complex, check out Stephen Toub's ForEachAsync
post.
The second approach is right to execute JavaScript code after the page has finished loading - but you don't actually execute JavaScript code there, you inserted plain HTML.
The first thing works, but loads the JavaScript immediately and clears the page (so your tag will be there - but nothing else).
(Plus: language="javascript" has been deprecated for years, use type="text/javascript" instead!)
To get that working, you have to use the DOM manipulating methods included in JavaScript. Basically you'll need something like this:
var scriptElement=document.createElement('script');
scriptElement.type = 'text/javascript';
scriptElement.src = filename;
document.head.appendChild(scriptElement);
Bound method = instance method
Unbound method = static method.
ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
executor.schedule(yourRunnable, 1L, TimeUnit.MINUTES);
...
// when done...
executor.shutdown();
If you're referring to what happens when you echo something, the single quotes will literally echo what you have between them, while the double quotes will evaluate variables between them and output the value of the variable.
For example, this
#!/bin/sh
MYVAR=sometext
echo "double quotes gives you $MYVAR"
echo 'single quotes gives you $MYVAR'
will give this:
double quotes gives you sometext
single quotes gives you $MYVAR
Two ways to achieve it.
1) Need to start the dialer via code, without user interaction.
You need Action_Dial
,
use below code it will open Dialer with number specified
Intent intent = new Intent(Intent.ACTION_DIAL);
intent.setData(Uri.parse("tel:0123456789"));
startActivity(intent);
The 'tel:' prefix is required, otherwhise the following exception will be thrown: java.lang.IllegalStateException: Could not execute method of the activity.
Action_Dial doesn't require any permission.
If you want to initiate the call directly without user's interaction , You can use action Intent.ACTION_CALL
. In this case, you must add the following permission in your AndroidManifest.xml:
<uses-permission android:name="android.permission.CALL_PHONE" />
2) Need user to click on Phone_Number string and start the call.
android:autoLink="phone"
You need to use TextView with below property.
android:autoLink="phone" android:linksClickable="true" a textView property
You don't need to use intent or to get permission via this way.
I had the same problem. I solved with move the references and in less than 15 minutes, without change the references.
For me the solution was simple:
Examples:
In solution file (.sln)
Original: Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.UI", "ScannerPDF\PATH1.UI\PATH1.UI.csproj", "{A26438AD-E428-4AE4-8AB8-A5D6933E2D7B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.DataService", "ScannerPDF\PATH1.DataService\PATH1.DataService.csproj", "{ED5A561B-3674-4613-ADE5-B13661146E2E}"
New: Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.MX.UI", "PATH1.MX.UI\PATH1.UI.csproj", "{A26438AD-E428-4AE4-8AB8-A5D6933E2D7B}" Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "PATH1.DataService", "PATH1.DataService\PATH1.DataService.csproj", "{ED5A561B-3674-4613-ADE5-B13661146E2E}"
In project file:
Original:
New:
Original reference: ....\lib\RCWF\2018.1.220.40\TelerikCommon.dll
New reference: ..\lib\RCWF\2018.1.220.40\TelerikCommon.dll
The most obvious way is:
foreach(var kvp in NewAnimals)
Animals.Add(kvp.Key, kvp.Value);
//use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue
Since Dictionary<TKey, TValue>
explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Add
method, you can also do this:
var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;
foreach(var kvp in NewAnimals)
animalsAsCollection.Add(kvp);
It's a pity the class doesn't have anAddRange
method likeList<T>
does.
In general I would consider setting up of an environment variable (like PYTHONPATH)
to be a bad practice. While this might be fine for a one off debugging but using this as
a regular practice might not be a good idea.
Usage of environment variable leads to situations like "it works for me" when some one
else reports problems in the code base. Also one might carry the same practice with the
test environment as well, leading to situations like the tests running fine for a
particular developer but probably failing when some one launches the tests.
With jQuery 1.7 onward the event API has been updated, .bind()
/.unbind()
are still available for backwards compatibility, but the preferred method is using the on()/off() functions. The below would now be,
$('#myimage').click(function() { return false; }); // Adds another click event
$('#myimage').off('click');
$('#myimage').on('click.mynamespace', function() { /* Do stuff */ });
$('#myimage').off('click.mynamespace');
In your example code you are simply adding another click event to the image, not overriding the previous one:
$('#myimage').click(function() { return false; }); // Adds another click event
Both click events will then get fired.
As people have said you can use unbind to remove all click events:
$('#myimage').unbind('click');
If you want to add a single event and then remove it (without removing any others that might have been added) then you can use event namespacing:
$('#myimage').bind('click.mynamespace', function() { /* Do stuff */ });
and to remove just your event:
$('#myimage').unbind('click.mynamespace');
I am working on an application in which we track live route. Passenger wants to show current position of driver and the expected arrival time to reach at his/her location. So I need to add some duration into current time.
So I found the below mentioned way to do the same. We can add any duration(hour,minutes and seconds) in our current time by moment:
var travelTime = moment().add(642, 'seconds').format('hh:mm A');// it will add 642 seconds in the current time and will give time in 03:35 PM format
var travelTime = moment().add(11, 'minutes').format('hh:mm A');// it will add 11 mins in the current time and will give time in 03:35 PM format; can use m or minutes
var travelTime = moment().add(2, 'hours').format('hh:mm A');// it will add 2 hours in the current time and will give time in 03:35 PM format
It fulfills my requirement. May be it can help you.
>>> {k: v**3 for (k, v) in zip(string.ascii_lowercase, range(26))}
Python supports dict comprehensions, which allow you to express the creation of dictionaries at runtime using a similarly concise syntax.
A dictionary comprehension takes the form {key: value for (key, value) in iterable}. This syntax was introduced in Python 3 and backported as far as Python 2.7, so you should be able to use it regardless of which version of Python you have installed.
A canonical example is taking two lists and creating a dictionary where the item at each position in the first list becomes a key and the item at the corresponding position in the second list becomes the value.
The zip function used inside this comprehension returns an iterator of tuples, where each element in the tuple is taken from the same position in each of the input iterables. In the example above, the returned iterator contains the tuples (“a”, 1), (“b”, 2), etc.
Output:
{'i': 512, 'e': 64, 'o': 2744, 'h': 343, 'l': 1331, 's': 5832, 'b': 1, 'w': 10648, 'c': 8, 'x': 12167, 'y': 13824, 't': 6859, 'p': 3375, 'd': 27, 'j': 729, 'a': 0, 'z': 15625, 'f': 125, 'q': 4096, 'u': 8000, 'n': 2197, 'm': 1728, 'r': 4913, 'k': 1000, 'g': 216, 'v': 9261}
I made a new checkout from the same project to a different location then copied the .svn folder from it and replaced with my old .svn folder. After that called the svn update function and everything were synced properly up to date.
I ran into this very problem trying to send mail with javax.mail from a web application in a web server running Java 7. Internal mail server destinations failed with "network unreachable", despite telnet and ping working from the same host, and while external mail servers worked. I tried
System.setProperty("java.net.preferIPv4Stack" , "true");
in the code, but that failed. So the parameter value was probably cached earlier by the system. Setting the VM argument
-Djava.net.preferIPv4Stack=true
in the web server startup script worked.
One further bit of evidence: in a very small targeted test program, setting the system property in the code did work. So the parameter is probably cached when the first Socket is used, probably not just as the JVM starts.
Here's a one-liner for you:
singleton = lambda c: c()
Here's how you use it:
@singleton
class wat(object):
def __init__(self): self.x = 1
def get_x(self): return self.x
assert wat.get_x() == 1
Your object gets instantiated eagerly. This may or may not be what you want.
Many description internet-wide don't mention that specifying Access-Control-Allow-Origin
is not enough. Here is a complete example that works for me:
<?php
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, DELETE, PUT, PATCH, OPTIONS');
header('Access-Control-Allow-Headers: token, Content-Type');
header('Access-Control-Max-Age: 1728000');
header('Content-Length: 0');
header('Content-Type: text/plain');
die();
}
header('Access-Control-Allow-Origin: *');
header('Content-Type: application/json');
$ret = [
'result' => 'OK',
];
print json_encode($ret);
You can use ng-repeat
with option
like this:
<form>
<select ng-model="yourSelect"
ng-options="option as option for option in ['var1', 'var2', 'var3']"
ng-init="yourSelect='var1'"></select>
<input type="hidden" name="yourSelect" value="{{yourSelect}}" />
</form>
When you submit your form
you can get value of input hidden.
You are most likely pushing a string 'NULL'
to the table, rather then an actual NULL
, but other things may be going on as well, an illustration:
mysql> CREATE TABLE date_test (pdd DATE NOT NULL);
Query OK, 0 rows affected (0.11 sec)
mysql> INSERT INTO date_test VALUES (NULL);
ERROR 1048 (23000): Column 'pdd' cannot be null
mysql> INSERT INTO date_test VALUES ('NULL');
Query OK, 1 row affected, 1 warning (0.05 sec)
mysql> show warnings;
+---------+------+------------------------------------------+
| Level | Code | Message |
+---------+------+------------------------------------------+
| Warning | 1265 | Data truncated for column 'pdd' at row 1 |
+---------+------+------------------------------------------+
1 row in set (0.00 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
+------------+
1 row in set (0.00 sec)
mysql> ALTER TABLE date_test MODIFY COLUMN pdd DATE NULL;
Query OK, 1 row affected (0.15 sec)
Records: 1 Duplicates: 0 Warnings: 0
mysql> INSERT INTO date_test VALUES (NULL);
Query OK, 1 row affected (0.06 sec)
mysql> SELECT * FROM date_test;
+------------+
| pdd |
+------------+
| 0000-00-00 |
| NULL |
+------------+
2 rows in set (0.00 sec)
You can use as below:
string selected = cmbbox.Text;
MessageBox.Show(selected);
I've tried several of the answers here, and I think I have a solution that will work every time and manages permissions as well.
It is based on the clever solution from LEO. This post should contain all the code you need to make this work, and it should work on any phone and Android version ;)
In order to have the ability to pick a file from an SD card, you'll need this in your manifest:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
private static final int PICK_IMAGE = 456; // Whatever number you like
public static final int MY_PERMISSIONS_REQUEST_READ_EXTERNAL = 28528; // Whatever number you like
public static final String FILE_TEMP_NAME = "temp_image"; // Whatever file name you like
if (ContextCompat.checkSelfPermission(getThis(),
Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(getThis(),
new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
MY_PERMISSIONS_REQUEST_READ_EXTERNAL);
}
else {
launchImagePick();
}
@Override
public void onRequestPermissionsResult(int requestCode,
@NonNull
String permissions[],
@NonNull
int[] grantResults) {
if (manageReadExternalPermissionResponse(this, requestCode, grantResults)) {
launchImagePick();
}
}
public static boolean manageReadExternalPermissionResponse(final Activity activity, int requestCode, int[] grantResults) {
if (requestCode == MY_PERMISSIONS_REQUEST_READ_EXTERNAL) {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Permission was granted, yay! Do the
// contacts-related task you need to do.
return true;
} else if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_DENIED) {
boolean showRationale = ActivityCompat.shouldShowRequestPermissionRationale(activity,
Manifest.permission.READ_EXTERNAL_STORAGE);
if (!showRationale) {
// The user also CHECKED "never ask again".
// You can either enable some fall back,
// disable features of your app
// or open another dialog explaining
// again the permission and directing to
// the app setting.
} else {
// The user did NOT check "never ask again".
// This is a good place to explain the user
// why you need the permission and ask if he/she wants
// to accept it (the rationale).
}
} else {
// Permission denied, boo! Disable the
// functionality that depends on this permission.
}
}
return false;
}
Launch image pick
private void launchImagePick() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, PICK_IMAGE);
// see onActivityResult
}
Manage Image pick response
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == PICK_IMAGE) {
if (resultCode == Activity.RESULT_OK) {
if (data != null && data.getData() != null) {
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData())
if (inputStream != null) {
// No special persmission needed to store the file like that
FileOutputStream fos = openFileOutput(FILE_TEMP_NAME, Context.MODE_PRIVATE);
final int BUFFER_SIZE = 1 << 10 << 3; // 8 KiB buffer
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) > -1) {
fos.write(buffer, 0, bytesRead);
}
inputStream.close();
fos.close();
File tempImageFile = new File(getFilesDir()+"/"+FILE_TEMP_NAME);
// Do whatever you want with the File
// Delete when not needed anymore
deleteFile(FILE_TEMP_NAME);
}
}
catch (Exception e) {
e.printStackTrace();
}
} else {
// Error display
}
} else {
// The user did not select any image
}
}
}
That's all folks; this works for me on all the telephones I have.
In SQL Developer: Everything was working fine and I had all the permissions to login and there was no password change and I could click the table and see the data tab.
But when I run query (simple select statement) it was showing "ORA-01031: insufficient privileges" message.
The solution is simply disconnect the connection and reconnect. Note: only doing Reconnect did not work for me. SQL Developer Disconnect Snapshot
Try this (on the guest machine. i.e. the OS running in the Virtual box):
sudo adduser your-user vboxsf
Now reboot the OS running in the virtual box.
try This
setTimeout( function(){
// call after 5 second
} , 5000 );
You can still use HttpResponseMessage
. That capability will not go away. I felt the same way as you and argued extensively with the team that there was no need for an additional abstraction. There were a few arguments thrown around to try and justify its existence but nothing that convinced me that it was worthwhile.
That is, until I saw this sample from Brad Wilson. If you construct IHttpActionResult
classes in a way that can be chained, you gain the ability to create a "action-level" response pipeline for generating the HttpResponseMessage
. Under the covers, this is how ActionFilters
are implemented however, the ordering of those ActionFilters
is not obvious when reading the action method which is one reason I'm not a fan of action filters.
However, by creating an IHttpActionResult
that can be explicitly chained in your action method you can compose all kinds of different behaviour to generate your response.
To add to x4u answer, which gives you the floor of the binary log of a number, this function return the ceil of the binary log of a number :
public static int ceilbinlog(int number) // returns 0 for bits=0
{
int log = 0;
int bits = number;
if ((bits & 0xffff0000) != 0) {
bits >>>= 16;
log = 16;
}
if (bits >= 256) {
bits >>>= 8;
log += 8;
}
if (bits >= 16) {
bits >>>= 4;
log += 4;
}
if (bits >= 4) {
bits >>>= 2;
log += 2;
}
if (1 << log < number)
log++;
return log + (bits >>> 1);
}
I would personally recommend that you use os.path.isdir()
to test instead of os.path.exists()
.
>>> os.path.exists('/tmp/dirname')
True
>>> os.path.exists('/tmp/dirname/filename.etc')
True
>>> os.path.isdir('/tmp/dirname/filename.etc')
False
>>> os.path.isdir('/tmp/fakedirname')
False
If you have:
>>> dir = raw_input(":: ")
And a foolish user input:
:: /tmp/dirname/filename.etc
... You're going to end up with a directory named filename.etc
when you pass that argument to os.makedirs()
if you test with os.path.exists()
.
You can look into the regex module (the fuzzy section). I don't know if you can get the actual differences, but at least you can specify allowed number of different types of changes like insert, delete, and substitutions:
import regex
sequence = 'afrykanerskojezyczny'
queries = [ 'afrykanerskojezycznym', 'afrykanerskojezyczni',
'nieafrykanerskojezyczni' ]
for q in queries:
m = regex.search(r'(%s){e<=2}'%q, sequence)
print 'match' if m else 'nomatch'
Selected answer throws exceptions, and the answer from Carlos Toledo applies filtering after retrieving all values from the database.
The following one runs a single round-trip and reads a single value, using any possible indexes, without an exception.
int maxAge = _dbContext.Persons
.OrderByDescending(p => p.Age)
.Select(p => p.Age)
.FirstOrDefault();
Whenever gcc
on the compilation machine and gdb
on the testing machine have differing versions, you may be facing debuginfo format incompatibility.
To fix that, try downgrading the debuginfo format:
gcc -gdwarf-3 ...
gcc -gdwarf-2 ...
gcc -gstabs ...
gcc -gstabs+ ...
gcc -gcoff ...
gcc -gxcoff ...
gcc -gxcoff+ ...
Or match gdb
to the gcc
you're using.
I finally figured this out! Yes, you have to uninstall/delete all files and reinstall. BUT SOME OF THE FILE PATHS ARE TOO LONG TO DELETE DURING THE UNINSTALL PROCESS. The file paths are so long in Node that they may not be able to be deleted. You have to rename the file paths.
After uninstalling Node, use Command Prompt, navigate to ...\Appdata\roaming\ (use the path from the error message). Try to delete the folder with del npm. Then, if it doesn't allow you to delete a folder, start renaming the folders in the file path in the next error message to "a" or something short. You may have to do this for multiple folders along the path. Then you should be able to delete! Then reinstall node and it should work.
I had this problem when using java 9+ modules. I had to open
the module in order for the com.fasterxml.jackson.databind
to access the objects with reflection. Alternatively you could only open the package where the models are located if you have one.
Never ever use a "background color" for your listview rows...
this will block every selector action (was my problem!)
good luck!
I'm using the Hadoop Mincemeat module. I think this is a great example to take a note of:
import mincemeat
def mapfn(k,v):
for w in v:
yield 'sum',w
#yield 'count',1
def reducefn(k,v):
r1=sum(v)
r2=len(v)
print r2
m=r1/r2
std=0
for i in range(r2):
std+=pow(abs(v[i]-m),2)
res=pow((std/r2),0.5)
return r1,r2,res
Here the generator gets numbers out of a text file (as big as 15GB) and applies simple math on those numbers using Hadoop's map-reduce. If I had not used the yield function, but instead a list comprehension, it would have taken a much longer time calculating the sums and average (not to mention the space complexity).
Hadoop is a great example for using all the advantages of Generators.
.headerDivider {
border-left:1px solid #38546d;
border-right:1px solid #16222c;
height:80px;
position:absolute;
right:249px;
top:10px;
}
<div class="headerDivider"></div>
parameter?: type
is a shorthand for parameter: type | undefined
Intervention Image is an open source PHP image handling and manipulation library http://image.intervention.io/
This library provides a lot of useful features:
Basic Examples
// open an image file
$img = Image::make('public/foo.jpg');
// now you are able to resize the instance
$img->resize(320, 240);
// and insert a watermark for example
$img->insert('public/watermark.png');
// finally we save the image as a new file
$img->save('public/bar.jpg');
Method chaining:
$img = Image::make('public/foo.jpg')->resize(320, 240)->insert('public/watermark.png');
Tips: (In your case) https://laracasts.com/discuss/channels/laravel/file-upload-isvalid-returns-false
Tips 1:
// Tell the validator input file should be an image & check this validation
$rules = array(
'image' => 'mimes:jpeg,jpg,png,gif,svg // allowed type
|required // is required field
|max:2048' // max 2MB
|min:1024 // min 1MB
);
// validator Rules
$validator = Validator::make($request->only('image'), $rules);
// Check validation (fail or pass)
if ($validator->fails())
{
//Error do your staff
} else
{
//Success do your staff
};
Tips 2:
$this->validate($request, [
'input_img' =>
'required
|image
|mimes:jpeg,png,jpg,gif,svg
|max:1024',
]);
Function:
function imageUpload(Request $request) {
if ($request->hasFile('input_img')) { //check the file present or not
$image = $request->file('input_img'); //get the file
$name = "//what every you want concatenate".'.'.$image->getClientOriginalExtension(); //get the file extention
$destinationPath = public_path('/images'); //public path folder dir
$image->move($destinationPath, $name); //mve to destination you mentioned
$image->save(); //
}
}
// service: (nothing special here)
myApp.service('myService', function() {
return { someVariable:'abc123' };
});
// ctrl:
myApp.controller('MyCtrl', function($scope, myService) {
$scope.someVariable = myService.someVariable;
// watch the service and update this ctrl...
$scope.$watch(function(){
return myService.someVariable;
}, function(newValue){
$scope.someVariable = newValue;
});
});
I resorted to creating 2 style cascades using inline-block for input that pretty much override the field:
.input-sm {
height: 2.1em;
display: inline-block;
}
and a series of fixed sizes as opposed to %
.input-10 {
width: 10em;
}
.input-32 {
width: 32em;
}
This is a firewall issue, if you are using a VMware application, make sure the firewall on the antivirus is turned off or allowing connections.
If this server is on a secure network, please have a look at firewall rules of the server.
Thanks Ganesh PNS
awk -F"|" '{gsub(/\"/,"|");print "\""$2"\""}' your_file
The best practice is using File.separator in the paths.
I've created a little Powershell function to emulate MSDOS pause
. This handles whether running Powershell ISE or non ISE. (ReadKey
does not work in powershell ISE). When running Powershell ISE, this function opens a Windows MessageBox
. This can sometimes be confusing, because the MessageBox
does not always come to the forefront. Anyway, here it goes:
Usage:
pause "Press any key to continue"
Function definition:
Function pause ($message)
{
# Check if running Powershell ISE
if ($psISE)
{
Add-Type -AssemblyName System.Windows.Forms
[System.Windows.Forms.MessageBox]::Show("$message")
}
else
{
Write-Host "$message" -ForegroundColor Yellow
$x = $host.ui.RawUI.ReadKey("NoEcho,IncludeKeyDown")
}
}
NTML PROXY AND DOCKER
If your company is behind MS Proxy Server that using the proprietary NTLM protocol.
You need to install **Cntlm** Authentication Proxy
After this SET the proxy in
/etc/systemd/system/docker.service.d/http-proxy.conf) with the following format:
[Service]
Environment=“HTTP_PROXY=http://<<IP OF CNTLM Proxy Server>>:3182”
In addition you can set in the .DockerFile
export http_proxy=http://<<IP OF CNTLM Proxy Server>>:3182
export https_proxy=http://<IP OF CNTLM Proxy Server>>:3182
export no_proxy=localhost,127.0.0.1,10.0.2.*
Followed by:
systemctl daemon-reload
systemctl restart docker
This Worked for me
You specify the named capture group string by passing it to the indexer of the Groups
property of a resulting Match
object.
Here is a small example:
using System;
using System.Text.RegularExpressions;
class Program
{
static void Main()
{
String sample = "hello-world-";
Regex regex = new Regex("-(?<test>[^-]*)-");
Match match = regex.Match(sample);
if (match.Success)
{
Console.WriteLine(match.Groups["test"].Value);
}
}
}
Session.Abandon()
destroys the session and the Session_OnEnd event is triggered.
Session.Clear()
just removes all values (content) from the Object. The session with the same key is still alive.
So, if you use Session.Abandon()
, you lose that specific session and the user will get a new session key. You could use it for example when the user logs out.
Use Session.Clear()
, if you want that the user remaining in the same session (if you don't want the user to relogin for example) and reset all the session specific data.
As seen on WWDC 2016/XCode 8 (what's new in LLVM session @5:05). Class properties can be declared as follows
@interface MyType : NSObject
@property (class) NSString *someString;
@end
NSLog(@"format string %@", MyType.someString);
Note that class properties are never synthesized
@implementation
static NSString * _someString;
+ (NSString *)someString { return _someString; }
+ (void)setSomeString:(NSString *)newString { _someString = newString; }
@end
Spring Boot, v2.3.0.RELEASE
Recommended (In application.properties):
logging.level.org.hibernate.SQL=DEBUG //logs all SQL DML statements
logging.level.org.hibernate.type=TRACE //logs all JDBC parameters
parameters
Note:
The above will not give you a pretty-print though.
You can add it as a configuration:
properties.put("hibernate.format_sql", "true");
or as per below.
Works but NOT recommended
spring.jpa.show-sql=true
spring.jpa.properties.hibernate.format_sql=true
Reason: It's better to let the logging framework manage/optimize the output for you + it doesn't give you the prepared statement parameters.
Cheers
Try using cURL instead. cURL implements a cookie jar, while file_get_contents doesn't.
Alternatively, you can resize the array.
Array.Resize(ref array, array.Length + 1);
array[array.Length - 1] = "new string";
You can use filter method and indexOf() to get all the duplicate values
function duplicate(arr) {
return duplicateArray = arr.filter((item, index) => arr.indexOf(item) !== index)
}
arr.indexOf(item) will always return the first index at which a given element can be found
NuGet references
Assume the -Project_A (produces project_a.dll) -Project_B (produces project_b.dll) and Project_B references to Project_A by NuGet packages then just copy project_a.dll , project_a.pdb to the folder Project_B/Packages. In effect that should be copied to the /bin.
Now debug Project_A. When code reaches the part where you need to call dll's method or events etc while debugging, press F11 to step into the dll's code.
Use the abs
function:
int sum=0;
for(Integer i : container)
sum+=Math.abs(i);
<TouchableHighlight>
element can have only one child inside var mapped = _.reduce({ one: 1, two: 2, three: 3 }, function(obj, val, key) {_x000D_
obj[key] = val*3;_x000D_
return obj;_x000D_
}, {});_x000D_
_x000D_
console.log(mapped);
_x000D_
<script src="http://underscorejs.org/underscore-min.js"></script>_x000D_
<script src="https://getfirebug.com/firebug-lite-debug.js"></script>
_x000D_
Step 1 . Go to Androidsdk\platform-tools on PC/Laptop
Step 2 :
Connect your device via USB and run:
adb kill-server
then run
adb tcpip 5555
you will see below message...
daemon not running. starting it now on port 5037 * daemon started successfully * restarting in TCP mode port: 5555
Step3:
Now open new CMD window,
Go to Androidsdk\platform-tools
Now run
adb connect xx.xx.xx.xx:5555
(xx.xx.xx.xx is device IP)
Step4: Disconnect your device from USB and it will work as if connected from your Android studio.
This is how I do it.
[[[UIApplication sharedApplication] delegate] performSelector:@selector(nameofMethod)];
Dont forget to import.
#import "AppDelegate.h"
User float:left
property in child div class
check for div structure in detail : http://www.dzone.com/links/r/div_table.html
You can always simply add an alert() prompt anywhere in a function. Especially useful for knowing if a function was called, if a function completed or where a function fails.
alert('start of function x');
alert('end of function y');
alert('about to call function a');
alert('returned from function b');
You get the idea.
JavaScript perfectly supports date difference out of the box
https://jsfiddle.net/b9chris/v5twbe3h/
var msMinute = 60*1000,
msDay = 60*60*24*1000,
a = new Date(2012, 2, 12, 23, 59, 59),
b = new Date("2013 march 12");
console.log(Math.floor((b - a) / msDay) + ' full days between'); // 364
console.log(Math.floor(((b - a) % msDay) / msMinute) + ' full minutes between'); // 0
Now some pitfalls. Try this:
console.log(a - 10); // 1331614798990
console.log(a + 10); // mixed string
So if you have risk of adding a number and Date, convert Date to number
directly.
console.log(a.getTime() - 10); // 1331614798990
console.log(a.getTime() + 10); // 1331614799010
My fist example demonstrates the power of Date object but it actually appears to be a time bomb
I would do this slightly different by applying both the UNPIVOT
and the PIVOT
functions to get the final result. The unpivot takes the values from both the totalcount
and totalamount
columns and places them into one column with multiple rows. You can then pivot on those results.:
select chardate,
Australia_totalcount as [Australia # of Transactions],
Australia_totalamount as [Australia Total $ Amount],
Austria_totalcount as [Austria # of Transactions],
Austria_totalamount as [Austria Total $ Amount]
from
(
select
numericmonth,
chardate,
country +'_'+col col,
value
from
(
select numericmonth,
country,
chardate,
cast(totalcount as numeric(10, 2)) totalcount,
cast(totalamount as numeric(10, 2)) totalamount
from mytransactions
) src
unpivot
(
value
for col in (totalcount, totalamount)
) unpiv
) s
pivot
(
sum(value)
for col in (Australia_totalcount, Australia_totalamount,
Austria_totalcount, Austria_totalamount)
) piv
order by numericmonth
See SQL Fiddle with Demo.
If you have an unknown number of country
names, then you can use dynamic SQL:
DECLARE @cols AS NVARCHAR(MAX),
@colsName AS NVARCHAR(MAX),
@query AS NVARCHAR(MAX)
select @cols = STUFF((SELECT distinct ',' + QUOTENAME(country +'_'+c.col)
from mytransactions
cross apply
(
select 'TotalCount' col
union all
select 'TotalAmount'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
select @colsName
= STUFF((SELECT distinct ', ' + QUOTENAME(country +'_'+c.col)
+' as ['
+ country + case when c.col = 'TotalCount' then ' # of Transactions]' else 'Total $ Amount]' end
from mytransactions
cross apply
(
select 'TotalCount' col
union all
select 'TotalAmount'
) c
FOR XML PATH(''), TYPE
).value('.', 'NVARCHAR(MAX)')
,1,1,'')
set @query
= 'SELECT chardate, ' + @colsName + '
from
(
select
numericmonth,
chardate,
country +''_''+col col,
value
from
(
select numericmonth,
country,
chardate,
cast(totalcount as numeric(10, 2)) totalcount,
cast(totalamount as numeric(10, 2)) totalamount
from mytransactions
) src
unpivot
(
value
for col in (totalcount, totalamount)
) unpiv
) s
pivot
(
sum(value)
for col in (' + @cols + ')
) p
order by numericmonth'
execute(@query)
Both give the result:
| CHARDATE | AUSTRALIA # OF TRANSACTIONS | AUSTRALIA TOTAL $ AMOUNT | AUSTRIA # OF TRANSACTIONS | AUSTRIA TOTAL $ AMOUNT |
--------------------------------------------------------------------------------------------------------------------------------------
| Jul-12 | 36 | 699.96 | 11 | 257.82 |
| Aug-12 | 44 | 1368.71 | 5 | 126.55 |
| Sep-12 | 52 | 1161.33 | 7 | 92.11 |
| Oct-12 | 50 | 1099.84 | 12 | 103.56 |
| Nov-12 | 38 | 1078.94 | 21 | 377.68 |
| Dec-12 | 63 | 1668.23 | 3 | 14.35 |
One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.
EDIT: Here's some sample code from MSDN: http://msdn.microsoft.com/en-us/library/ms748365.aspx
In C#, hooking the ListBox to the collection could be as easy as
listBox.ItemsSource = NameListData;
though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:
public override ToString()
{
return string.Format("{0} {1}", this.FirstName, this.LastName);
}
Example for CoffeeScript
:
test = (str, callback) ->
data = "Input values"
$.ajax
type: "post"
url: "http://www.mydomain.com/ajaxscript"
data: data
success: callback
test (data, textStatus, xhr) ->
alert data + "\t" + textStatus
The solution will be simple, As you just need 'listeners' when a certain radio button is checked. Do it :-
if($('#yourRadioButtonId').is(':checked')){
// Do your listener's stuff here.
}
Just letting you all know I had this problem too. Rather than the code, the issue lay with what macro a button was calling. (It had been calling the 'createroutes.createroutes' macro, but I had renamed the 'createroutes' module to 'routes'.) Therefore the problem was fixed by pointing the button to the correct location.
the following is that the difference between iterator and listIterator
iterator :
boolean hasNext();
E next();
void remove();
listIterator:
boolean hasNext();
E next();
boolean hasPrevious();
E previous();
int nextIndex();
int previousIndex();
void remove();
void set(E e);
void add(E e);
Assuming (!) the strings are of equal length, why not convert the strings to byte arrays and then XOR the bytes. The resultant byte arrays may be of different lengths too depending on your encoding (e.g. UTF8 will expand to different byte lengths for different characters).
You should be careful to specify the character encoding to ensure consistent/reliable string/byte conversion.
2016 Update: in Chrome Version 51.0.2704.103
There is a Go to member
shortcut (listed in settings > shortcut > Text Editor
). Open the file containing your function (in the sources
panel of the DevTools) and press:
ctrl + shift + O
or in OS X:
? + shift + O
This enables to list and reach members of the current file.
There is sort of a way around this:
struct Cell {
bool isParent;
struct Cell* child;
};
struct Cell;
typedef struct Cell Cell;
If you declare it like this, it properly tells the compiler that struct Cell and plain-ol'-cell are the same. So you can use Cell just like normal. Still have to use struct Cell inside of the initial declaration itself though.
Here is another library.
Changes required are -
Add sorttable js
Add class name sortable
to table.
Click the table headers to sort the table accordingly:
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>
<table class="sortable">
<tr>
<th>Name</th>
<th>Address</th>
<th>Sales Person</th>
</tr>
<tr class="item">
<td>user:0001</td>
<td>UK</td>
<td>Melissa</td>
</tr>
<tr class="item">
<td>user:0002</td>
<td>France</td>
<td>Justin</td>
</tr>
<tr class="item">
<td>user:0003</td>
<td>San Francisco</td>
<td>Judy</td>
</tr>
<tr class="item">
<td>user:0004</td>
<td>Canada</td>
<td>Skipper</td>
</tr>
<tr class="item">
<td>user:0005</td>
<td>Christchurch</td>
<td>Alex</td>
</tr>
</table>
_x000D_
You don't need to update anything. Just download the SDK for API 25 from Android SDK Manager or by launching Android standalone SDK manager. The error is for missing platform and not for missing tool.
The trick is that you have to set it as position:fixed, but only after the user has scrolled past it.
This is done with something like this, attaching a handler to the window.scroll event
// Cache selectors outside callback for performance.
var $window = $(window),
$stickyEl = $('#the-sticky-div'),
elTop = $stickyEl.offset().top;
$window.scroll(function() {
$stickyEl.toggleClass('sticky', $window.scrollTop() > elTop);
});
This simply adds a sticky
CSS class when the page has scrolled past it, and removes the class when it's back up.
And the CSS class looks like this
#the-sticky-div.sticky {
position: fixed;
top: 0;
}
EDIT- Modified code to cache jQuery objects, faster now.
Laravel 5.2
$sql = "SELECT * FROM users WHERE email = $email";
$user = collect(\User::select($sql))->first();
or
$user = User::table('users')->where('email', $email)->pluck();
It used to be possible to compile Matlab to C with older versions of Matlab. Check out other tools that Matlab comes with.
Newest Matlab code can be exported as a Java's jar or a .Net Dll, etc. You can then write an executable against that library - it will be obfuscated by the way. The users will have to install a freely available Matlab Runtime.
Like others mentioned, mcc / mcc.exe is what you want to convert matlab code to C code.
You can use VBA - something like
Range("A1:A6").Interior.Color = RGB(127,187,199)
Just pass in the cell value.
You should use new when you want an object to be created on the heap instead of the stack. This allows an object to be accessed from outside the current function or procedure, through the aid of pointers.
It might be of use to you to look up pointers and memory management in C++ since these are things you are unlikely to have come across in other languages.
Try:
In the controller:
ViewBag.Accounts= new SelectList(db.Accounts, "AccountId", "AccountName");
In the View:
@Html.DropDownList("AccountId", (IEnumerable<SelectListItem>)ViewBag.Accounts, null, new { @class ="form-control" })
or you can replace the "null" with whatever you want display as default selector, i.e. "Select Account".
jQuery is just JavaScript, don't think very differently about it! Like you would do in 'normal' JS, you add an event listener to the buttons and change the action attribute of the form. In jQuery this looks something like:
$('#button1').click(function(){
$('#your_form').attr('action', 'http://uri-for-button1.com');
});
This code is the same for the second button, you only need to change the id of your button and the URI where the form should be submitted to.
Bit late to the party here, but another way to do it would be to use a Deferred object. You essentially have the same amount of boilerplate, but it's handy if you want to pass them around and possibly resolve outside of their definition.
Naive Implementation:
class Deferred {
constructor() {
this.promise = new Promise((resolve, reject)=> {
this.reject = reject
this.resolve = resolve
})
}
}
function asyncAction() {
var dfd = new Deferred()
setTimeout(()=> {
dfd.resolve(42)
}, 500)
return dfd.promise
}
asyncAction().then(result => {
console.log(result) // 42
})
ES5 Version:
function Deferred() {
var self = this;
this.promise = new Promise(function(resolve, reject) {
self.reject = reject
self.resolve = resolve
})
}
function asyncAction() {
var dfd = new Deferred()
setTimeout(function() {
dfd.resolve(42)
}, 500)
return dfd.promise
}
asyncAction().then(function(result) {
console.log(result) // 42
})
Use str_replace
to remove the spaces first ?
I liked @mate64's answer so I am going to reuse that with slight modifications to create a slide down and up animations below:
var $slider = document.getElementById('slider');_x000D_
var $toggle = document.getElementById('toggle');_x000D_
_x000D_
$toggle.addEventListener('click', function() {_x000D_
var isOpen = $slider.classList.contains('slide-in');_x000D_
_x000D_
$slider.setAttribute('class', isOpen ? 'slide-out' : 'slide-in');_x000D_
});
_x000D_
#slider {_x000D_
position: absolute;_x000D_
width: 100px;_x000D_
height: 100px;_x000D_
background: blue;_x000D_
transform: translateY(-100%);_x000D_
-webkit-transform: translateY(-100%);_x000D_
}_x000D_
_x000D_
.slide-in {_x000D_
animation: slide-in 0.5s forwards;_x000D_
-webkit-animation: slide-in 0.5s forwards;_x000D_
}_x000D_
_x000D_
.slide-out {_x000D_
animation: slide-out 0.5s forwards;_x000D_
-webkit-animation: slide-out 0.5s forwards;_x000D_
}_x000D_
_x000D_
@keyframes slide-in {_x000D_
100% { transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-in {_x000D_
100% { -webkit-transform: translateY(0%); }_x000D_
}_x000D_
_x000D_
@keyframes slide-out {_x000D_
0% { transform: translateY(0%); }_x000D_
100% { transform: translateY(-100%); }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes slide-out {_x000D_
0% { -webkit-transform: translateY(0%); }_x000D_
100% { -webkit-transform: translateY(-100%); }_x000D_
}
_x000D_
<div id="slider" class="slide-in">_x000D_
<ul>_x000D_
<li>Lorem</li>_x000D_
<li>Ipsum</li>_x000D_
<li>Dolor</li>_x000D_
</ul>_x000D_
</div>_x000D_
_x000D_
<button id="toggle" style="position:absolute; top: 120px;">Toggle</button>
_x000D_
I created a vanilla javascript solution to using VH units. Using VH pretty much anywhere is effected by address bars minimizing on scroll. To fix the jank that shows when the page redraws, I've got this js here that will grab all your elements using VH units (if you give them the class .vh-fix
), and give them inlined pixel heights. Essentially freezing them at the height we want. You could do this on rotation or on viewport size change to stay responsive.
var els = document.querySelectorAll('.vh-fix')
if (!els.length) return
for (var i = 0; i < els.length; i++) {
var el = els[i]
if (el.nodeName === 'IMG') {
el.onload = function() {
this.style.height = this.clientHeight + 'px'
}
} else {
el.style.height = el.clientHeight + 'px'
}
}
This has solved all my use cases, hope it helps.
If you are using angular/flex-layout in your project, you can set column with by adding fxFlex directive to mat-header-cell and mat-cell:
<ng-container matColumnDef="name" >
<mat-header-cell fxFlex="100px" *matHeaderCellDef mat-sort-header>Name</mat-header-cell>
<mat-cell fxFlex="100px" *matCellDef="let row;" (click)="rowClick(row)">{{row.Name}}</mat-cell>
</ng-container>
Otherwise, you can add custom CSS to achieve the same result:
.mat-column-name{
flex: 0 0 100px;
}
Here is a jQuery plugin that will handle everything for you, Transify (Transify - a jQuery plugin to easily apply transparency / opacity to an element’s background).
I was running into this problem every now and then, so I decided to write something that would make life a lot easier. The script is less than 2 KB and it only requires one line of code to get it to work, and it will also handle animating the opacity of the background if you like.
Verify that your installation of PHP has been compiled with mysql support. Create a test web page containing <?php phpinfo(); exit(); ?>
and load it in your browser. Search the page for MySQL. If you don't see it, you need to recompile PHP with MySQL support, or reinstall a PHP package that has it built-in
As mentioned in the error, the official manual and the comments:
Replace
public function TSStatus($host, $queryPort)
with
public function __construct($host, $queryPort)
This works for me
dataGridView1.Rows[rowIndex].Cells[columnIndex].Style.BackColor = Color.Red;
ManagementFactory.getThreadMXBean().getThreadCount()
doesn't limit itself to thread groups as Thread.activeCount()
does.
jQuery has some issues loading binary data using AJAX requests, as it does not yet implement some HTML5 XHR v2 capabilities, see this enhancement request and this discussion
Given that, you have one of two solutions:
First solution, abandon JQuery and use XMLHTTPRequest
Go with the native HTMLHTTPRequest, here is the code to do what you need
var req = new XMLHttpRequest();
req.open("GET", "/file.pdf", true);
req.responseType = "blob";
req.onload = function (event) {
var blob = req.response;
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
};
req.send();
Second solution, use the jquery-ajax-native plugin
The plugin can be found here and can be used to the XHR V2 capabilities missing in JQuery, here is a sample code how to use it
$.ajax({
dataType: 'native',
url: "/file.pdf",
xhrFields: {
responseType: 'blob'
},
success: function(blob){
console.log(blob.size);
var link=document.createElement('a');
link.href=window.URL.createObjectURL(blob);
link.download="Dossier_" + new Date() + ".pdf";
link.click();
}
});
Press "F4" on windows which will open up "Project Structure" and then click "+" icon or "Alt + Insert" to select a new project to be imported; then click OK button...
I ran into this error after my client PC crashed, the jest --watch
command I was running on the server persisted, and I tried to run jest --watch
again.
The addition to /etc/sysctl.conf
described in the answers above worked around this issue, but it was also important to find my old process via ps aux | grep node
and kill
it.
Wildcards (asterisks) ARE NOT allowed in the subdomain part.
Forget what Google says on the placeholder, it is not allowed.
`
data1 <- data.frame(col1=1:4, col2=5:8, col3=9:12)
row.names(data1) <- c("row1","row2","row3","row4")
data1
data2 <- data.frame(col1=21:24, col2=25:28, col3=29:32)
row.names(data2) <- c("row1","row2","row3","row4")
data2
insertPosition = 2
leftBlock <- unlist(data1[,1:(insertPosition-1)])
insertBlock <- unlist(data2[,1:length(data2[1,])])
rightBlock <- unlist(data1[,insertPosition:length(data1[1,])])
newData <- matrix(c(leftBlock, insertBlock, rightBlock), nrow=length(data1[,1]), byrow=FALSE)
newData
`
This SQL Server User Defined Function resolves the problem efficiently.No recursion, no complex loops. It takes a very short time to generate.
ALTER FUNCTION [GA].[udf_GenerateCalendar]
(
@StartDate DATE -- StartDate
, @EndDate DATE -- EndDate
)
RETURNS @Results TABLE
(
Date DATE
)
AS
/**********************************************************
Purpose: Generate a sequence of dates based on StartDate and EndDate
***********************************************************/
BEGIN
DECLARE @counter INTEGER = 1
DECLARE @days table(
day INTEGER NOT NULL
)
DECLARE @months table(
month INTEGER NOT NULL
)
DECLARE @years table(
year INTEGER NOT NULL
)
DECLARE @calendar table(
Date DATE NOT NULL
)
-- Populate generic days
SET @counter = 1
WHILE @counter <= 31
BEGIN
INSERT INTO @days
SELECT @counter dia
SELECT @counter = @counter + 1
END
-- Populate generic months
SET @counter = 1
WHILE @counter <= 12
BEGIN
INSERT INTO @months
SELECT @counter month
SELECT @counter = @counter + 1
END
-- Populate generic years
SET @counter = YEAR(@StartDate)
WHILE @counter <= YEAR(@EndDate)
BEGIN
INSERT INTO @years
SELECT @counter year
SELECT @counter = @counter + 1
END
INSERT @calendar (Date)
SELECT Date
FROM (
SELECT
CONVERT(Date, [Date], 102) AS Date
FROM (
SELECT
CAST(
y.year * 10000
+ m.month * 100
+ d.day
AS VARCHAR(8)) AS Date
FROM @days d, @months m, @years y
WHERE
ISDATE(CAST(
y.year * 10000
+ m.month * 100
+ d.day
AS VARCHAR(8))
) = 1
) A
) A
INSERT @Results (Date)
SELECT Date
FROM @calendar
WHERE Date BETWEEN @StartDate AND @EndDate
RETURN
/*
DECLARE @StartDate DATE = '2015-08-01'
DECLARE @EndDate DATE = '2015-08-31'
select * from [GA].[udf_GenerateCalendar](@StartDate, @EndDate)
*/
END
Just in case you don't want to bump Windows SDK to Windows 10 (you could be for example working on an open source project where the decision isn't yours to make), you can solve this problem in a Windows SDK 8.1 project by navigating Tools -> Get Tools and Features... -> Individual Compontents tab
and installing the individual components "Windows 8.1 SDK" (under SDKs, libraries and frameworks) and "Windows Universal CRT SDK" (under Compilers, build tools and runtimes):
This is a very old question, but I found a new solution, so I wrote about it.
First of all, is this way of solution possible while using AutoGenerateColumns?
Yes, that can be done with AttachedProperty as follows.
<DataGrid AutoGenerateColumns="True"
local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
ItemsSource="{Binding}" />
There are two AttachedProperty defined that allow you to specify two formats.
DateTimeFormatAutoGenerate
for DateTime
and TimeSpanFormatAutoGenerate
for TimeSpan
.
class DataGridOperation
{
public static string GetDateTimeFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(DateTimeFormatAutoGenerateProperty);
public static void SetDateTimeFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(DateTimeFormatAutoGenerateProperty, value);
public static readonly DependencyProperty DateTimeFormatAutoGenerateProperty =
DependencyProperty.RegisterAttached("DateTimeFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<DateTime>(d, e)));
public static string GetTimeSpanFormatAutoGenerate(DependencyObject obj) => (string)obj.GetValue(TimeSpanFormatAutoGenerateProperty);
public static void SetTimeSpanFormatAutoGenerate(DependencyObject obj, string value) => obj.SetValue(TimeSpanFormatAutoGenerateProperty, value);
public static readonly DependencyProperty TimeSpanFormatAutoGenerateProperty =
DependencyProperty.RegisterAttached("TimeSpanFormatAutoGenerate", typeof(string), typeof(DataGridOperation),
new PropertyMetadata(null, (d, e) => AddEventHandlerOnGenerating<TimeSpan>(d, e)));
private static void AddEventHandlerOnGenerating<T>(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
if (!(d is DataGrid dGrid))
return;
if ((e.NewValue is string format))
dGrid.AutoGeneratingColumn += (o, e) => AddFormat_OnGenerating<T>(e, format);
}
private static void AddFormat_OnGenerating<T>(DataGridAutoGeneratingColumnEventArgs e, string format)
{
if (e.PropertyType == typeof(T))
(e.Column as DataGridTextColumn).Binding.StringFormat = format;
}
}
<Window
x:Class="DataGridAutogenerateCustom.MainWindow"
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:local="clr-namespace:DataGridAutogenerateCustom"
Width="400" Height="250">
<Window.DataContext>
<local:MainWindowViewModel />
</Window.DataContext>
<StackPanel>
<TextBlock Text="DEFAULT FORMAT" />
<DataGrid ItemsSource="{Binding Dates}" />
<TextBlock Margin="0,30,0,0" Text="CUSTOM FORMAT" />
<DataGrid
local:DataGridOperation.DateTimeFormatAutoGenerate="yy-MM-dd"
local:DataGridOperation.TimeSpanFormatAutoGenerate="dd\-hh\-mm\-ss"
ItemsSource="{Binding Dates}" />
</StackPanel>
</Window>
public class MainWindowViewModel
{
public DatePairs[] Dates { get; } = new DatePairs[]
{
new (){StartDate= new (2011,1,1), EndDate= new (2011,2,1) },
new (){StartDate= new (2020,1,1), EndDate= new (2021,1,1) },
};
}
public class DatePairs
{
public DateTime StartDate { get; set; }
public DateTime EndDate { get; set; }
public TimeSpan Span => EndDate - StartDate;
}
Try this in your Head section of the site:
$(function() {
$('.menu_box_list li').click(function() {
$('.menu_box_list li.active').removeClass('active');
$(this).addClass('active');
});
});
if (data[j] =='B'){
row.cells[j].title="Basic";
}
In Java script conditionally adding title by comparing value of Data. The Table is generated by Java script dynamically.
It's basically the same mechanism as for a non query command with:
CommandType.StoredProcedure
There are plenty of examples out there, the first one returned by Google is this one
There's also a little trap you might fall into, if your SP is a function, your return value parameter must be first in the parameters collection
There is also now https://github.com/xk/node-threads-a-gogo, though I'm not sure about project status.
if name in ("Jesse", "jesse"):
would be the correct way to do it.
Although, if you want to use or
, the statement would be
if name == 'Jesse' or name == 'jesse':
>>> ("Jesse" or "jesse")
'Jesse'
evaluates to 'Jesse'
, so you're essentially not testing for 'jesse'
when you do if name == ("Jesse" or "jesse")
, since it only tests for equality to 'Jesse'
and does not test for 'jesse'
, as you observed.
Check to make sure that the file is complete. This error message can occur if you only partially downloaded a file or if it has major issues. Check the MD5sum.
I continued to have this problem in ie7 when the browser was at certain widths. Turns out older browsers round the pixel value up if the percentage result isn't a whole number. To solve this you can try setting
overflow: hidden;
on the last element (or all of them).
If you are feeling particularly clever and don't want to use Regex:
char[] separators = new char[]{' ',';',',','\r','\t','\n'};
string s = "this;is,\ra\t\n\n\ntest";
string[] temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
s = String.Join("\n", temp);
You could wrap this in an extension method with little effort as well.
Edit: Or just wait 2 minutes and I'll end up writing it anyway :)
public static class ExtensionMethods
{
public static string Replace(this string s, char[] separators, string newVal)
{
string[] temp;
temp = s.Split(separators, StringSplitOptions.RemoveEmptyEntries);
return String.Join( newVal, temp );
}
}
And voila...
char[] separators = new char[]{' ',';',',','\r','\t','\n'};
string s = "this;is,\ra\t\n\n\ntest";
s = s.Replace(separators, "\n");
@Html.TextBoxFor(x => x.MobileNo, new { @class = "digit" , @maxlength = "10"})
@section Scripts
{
@Scripts.Render("~/bundles/jqueryui")
@Styles.Render("~/Content/cssjqryUi")
<script type="text/javascript">
$(".digit").keypress(function (e) {
if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57))
{
$("#errormsg").html("Digits Only").show().fadeOut("slow");
return false;
}
});
</script>
}
muPdf library looks very promising: http://mupdf.com/
There is also an open source viewer: http://blog.kowalczyk.info/software/sumatrapdf/free-pdf-reader.html
I think this code will resolve your issue. Copy and paste this code on your MainActivity.java
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View decorView = getWindow().getDecorView();
decorView.setOnSystemUiVisibilityChangeListener
(new View.OnSystemUiVisibilityChangeListener() {
@Override
public void onSystemUiVisibilityChange(int visibility) {
if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
hideNavigationBar();
}
}
});
}
private void hideNavigationBar() {
getWindow().getDecorView().setSystemUiVisibility(
View.SYSTEM_UI_FLAG_HIDE_NAVIGATION|
View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY);
}
It will works on Android-10. I hope it will helps.
Ok I actually found the answer but thought I would 'import' the question into SO anyway
String[] files = new String[0];
or
int[] files = new int[0];
For WampServer, click on its tray icon and then in the popup cascading menu select
MySQL | MySQL settings | datadir
append
appends a single element. extend
appends a list of elements.
Note that if you pass a list to append, it still adds one element:
>>> a = [1, 2, 3]
>>> a.append([4, 5, 6])
>>> a
[1, 2, 3, [4, 5, 6]]
try:
r = requests.post(url, data=data, verify='/path/to/public_key.pem')
inputString.splitlines()
Will give you a list with each item, the splitlines()
method is designed to split each line into a list element.
You use NSSortDescriptor to sort an NSMutableArray with custom objects
NSSortDescriptor *sortingDescriptor;
sortingDescriptor = [[NSSortDescriptor alloc] initWithKey:@"birthDate"
ascending:YES];
NSArray *sortArray = [drinkDetails sortedArrayUsingDescriptors:@[sortDescriptor]];
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
In my case I had to register the .dll.
To do so, open cmd.exe
(the console) with admin rights and type:
regsvr32 "foo.dll"
My situation was that I did not have a main function.
Warning! chrome.tabs.getSelected
is deprecated. Please use chrome.tabs.query
as shown in the other answers.
First, you've to set the permissions for the API in manifest.json:
"permissions": [
"tabs"
]
And to store the URL :
chrome.tabs.getSelected(null,function(tab) {
var tablink = tab.url;
});
Slightly modified version of @PercyPercy - it doesn't throw and just returns null if anything goes wrong:
public String getPathFromMediaUri(Context context, Uri uri) {
String result = null;
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = context.getContentResolver().query(uri, projection, null, null, null);
int col = cursor.getColumnIndex(MediaStore.Images.Media.DATA);
if (col >= 0 && cursor.moveToFirst())
result = cursor.getString(col);
cursor.close();
return result;
}
I have found the selected answer to have problems with upscaling, and so I have made (yet) another version (which I have tested):
public static Point scaleFit(Point src, Point bounds) {
int newWidth = src.x;
int newHeight = src.y;
double boundsAspectRatio = bounds.y / (double) bounds.x;
double srcAspectRatio = src.y / (double) src.x;
// first check if we need to scale width
if (boundsAspectRatio < srcAspectRatio) {
// scale width to fit
newWidth = bounds.x;
//scale height to maintain aspect ratio
newHeight = (newWidth * src.y) / src.x;
} else {
//scale height to fit instead
newHeight = bounds.y;
//scale width to maintain aspect ratio
newWidth = (newHeight * src.x) / src.y;
}
return new Point(newWidth, newHeight);
}
Written in Android terminology :-)
as for the tests:
@Test public void scaleFit() throws Exception {
final Point displaySize = new Point(1080, 1920);
assertEquals(displaySize, Util.scaleFit(displaySize, displaySize));
assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x / 2, displaySize.y / 2), displaySize));
assertEquals(displaySize, Util.scaleFit(new Point(displaySize.x * 2, displaySize.y * 2), displaySize));
assertEquals(new Point(displaySize.x, displaySize.y * 2), Util.scaleFit(new Point(displaySize.x / 2, displaySize.y), displaySize));
assertEquals(new Point(displaySize.x * 2, displaySize.y), Util.scaleFit(new Point(displaySize.x, displaySize.y / 2), displaySize));
assertEquals(new Point(displaySize.x, displaySize.y * 3 / 2), Util.scaleFit(new Point(displaySize.x / 3, displaySize.y / 2), displaySize));
}
In this sample in catch block i change the value of counter and it will break while block:
class TestBreak {
public static void main(String[] a) {
int counter = 0;
while(counter<5) {
try {
counter++;
int x = counter/0;
}
catch(Exception e) {
counter = 1000;
}
}
}
}k
Superclass constructor CAN'T be inherited in extended class. Although it can be invoked in extended class constructor's with super() as the first statement.
An abstract method is a method that must be implemented to make a concrete class. The declaration is in the abstract class (and any class with an abstract method must be an abstract class) and it must be implemented in a concrete class.
A virtual method is a method that can be overridden in a derived class using the override, replacing the behavior in the superclass. If you don't override, you get the original behavior. If you do, you always get the new behavior. This opposed to not virtual methods, that can not be overridden but can hide the original method. This is done using the new
modifier.
See the following example:
public class BaseClass
{
public void SayHello()
{
Console.WriteLine("Hello");
}
public virtual void SayGoodbye()
{
Console.WriteLine("Goodbye");
}
public void HelloGoodbye()
{
this.SayHello();
this.SayGoodbye();
}
}
public class DerivedClass : BaseClass
{
public new void SayHello()
{
Console.WriteLine("Hi There");
}
public override void SayGoodbye()
{
Console.WriteLine("See you later");
}
}
When I instantiate DerivedClass
and call SayHello
, or SayGoodbye
, I get "Hi There" and "See you later". If I call HelloGoodbye
, I get "Hello" and "See you later". This is because SayGoodbye
is virtual, and can be replaced by derived classes. SayHello
is only hidden, so when I call that from my base class I get my original method.
Abstract methods are implicitly virtual. They define behavior that must be present, more like an interface does.
You can update your npm to the latest stable version with the following command:
npm install npm@latest -g
Use PowerShell to run it. This command doesn't need windows administrator privileges and you can verify the result with npm -v
I linux this works too:
import sys
sys.path.extend(["/path/to/dotpy/file/"])
This answer relevant for Vue.js version 2
<th
class="initial "
v-on:click="myFilter"
v-bind:class="{ active: isActive }"
>
<span class="wkday">M</span>
</th>
The rest of the answer by Douglas is still applicable (setting up the new Vue instance with isActive: false
, etc).
Relevant docs: https://vuejs.org/v2/guide/class-and-style.html#Object-Syntax and https://vuejs.org/v2/guide/events.html#Method-Event-Handlers
When you add an object to $stateProvider.state
that object is then passed with the state. So you can add additional properties which you can read later on when needed.
Example route configuration
$stateProvider
.state('public', {
abstract: true,
module: 'public'
})
.state('public.login', {
url: '/login',
module: 'public'
})
.state('tool', {
abstract: true,
module: 'private'
})
.state('tool.suggestions', {
url: '/suggestions',
module: 'private'
});
The $stateChangeStart
event gives you acces to the toState
and fromState
objects. These state objects will contain the configuration properties.
Example check for the custom module property
$rootScope.$on('$stateChangeStart', function(e, toState, toParams, fromState, fromParams) {
if (toState.module === 'private' && !$cookies.Session) {
// If logged out and transitioning to a logged in page:
e.preventDefault();
$state.go('public.login');
} else if (toState.module === 'public' && $cookies.Session) {
// If logged in and transitioning to a logged out page:
e.preventDefault();
$state.go('tool.suggestions');
};
});
I didn't change the logic of the cookies because I think that is out of scope for your question.
You can create a Helper to get you this to work more modular.
Value publicStates
myApp.value('publicStates', function(){
return {
module: 'public',
routes: [{
name: 'login',
config: {
url: '/login'
}
}]
};
});
Value privateStates
myApp.value('privateStates', function(){
return {
module: 'private',
routes: [{
name: 'suggestions',
config: {
url: '/suggestions'
}
}]
};
});
The Helper
myApp.provider('stateshelperConfig', function () {
this.config = {
// These are the properties we need to set
// $stateProvider: undefined
process: function (stateConfigs){
var module = stateConfigs.module;
$stateProvider = this.$stateProvider;
$stateProvider.state(module, {
abstract: true,
module: module
});
angular.forEach(stateConfigs, function (route){
route.config.module = module;
$stateProvider.state(module + route.name, route.config);
});
}
};
this.$get = function () {
return {
config: this.config
};
};
});
Now you can use the helper to add the state configuration to your state configuration.
myApp.config(['$stateProvider', '$urlRouterProvider',
'stateshelperConfigProvider', 'publicStates', 'privateStates',
function ($stateProvider, $urlRouterProvider, helper, publicStates, privateStates) {
helper.config.$stateProvider = $stateProvider;
helper.process(publicStates);
helper.process(privateStates);
}]);
This way you can abstract the repeated code, and come up with a more modular solution.
Note: the code above isn't tested
But that doesn't seem like the proper way to do it..
That is indeed the proper way to do it (or at least a proper way to do it). This is a key aspect of promises, they're a pipeline, and the data can be massaged by the various handlers in the pipeline.
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("First handler", data);_x000D_
return data.map(entry => entry * 10);_x000D_
})_x000D_
.then(data => {_x000D_
console.log("Second handler", data);_x000D_
});
_x000D_
(catch
handler omitted for brevity. In production code, always either propagate the promise, or handle rejection.)
The output we see from that is:
First handler [1,2] Second handler [10,20]
...because the first handler gets the resolution of the two promises (1
and 2
) as an array, and then creates a new array with each of those multiplied by 10 and returns it. The second handler gets what the first handler returned.
If the additional work you're doing is synchronous, you can also put it in the first handler:
Example:
const promises = [_x000D_
new Promise(resolve => setTimeout(resolve, 0, 1)),_x000D_
new Promise(resolve => setTimeout(resolve, 0, 2))_x000D_
];_x000D_
Promise.all(promises)_x000D_
.then(data => {_x000D_
console.log("Initial data", data);_x000D_
data = data.map(entry => entry * 10);_x000D_
console.log("Updated data", data);_x000D_
return data;_x000D_
});
_x000D_
...but if it's asynchronous you won't want to do that as it ends up getting nested, and the nesting can quickly get out of hand.
There is much simpler way:
using System;
using System.Collections.Generic;
....
var caseInsensitiveDictionary = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase);
Let's see both the options:
1.) Use PHP inside Javascript
<script>
<?php $temp = 'hello';?>
console.log('<?php echo $temp; ?>');
</script>
Note: File name should be in .php only.
2.) Use Javascript variable inside PHP
<script>
var res = "success";
</script>
<?php
echo "<script>document.writeln(res);</script>";
?>
Here are the significant differences between lateinit var
and by lazy { ... }
delegated property:
lazy { ... }
delegate can only be used for val
properties, whereas lateinit
can only be applied to var
s, because it can't be compiled to a final
field, thus no immutability can be guaranteed;
lateinit var
has a backing field which stores the value, and by lazy { ... }
creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit
;
In addition to val
s, lateinit
cannot be used for nullable properties or Java primitive types (this is because of null
used for uninitialized value);
lateinit var
can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }
, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit
.
Initialization by lazy { ... }
is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy
overload). In the case of lateinit var
, it's up to the user's code to initialize the property correctly in multi-threaded environments.
A Lazy
instance can be saved, passed around and even used for multiple properties. On contrary, lateinit var
s do not store any additional runtime state (only null
in the field for uninitialized value).
If you hold a reference to an instance of Lazy
, isInitialized()
allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized
since Kotlin 1.2.
A lambda passed to by lazy { ... }
may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.
Also, there's another way not mentioned in the question: Delegates.notNull()
, which is suitable for deferred initialization of non-null properties, including those of Java primitive types.
You can simply write
new ArrayList<MyEnum>(Arrays.asList(MyEnum.values()));