Copy the ib_logfileXX and ibdata file from old mysql/data folder to the new mysql data folder and it will fix the issue
Just a minor contribution related to the Any
object.
I was working with unit tests around NotificationCenter
, which makes use of Any
as a parameter that I wanted to compare for equality.
However, since Any
cannot be used in an equality operation, it was necessary to change it. Ultimately, I settled on the following approach, which allowed me to get equality in my specific situation, shown here with a simplistic example:
func compareTwoAny(a: Any, b: Any) -> Bool {
return ObjectIdentifier(a as AnyObject) == ObjectIdentifier(b as AnyObject)
}
This function takes advantage of ObjectIdentifier, which provides a unique address for the object, allowing me to test.
One item to note though about ObjectIdentifier
per Apple at the above link:
In Swift, only class instances and metatypes have unique identities. There is no notion of identity for structs, enums, functions, or tuples.
$(document).ready(function () {
// Set button disabled
$('#save_info').button("disable");
$(".name").bind("change", function (event, ui) {
var edit = $("#your_name").val();
var edit_surname = $("#your_surname").val();
console.log(edit);
if (edit != ''&& edit_surname!='') {
//name.addClass('hightlight');
$('#save_info').button("enable");
console.log("enable");
return false;
} else {
$('#save_info').button("disable");
console.log("disable");
}
});
<ul data-role="listview" data-inset="true" data-split-icon="gear" data-split-theme="d">
<li>
<input type="text" name="your_name" id="your_name" class="name" value="" placeholder="Frist Name" /></li>
<li>
<input type="text" name="your_surname" id="your_surname" class="name" value="" placeholder="Last Name" /></li>
<li>
<button data-icon="info" href="" data-role="submit" data-inline="true" id="save_info">
Save</button>
This one work for me you might need to workout the logic, of disable -enable
OK, you should apply something like this to your dataset. Do not replace & save or you'll destroy your data! And, btw, you should (almost) never remove outliers from your data:
remove_outliers <- function(x, na.rm = TRUE, ...) {
qnt <- quantile(x, probs=c(.25, .75), na.rm = na.rm, ...)
H <- 1.5 * IQR(x, na.rm = na.rm)
y <- x
y[x < (qnt[1] - H)] <- NA
y[x > (qnt[2] + H)] <- NA
y
}
To see it in action:
set.seed(1)
x <- rnorm(100)
x <- c(-10, x, 10)
y <- remove_outliers(x)
## png()
par(mfrow = c(1, 2))
boxplot(x)
boxplot(y)
## dev.off()
And once again, you should never do this on your own, outliers are just meant to be! =)
EDIT: I added na.rm = TRUE
as default.
EDIT2: Removed quantile
function, added subscripting, hence made the function faster! =)
It's probably easiest to create your query object directly as:
Test.find({
$and: [
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
]
}, function (err, results) {
...
}
But you can also use the Query#and
helper that's available in recent 3.x Mongoose releases:
Test.find()
.and([
{ $or: [{a: 1}, {b: 1}] },
{ $or: [{c: 1}, {d: 1}] }
])
.exec(function (err, results) {
...
});
you can define a route in web.php
Route::get('/clear/route', 'ConfigController@clearRoute');
and make ConfigController.php like this
class ConfigController extends Controller
{
public function clearRoute()
{
\Artisan::call('route:clear');
}
}
and go to that route on server example http://your-domain/clear/route
The comma expression takes on the value of the last (eg. right-most) expression.
So in your first loop, the only controlling expression is i<=5
; and j>=0
is ignored.
In the second loop, j>=0
controls the loop, and i<=5
is ignored.
As for a reason... there is no reason. This code is just wrong. The first part of the comma-expressions does nothing except confuse programmers. If a serious programmer wrote this, they should be ashamed of themselves and have their keyboard revoked.
Well the folks who are trying to download either on *ix or Ec2 machine would suggest to clean approach in below steps:
$ mkdir android-sdk
$ cd android-sdk
$ mkdir cmdline-tools
$ cd cmdline-tools
$ wget https://dl.google.com/android/repository/commandlinetools-linux-*.zip
$ unzip commandlinetools-linux-*.zip
The king - sdkmanager lives inside
cmdline-tools/tools/bin
, you'd better set in PATH environment variable.
but cmdline-tools
should not be set as ANDROID_HOME
. Because later, when updating Android SDK, or installing more packages, the other packages will be placed under ANDROID_HOME
, but not under cmdline-tools
.
The final, complete ANDROID_HOME directory structure should look like below, consist of quite a few sub-directories:
build-tools, cmdline-tools, emulator, licenses, patcher, platform-tools, platforms, tools
.
You can easily point out that build-tools
and cmdline-tools
are siblings, all resides inside the parent ANDROID_HOME.
Add SDK tools directory in PATH environment variable to make executable available globally. Add below line either in ~/.bashrc
or ~/.profile
file to make it permanent.
In order to edit the ~/.bashrc
simply can be editable in vim mode
$ vim .bashrc
Now set your preferred ANDROID_HOME
in .bashrc
file :
export ANDROID_HOME=/home/<user>/android-sdk
export PATH=${PATH}:$ANDROID_HOME/cmdline-tools/tools/bin:$ANDROID_HOME/platform-tools
here strange thing that we haven't download the platform-tools
directory as of now but mentoning it under path but let it be as it will help you avoid remodification on the same file later.
Now go inside the same directory:
$ cd android-sdk
NOTE
: well in first attempt sdkmanager command didnt found for me so I close the terminal and again created the connection or you can also refresh the same if it works for you.
after that use the sdkmanager to list and install the packages needed:
$ sdkmanager "platform-tools" "platforms;android-27" "build-tools;27.0.3"
Hence Sdkmanager path is already set it will be accessible from anywhere:
$ sdkmanager --update
$ sdkmanager --list
Installed packages:=====================] 100% Computing updates...
Path | Version | Description | Location
------- | ------- | ------- | -------
build-tools;27.0.3 | 27.0.3 | Android SDK Build-Tools 27.0.3 | build-tools/27.0.3/
emulator | 30.0.12 | Android Emulator | emulator/
patcher;v4 | 1 | SDK Patch Applier v4 | patcher/v4/
platform-tools | 30.0.1 | Android SDK Platform-Tools | platform-tools/
platforms;android-27 | 3 | Android SDK Platform 27 | platforms/android-27/
1) Best practice is to make new javascript file like my.js. Make this file into your js folder in root directory -> js/my.js . 2) In my.js file add your code inside of $(document).ready(function(){}) scope.
$(document).ready(function(){
$(".icon-bg").click(function () {
$(".btn").toggleClass("active");
$(".icon-bg").toggleClass("active");
$(".container").toggleClass("active");
$(".box-upload").toggleClass("active");
$(".box-caption").toggleClass("active");
$(".box-tags").toggleClass("active");
$(".private").toggleClass("active");
$(".set-time-limit").toggleClass("active");
$(".button").toggleClass("active");
});
$(".button").click(function () {
$(".button-overlay").toggleClass("active");
});
$(".iconmelon").click(function () {
$(".box-upload-ing").toggleClass("active");
$(".iconmelon-loaded").toggleClass("active");
});
$(".private").click(function () {
$(".private-overlay").addClass("active");
$(".private-overlay-wave").addClass("active");
});
});
3) add your new js file into your html
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script src="/js/my.js"></script>
</head>
Thanks for some great answers. Nothing original to add, but here are some progressive rewrites of qneill's answer using some useful Python facilities. I hope you agree they simplify and clarify the code.
import base64
def qneill_encode(key, clear):
enc = []
for i in range(len(clear)):
key_c = key[i % len(key)]
enc_c = chr((ord(clear[i]) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def qneill_decode(key, enc):
dec = []
enc = base64.urlsafe_b64decode(enc)
for i in range(len(enc)):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(enc[i]) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
enumerate()
-- pair the items in a list with their indexiterate over the characters in a string
def encode_enumerate(key, clear):
enc = []
for i, ch in enumerate(clear):
key_c = key[i % len(key)]
enc_c = chr((ord(ch) + ord(key_c)) % 256)
enc.append(enc_c)
return base64.urlsafe_b64encode("".join(enc))
def decode_enumerate(key, enc):
dec = []
enc = base64.urlsafe_b64decode(enc)
for i, ch in enumerate(enc):
key_c = key[i % len(key)]
dec_c = chr((256 + ord(ch) - ord(key_c)) % 256)
dec.append(dec_c)
return "".join(dec)
build lists using a list comprehension
def encode_comprehension(key, clear):
enc = [chr((ord(clear_char) + ord(key[i % len(key)])) % 256)
for i, clear_char in enumerate(clear)]
return base64.urlsafe_b64encode("".join(enc))
def decode_comprehension(key, enc):
enc = base64.urlsafe_b64decode(enc)
dec = [chr((256 + ord(ch) - ord(key[i % len(key)])) % 256)
for i, ch in enumerate(enc)]
return "".join(dec)
Often in Python there's no need for list indexes at all. Eliminate loop index variables entirely using zip and cycle:
from itertools import cycle
def encode_zip_cycle(key, clear):
enc = [chr((ord(clear_char) + ord(key_char)) % 256)
for clear_char, key_char in zip(clear, cycle(key))]
return base64.urlsafe_b64encode("".join(enc))
def decode_zip_cycle(key, enc):
enc = base64.urlsafe_b64decode(enc)
dec = [chr((256 + ord(enc_char) - ord(key_char)) % 256)
for enc_char, key_char in zip(enc, cycle(key))]
return "".join(dec)
and some tests...
msg = 'The quick brown fox jumps over the lazy dog.'
key = 'jMG6JV3QdtRh3EhCHWUi'
print('cleartext: {0}'.format(msg))
print('ciphertext: {0}'.format(encode_zip_cycle(key, msg)))
encoders = [qneill_encode, encode_enumerate, encode_comprehension, encode_zip_cycle]
decoders = [qneill_decode, decode_enumerate, decode_comprehension, decode_zip_cycle]
# round-trip check for each pair of implementations
matched_pairs = zip(encoders, decoders)
assert all([decode(key, encode(key, msg)) == msg for encode, decode in matched_pairs])
print('Round-trips for encoder-decoder pairs: all tests passed')
# round-trip applying each kind of decode to each kind of encode to prove equivalent
from itertools import product
all_combinations = product(encoders, decoders)
assert all(decode(key, encode(key, msg)) == msg for encode, decode in all_combinations)
print('Each encoder and decoder can be swapped with any other: all tests passed')
>>> python crypt.py
cleartext: The quick brown fox jumps over the lazy dog.
ciphertext: vrWsVrvLnLTPlLTaorzWY67GzYnUwrSmvXaix8nmctybqoivqdHOic68rmQ=
Round-trips for encoder-decoder pairs: all tests passed
Each encoder and decoder can be swapped with any other: all tests passed
A quick google indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!
See also this article http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/
There's no reasonable way to check whether a value has been initialized.
If you care about whether something has been initialized, instead of trying to check for it, put code into the constructor(s) to ensure that they are always initialized and be done with it.
Check this out! It was built no longer ago in 2014.
Get a list of country/state/city in a hierarchy using geonames webservice
you can use git svn in the following way.
git svn clone https://github.com/lodash/lodash/trunk/test
This way you don't have to go through the pain of setting svn, specifically for Windows users.
Short answer: the trade off is recursion is faster and for loops take up less memory in almost all cases. However there are usually ways to change the for loop or recursion to make it run faster
The answer is to use a JSONArray as well, and to dive "deep" into the tree structure:
JSONArray arr = new JSONArray();
arr.put (...); // a new JSONObject()
arr.put (...); // a new JSONObject()
JSONObject json = new JSONObject();
json.put ("aoColumnDefs",arr);
I've used a mix of two howtos: Jason's and alex's. With the second we have the advantage of being able to debug. I'll mostly just copy both below (and simplify alex's):
Update Jan 2012: this still works on SDK 4.2.1 and iOS 5.0.1 - I've just tested it all on a new computer and device!
Patch your iPhone SDK to allow the use of this certificate:
Launch Keychain Access.app. With no items selected, from the Keychain menu select Certificate Assistant, then Create a Certificate.
Click Continue
Click Continue
Blank out the Email address field.
Click Continue until complete.
You should see "This root certificate is not trusted". This is expected.
Set the iPhone SDK to allow the self-signed certificate to be used:
sudo /usr/bin/sed -i .bak 's/XCiPhoneOSCodeSignContext/XCCodeSignContext/' /Developer/Platforms/iPhoneOS.platform/Info.plist
If you have Xcode open, restart it for this change to take effect.
And if you're on iOS 5, that's it! Try it now! It may not allow debugging, but the app will be there!
I was very surprised by this because, as you should know, I've got no idea on what all those hackings are all about! All I did was improving a little bit what I found elsewhere, as I pointed.
So yeah, the whole method doesn't work the same way anymore and I couldn't bother to find a new one... Except for this, which uses a tool called Theos but I couldn't go through the whole process.
Finally, if you need to uninstall it for whatever reason, check the end of this post. In my case, I had to because I couldn't figure out why all of the blue this whole method stopped working, and I couldn't care anymore since we've already got the long waited license. (Freaking DUNS number takes so long...)
.
.
.
.
.
On your jailbroken iPhone, install the app AppSync by adding source ** http://repo.hackyouriphone.org**
Remove SDK requirements for code sign and entitlements (I'm loving sed!):
sudo /usr/bin/sed -i .bak '/_REQUIRED/N;s/YES/NO/' /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/SDKSettings.plist
Pay attention to the iPhoneOS5.0.sdk
part. If you're, for instance, using iOS 4.2 SDK, just replace it accordingly:
sudo /usr/bin/sed -i .bak '/_REQUIRED/N;s/YES/NO/' /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/SDKSettings.plist
Conclude the requirement removal through patching Xcode. This means binary editing:
cd /Developer/Platforms/iPhoneOS.platform/Developer/Library/Xcode/Plug-ins/iPhoneOS\ Build\ System\ Support.xcplugin/Contents/MacOS/
dd if=iPhoneOS\ Build\ System\ Support of=working bs=500 count=255
printf "\xc3\x26\x00\x00" >> working
/bin/mv -n iPhoneOS\ Build\ System\ Support iPhoneOS\ Build\ System\ Support.original
/bin/mv working iPhoneOS\ Build\ System\ Support
chmod a+x iPhoneOS\ Build\ System\ Support
If you have Xcode open, restart it for this change (and last one) to take effect.
Open "Project>Edit Project Settings" (from the menu). Click on the "Build" tab. Find "Code Signing Identity" and its child "Any iPhoneOS Device" in the list, and set both to the entry "Don't Code Sign":
After this feel free to undo step 3. At least in my case it went just fine.
Setting Xcode to code sign with our custom made self-signed certificate (the first how-to). This step can probably be skipped if you don't want to be able to debug:
mkdir /Developer/iphoneentitlements401
cd /Developer/iphoneentitlements401
curl -O http://www.alexwhittemore.com/iphone/gen_entitlements.txt
mv gen_entitlements.txt gen_entitlements.py
chmod 777 gen_entitlements.py
Plug your iPhone in and open Xcode. Open Window>Organizer. Select the device from the list on the left hand side, and click "Use for development." You'll be prompted for a provisioning website login, click cancel. It's there to make legitimate provisioning easier, but doesn't make illegitimate not-provisioning more difficult.
Now You have to do this last part for every new project you make. Go to the menu Project > New Build Phase > New Run Script Build Phase. In the window, copy/paste this:
export CODESIGN_ALLOCATE=/Developer/Platforms/iPhoneOS.platform/Developer/usr/bin/codesign_allocate
if [ "${PLATFORM_NAME}" == "iphoneos" ]; then
/Developer/iphoneentitlements401/gen_entitlements.py "my.company.${PROJECT_NAME}" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent";
codesign -f -s "iPhone Developer" --entitlements "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/${PROJECT_NAME}.xcent" "${BUILT_PRODUCTS_DIR}/${WRAPPER_NAME}/"
fi
.
.
.
.
For the 1st part:
sudo mv -f /Developer/Platforms/iPhoneOS.platform/Info.plist.bak /Developer/Platforms/iPhoneOS.platform/Info.plist
For the 2nd part:
sudo mv -f /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/SDKSettings.plist.bak /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS5.0.sdk/SDKSettings.plist
sudo mv -f iPhoneOS\ Build\ System\ Support.original iPhoneOS\ Build\ System\ Support
in case you did do the step 3 instead of 2, simply modify it accordingly as well:
sudo mv -f /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/SDKSettings.plist.bak /Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS4.2.sdk/SDKSettings.plist
for the rest, is just reverting what you did on XCode and deleting /Developer/iphoneentitlements401/gen_entitlements.py
if you want:
sudo rm -f /Developer/iphoneentitlements401/gen_entitlements.py
The simplest approach is to use ExecutorService.invokeAll()
which does what you want in a one-liner. In your parlance, you'll need to modify or wrap ComputeDTask
to implement Callable<>
, which can give you quite a bit more flexibility. Probably in your app there is a meaningful implementation of Callable.call()
, but here's a way to wrap it if not using Executors.callable()
.
ExecutorService es = Executors.newFixedThreadPool(2);
List<Callable<Object>> todo = new ArrayList<Callable<Object>>(singleTable.size());
for (DataTable singleTable: uniquePhrases) {
todo.add(Executors.callable(new ComputeDTask(singleTable)));
}
List<Future<Object>> answers = es.invokeAll(todo);
As others have pointed out, you could use the timeout version of invokeAll()
if appropriate. In this example, answers
is going to contain a bunch of Future
s which will return nulls (see definition of Executors.callable()
. Probably what you want to do is a slight refactoring so you can get a useful answer back, or a reference to the underlying ComputeDTask
, but I can't tell from your example.
If it isn't clear, note that invokeAll()
will not return until all the tasks are completed. (i.e., all the Future
s in your answers
collection will report .isDone()
if asked.) This avoids all the manual shutdown, awaitTermination, etc... and allows you to reuse this ExecutorService
neatly for multiple cycles, if desired.
There are a few related questions on SO:
None of these are strictly on-point for your question, but they do provide a bit of color about how folks think Executor
/ExecutorService
ought to be used.
I use this on my macbook:
" configure expanding of tabs for various file types
au BufRead,BufNewFile *.py set expandtab
au BufRead,BufNewFile *.c set expandtab
au BufRead,BufNewFile *.h set expandtab
au BufRead,BufNewFile Makefile* set noexpandtab
" --------------------------------------------------------------------------------
" configure editor with tabs and nice stuff...
" --------------------------------------------------------------------------------
set expandtab " enter spaces when tab is pressed
set textwidth=120 " break lines when line length increases
set tabstop=4 " use 4 spaces to represent tab
set softtabstop=4
set shiftwidth=4 " number of spaces to use for auto indent
set autoindent " copy indent from current line when starting a new line
" make backspaces more powerfull
set backspace=indent,eol,start
set ruler " show line and column number
syntax on " syntax highlighting
set showcmd " show (partial) command in status line
(edited to only show stuff related to indent / tabs)
Attention: this is an extremely rough and oversimplified sketch, assuming the simplest possible HTTP request (no HTTPS, no HTTP2, no extras), simplest possible DNS, no proxies, single-stack IPv4, one HTTP request only, a simple HTTP server on the other end, and no problems in any step. This is, for most contemporary intents and purposes, an unrealistic scenario; all of these are far more complex in actual use, and the tech stack has become an order of magnitude more complicated since this was written. With this in mind, the following timeline is still somewhat valid:
Again, discussion of each of these points have filled countless pages; take this only as a summary, abridged for the sake of clarity. Also, there are many other things happening in parallel to this (processing typed-in address, speculative prefetching, adding page to browser history, displaying progress to user, notifying plugins and extensions, rendering the page while it's downloading, pipelining, connection tracking for keep-alive, cookie management, checking for malicious content etc.) - and the whole operation gets an order of magnitude more complex with HTTPS (certificates and ciphers and pinning, oh my!).
If you're on Windows:
Go to your php.ini file and remove the ;
mark from the beginning of the following line:
;extension=php_curl.dll
After you have saved the file you must restart your HTTP server software (e.g. Apache) before this can take effect.
For Ubuntu 13.0 and above, simply use the debundled package. In a terminal type the following to install it and do not forgot to restart server.
sudo apt-get install php-curl
Or if you're using the old PHP5
sudo apt-get install php5-curl
or
sudo apt-get install php5.6-curl
Then restart apache to activate the package with
sudo service apache2 restart
We can get the distinct similar to the example shown below
//example
var distinctValues = DetailedBreakDown_Table.AsEnumerable().Select(r => new
{
InvestmentVehicleID = r.Field<string>("InvestmentVehicleID"),
Universe = r.Field<string>("Universe"),
AsOfDate = _imqDate,
Ticker = "",
Cusip = "",
PortfolioDate = r.Field<DateTime>("PortfolioDate")
} ).Distinct();
In my instance, there was something completely odd that I'm not sure what the cause was. An entire folder was committed previously. I could see it in Git, Windows Explorer, and GitHub, but any changes I made to the folder itself and the files in it were ignored. Using git check-ignore
to see what was ignoring it, and attempting to remove it using git rm --cached
had no impact. The changes were not able to be staged.
I fixed it by:
Here's a new way of putting dots in password
<EditText
android:id="@+id/loginPassword"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:inputType="textPassword"
android:hint="@string/pwprompt" /
add android:inputType = "textPassword"
When generating CSR is possible to specify -ext attribute again to have it inserted in the CSR
keytool -certreq -file test.csr -keystore test.jks -alias testAlias -ext SAN=dns:test.example.com
complete example here: How to create CSR with SANs using keytool
One way is that In case of Session Expire, in every action you have to check its session and if it is null then redirect to Login page.
But this is very hectic method
To over come this you need to create your own ActionFilterAttribute
which will do this, you just need to add this attribute in every action method.
Here is the Class which overrides ActionFilterAttribute.
public class SessionExpireFilterAttribute : ActionFilterAttribute
{
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
HttpContext ctx = HttpContext.Current;
// check if session is supported
CurrentCustomer objCurrentCustomer = new CurrentCustomer();
objCurrentCustomer = ((CurrentCustomer)SessionStore.GetSessionValue(SessionStore.Customer));
if (objCurrentCustomer == null)
{
// check if a new session id was generated
filterContext.Result = new RedirectResult("~/Users/Login");
return;
}
base.OnActionExecuting(filterContext);
}
}
Then in action just add this attribute like so:
[SessionExpire]
public ActionResult Index()
{
return Index();
}
This will do you work.
From the C# programming guide on MSDN:
The parameter of the Main method is a String array that represents the command-line arguments
So, if I had a program (MyApp.exe) like this:
class Program
{
static void Main(string[] args)
{
foreach (var arg in args)
{
Console.WriteLine(arg);
}
}
}
That I started at the command line like this:
MyApp.exe Arg1 Arg2 Arg3
The Main method would be passed an array that contained three strings: "Arg1", "Arg2", "Arg3".
If you need to pass an argument that contains a space then wrap it in quotes. For example:
MyApp.exe "Arg 1" "Arg 2" "Arg 3"
Command line arguments commonly get used when you need to pass information to your application at runtime. For example if you were writing a program that copies a file from one location to another you would probably pass the two locations as command line arguments. For example:
Copy.exe C:\file1.txt C:\file2.txt
`
def transpose(m):_x000D_
return(list(map(list,list(zip(*m)))))
_x000D_
`This function will return the transpose
jsonObj.profile-id
is a subtraction expression (i.e. jsonObj.profile - id
).
To access a key that contains characters that cannot appear in an identifier, use brackets:
jsonObj["profile-id"]
I just want to add that there is a master list of IntelliJ suppress parameters at: https://gist.github.com/vegaasen/157fbc6dce8545b7f12c
It looks fairly comprehensive. Partial:
Warning Description - Warning Name
"Magic character" MagicCharacter
"Magic number" MagicNumber
'Comparator.compare()' method does not use parameter ComparatorMethodParameterNotUsed
'Connection.prepare*()' call with non-constant string JDBCPrepareStatementWithNonConstantString
'Iterator.hasNext()' which calls 'next()' IteratorHasNextCallsIteratorNext
'Iterator.next()' which can't throw 'NoSuchElementException' IteratorNextCanNotThrowNoSuchElementException
'Statement.execute()' call with non-constant string JDBCExecuteWithNonConstantString
'String.equals("")' StringEqualsEmptyString
'StringBuffer' may be 'StringBuilder' (JDK 5.0 only) StringBufferMayBeStringBuilder
'StringBuffer.toString()' in concatenation StringBufferToStringInConcatenation
'assert' statement AssertStatement
'assertEquals()' between objects of inconvertible types AssertEqualsBetweenInconvertibleTypes
'await()' not in loop AwaitNotInLoop
'await()' without corresponding 'signal()' AwaitWithoutCorrespondingSignal
'break' statement BreakStatement
'break' statement with label BreakStatementWithLabel
'catch' generic class CatchGenericClass
'clone()' does not call 'super.clone()' CloneDoesntCallSuperClone
try adding android:scaleType="fitXY"
to your ImageView
.
When you dont want to put your hand yon regular expression (may be you should) you could first replace all "Milan Vasic" string with "Milan".
And than replace all "Milan" Strings with "Milan Vasic".
#include <algorithm>
static const size_t v_size = 2000;
int v[v_size];
// Fill the array by values
std::sort(v,v+v_size);
In C++11:
#include <algorithm>
#include <array>
std::array<int, 2000> v;
// Fill the array by values
std::sort(v.begin(),v.end());
In theory, maven does not allow to use a property to set a parent version.
In your case, maven can simply not figure out that the 0.0.1-SNAPSHOT version of your parent pom is the one that is currently in your project, and so it tries to find it in your local repo. It probably finds one since it is a snapshot, but it is an old version that probably not contains your Dependency Management section.
There is a workaround though :
Simply change the parent section in the child pom with this :
<parent>
<groupId>com.sw.system4</groupId>
<artifactId>system4-parent</artifactId>
<version>${system4.version}</version>
<relativePath>../pom.xml</relativePath> <!-- this must match your parent pom location -->
</parent>
In my case was facing the same issue, especially the first pull request trying after remotely adding a Git repository. The following error was facing.
fatal: refusing to merge unrelated histories on every try
Use the --allow-unrelated-histories command. It works perfectly.
git pull origin branchname --allow-unrelated-histories
In XSLT 1.0 the upper-case()
and lower-case()
functions are not available.
If you're using a 1.0 stylesheet the common method of case conversion is translate()
:
<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />
<xsl:template match="/">
<xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>
this is my code sample. I have comma separated numbers for multi select drop down and want to select options multiple options from comma separated values.
var selected_tags_arr = new Array();
var selected_tags = 1,2,4;
selected_tags_arr = selected_tags.split(",");
$('#contact_tags option').each(function (){
var option_val = this.value;
for (var i in selected_tags_arr) {
if(selected_tags_arr[i] == option_val){
$("#contact_tags option[value='" + this.value + "']").attr("selected", 1);
}
}
});
For simple stuff, System.currentTimeMillis() can work.
It's actually so common that my IDE is setup so that upon entering "t0" it generates me the following line:
final long t0 = System.currentTimeMillis()
But for more complicated things, you'll probably want to use statistical time measurements, like here (scroll down a bit and look at the time measurements expressed including standard deviations etc.):
Using ClipRRect
you need to hardcode BorderRadius
, so if you need complete circular stuff, use ClipOval
instead.
ClipOval(
child: Image.network(
"image_url",
height: 100,
width: 100,
fit: BoxFit.cover,
),
),
img
tag but without background-image
This solution retains the img
tag so that we do not lose the ability to drag or right-click to save the image but without background-image
just center and crop with css.
Maintain the aspect ratio fine except in very hight images. (check the link)
Markup
<div class="center-cropped">
<img src="http://placehold.it/200x150" alt="" />
</div>
? CSS
div.center-cropped {
width: 100px;
height: 100px;
overflow:hidden;
}
div.center-cropped img {
height: 100%;
min-width: 100%;
left: 50%;
position: relative;
transform: translateX(-50%);
}
The first argument to nonrecursivecountcells() doesn't have a variable name. You try to reference it as grid in the function body, so you probably want to call it grid.
It's (Get-NetTCPConnection -LocalPort "port no.").OwningProcess
You can just give it try to your code:
Array ints = Array.CreateInstance(typeof(int), 5);
ints.SetValue(10, 0);
ints.SetValue(20, 1);
ints.SetValue(10, 2);
ints.SetValue(34, 3);
ints.SetValue(113, 4);
int[] anyVariable=(int[])ints;
Then you can just use the anyVariable as your code.
Since you haven't given any indication to what you want, here is a link to 101 LINQ samples that use all the different LINQ methods: 101 LINQ Samples
Also, you should really really really change your List
into a strongly typed list (List<T>
), properly define T, and add instances of T to your list. It will really make the queries much easier since you won't have to cast everything all the time.
To get upper case version of a string you can use str.upper
:
s = 'sdsd'
s.upper()
#=> 'SDSD'
On the other hand string.ascii_uppercase
is a string containing all ASCII letters in upper case:
import string
string.ascii_uppercase
#=> 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
Answer given by user @JPM and @usman are really very useful. It works fine but in my case it come in onReceive
multiple time in my case 4 times so my code execute multiple time.
I do some modification and make as per my requirement and now it comes only 1 time
Here is java class for Broadcast.
public class WifiReceiver extends BroadcastReceiver {
String TAG = getClass().getSimpleName();
private Context mContext;
@Override
public void onReceive(Context context, Intent intent) {
mContext = context;
if (intent.getAction().equals(ConnectivityManager.CONNECTIVITY_ACTION)) {
ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo networkInfo = cm.getActiveNetworkInfo();
if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI &&
networkInfo.isConnected()) {
// Wifi is connected
WifiManager wifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
String ssid = wifiInfo.getSSID();
Log.e(TAG, " -- Wifi connected --- " + " SSID " + ssid );
}
}
else if (intent.getAction().equalsIgnoreCase(WifiManager.WIFI_STATE_CHANGED_ACTION))
{
int wifiState = intent.getIntExtra(WifiManager.EXTRA_WIFI_STATE, WifiManager.WIFI_STATE_UNKNOWN);
if (wifiState == WifiManager.WIFI_STATE_DISABLED)
{
Log.e(TAG, " ----- Wifi Disconnected ----- ");
}
}
}
}
In AndroidManifest
<receiver android:name=".util.WifiReceiver" android:enabled="true">
<intent-filter>
<action android:name="android.net.wifi.WIFI_STATE_CHANGED" />
<action android:name="android.net.conn.CONNECTIVITY_CHANGE"/>
</intent-filter>
</receiver>
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
You actually want to do
import os
os.environ["MY_DATA"] = "my_export"
this is an old post but...
just surprised that nobody talk about pg_hba file as it can be a good reason to get this error code.
Check here for those who forgot to configure it: http://www.postgresql.org/docs/current/static/auth-pg-hba-conf.html
After executing the below regex, your answer is in the first capture.
/^(.*?)\.txt/
For jQuery, do you mean like this?
$('#object').css('display');
You can check it like this:
if($('#object').css('display') === 'block')
{
//do something
}
else
{
//something else
}
try this
echo $sqlupdate1 = "UPDATE table SET commodity_quantity=$qty WHERE user='".$rows['user']."' ";
I would vote no. Hibernate doesn't seem to understand when datatypes for columns have changed. Examples (using MySQL):
String with @Column(length=50) ==> varchar(50)
changed to
String with @Column(length=100) ==> still varchar(50), not changed to varchar(100)
@Temporal(TemporalType.TIMESTAMP,TIME,DATE) will not update the DB columns if changed
There are probably other examples as well, such as pushing the length of a String column up over 255 and seeing it convert to text, mediumtext, etc etc.
Granted, I don't think there is really a way to "convert datatypes" with without creating a new column, copying the data and blowing away the old column. But the minute your database has columns which don't reflect the current Hibernate mapping you are living very dangerously...
Flyway is a good option to deal with this problem:
Make sure that the directory containing the private key files is set to 700
chmod 700 ~/.ec2
foreach (DataColumn col in rightsTable.Columns)
{
foreach (DataRow row in rightsTable.Rows)
{
Console.WriteLine(row[col.ColumnName].ToString());
}
}
The function argument to setTimeout
is closing over the loop variable. The loop finishes before the first timeout and displays the current value of i
, which is 3
.
Because JavaScript variables only have function scope, the solution is to pass the loop variable to a function that sets the timeout. You can declare and call such a function like this:
for (var i = 1; i <= 2; i++) {
(function (x) {
setTimeout(function () { alert(x); }, 100);
})(i);
}
Even though this is an already answered question, I'd leave another option that IMO is a lot easier to read:
BackgroundWorker worker = new BackgroundWorker();
worker.DoWork += (obj, e) => WorkerDoWork(value, text);
worker.RunWorkerAsync();
And on the handler method:
private void WorkerDoWork(int value, string text) {
...
}
Just write:
date("Y") // A full numeric representation of a year, 4 digits
// Examples: 1999 or 2003
Or:
date("y"); // A two digit representation of a year Examples: 99 or 03
And 'echo' this value...
Try this
$client = new \GuzzleHttp\Client();
$client->post(
'http://www.example.com/user/create',
array(
'form_params' => array(
'email' => '[email protected]',
'name' => 'Test user',
'password' => 'testpassword'
)
)
);
You shouldn't use LIs in email. They are unpredictable across email clients. Instead you have to code each bullet point like this:
<table width="100%" cellspacing="0" border="0" cellpadding="0">
<tr>
<td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">•</td>
<td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the first bullet point</td>
</tr>
<tr>
<td align="left" valign="top" width="10" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">•</td>
<td align="left" valign="top" style="font-family:Arial, Helvetica, Sans-Serif; font-size:12px;">This is the second bullet point</td>
</tr>
</table>
This will ensure that your bullets work in every email client.
So 4 years later, Microsoft has open sourced their JDBC driver on Github. I got a notification about this question today, and went and had a look, and I believe I have found the culprit here, mssql-jdbc/src/main/java/com/microsoft/sqlserver/jdbc/SQLServerStatement.java:1713
.
Basically, the driver tries to understand what SQL Server sends back if it is not a definite result set. According to the comments, it goes like this:
Check for errors first. (ln 1669)
Not an error. Is it a result set? (ln 1680)
Not an error or a result set. Maybe a result from a T-SQL statement? That is, one of the following:
- a positive count of the number of rows affected (from INSERT, UPDATE, or DELETE),
- a zero indicating no rows affected, or the statement was DDL, or
- a -1 indicating the statement succeeded, but there is no update count information available (translates to Statement.SUCCESS_NO_INFO in batch update count arrays). (ln 1706)
None of the above. Last chance here... Going into the parser above, we know moreResults was initially true. If we come out with moreResults false, the we hit a DONE token (either DONE (FINAL) or DONE (RPC in batch)) that indicates that the batch succeeded overall, but that there is no information on individual statements' update counts. This is similar to the last case above, except that there is no update count. That is: we have a successful result (return true), but we have no other information about it (updateCount = -1). (ln 1693)
Only way to get here (moreResults is still true, but no apparent results of any kind) is if the TDSParser didn't actually parse anything. That is, we are at EOF in the response. In that case, there truly are no more results. We're done. (ln 1717)
(Emphasis mine)
So you guys were right in the end. SQL simply can't tell how many rows are affected, and defaults to -1
. :)
[Updated to adapt to modern pandas
, which has isnull
as a method of DataFrame
s..]
You can use isnull
and any
to build a boolean Series and use that to index into your frame:
>>> df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
>>> df.isnull()
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
>>> df.isnull().any(axis=1)
0 False
1 True
2 True
3 False
4 False
dtype: bool
>>> df[df.isnull().any(axis=1)]
0 1 2
1 0 NaN 0
2 0 0 NaN
[For older pandas
:]
You could use the function isnull
instead of the method:
In [56]: df = pd.DataFrame([range(3), [0, np.NaN, 0], [0, 0, np.NaN], range(3), range(3)])
In [57]: df
Out[57]:
0 1 2
0 0 1 2
1 0 NaN 0
2 0 0 NaN
3 0 1 2
4 0 1 2
In [58]: pd.isnull(df)
Out[58]:
0 1 2
0 False False False
1 False True False
2 False False True
3 False False False
4 False False False
In [59]: pd.isnull(df).any(axis=1)
Out[59]:
0 False
1 True
2 True
3 False
4 False
leading to the rather compact:
In [60]: df[pd.isnull(df).any(axis=1)]
Out[60]:
0 1 2
1 0 NaN 0
2 0 0 NaN
Short of using a local templating system like many hundreds now exist in every scripting language or even using your homebrewed one with sed
or m4
and sending the result over to your server, no, you'd need at least SSI.
I find attributes to be cleaner to use than manually adding them via code. Here is a simple example.
[RoutePrefix("api/example")]
public class ExampleController : ApiController
{
[HttpGet]
[Route("get1/{param1}")] // /api/example/get1/1?param2=4
public IHttpActionResult Get(int param1, int param2)
{
Object example = null;
return Ok(example);
}
}
You also need this in your webapiconfig
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
config.Routes.MapHttpRoute(
name: "ActionApi",
routeTemplate: "api/{controller}/{action}/{id}",
defaults: new { id = RouteParameter.Optional }
);
Some Good Links http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api This one explains routing better. http://www.asp.net/web-api/overview/web-api-routing-and-actions/routing-in-aspnet-web-api
If you have both Python2 and Python3 installed on your Mac, you can use
python --version
to check the version of Python2, and
python3 --version
to check the version of Python3.
However, if only Python3 is installed, then your system might use python
instead of python3
for Python3. In this case, you can just use
python --version
to check the version of Python3.
There is a lot of confusion regarding how "this" keyword is interpreted in JavaScript. Hopefully this article will lay all those to rest once and for all. And a lot more. Please read the entire article carefully. Be forewarned that this article is long.
Irrespective of the context in which it is used, "this" always references the "current object" in Javascript. However, what the "current object" is differs according to context. The context may be exactly 1 of the 6 following:
The following describes each of this contexts one by one:
Global Context (i.e. Outside all functions):
Outside all functions (i.e. in global context) the "current object" (and hence the value of "this") is always the "window" object for browsers.
Inside Direct "Non Bound Function" Call:
Inside a Direct "Non Bound Function" Call, the object that invoked the function call becomes the "current object" (and hence the value of "this"). If a function is called without a explicit current object, the current object is either the "window" object (For Non Strict Mode) or undefined (For Strict Mode) . Any function (or variable) defined in Global Context automatically becomes a property of the "window" object.For e.g Suppose function is defined in Global Context as
function UserDefinedFunction(){
alert(this)
}
it becomes the property of the window object, as if you have defined it as
window.UserDefinedFunction=function(){
alert(this)
}
In "Non Strict Mode", Calling/Invoking this function directly through "UserDefinedFunction()" will automatically call/invoke it as "window.UserDefinedFunction()" making "window" as the "current object" (and hence the value of "this") within "UserDefinedFunction".Invoking this function in "Non Strict Mode" will result in the following
UserDefinedFunction() // displays [object Window] as it automatically gets invoked as window.UserDefinedFunction()
In "Strict Mode", Calling/Invoking the function directly through "UserDefinedFunction()" will "NOT" automatically call/invoke it as "window.UserDefinedFunction()".Hence the "current object" (and the value of "this") within "UserDefinedFunction" shall be undefined. Invoking this function in "Strict Mode" will result in the following
UserDefinedFunction() // displays undefined
However, invoking it explicitly using window object shall result in the following
window.UserDefinedFunction() // "always displays [object Window] irrespective of mode."
Let us look at another example. Please look at the following code
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction
}
var o2={
c:3,
d:4,
f:UserDefinedFunction
}
o1.f() // Shall display 1,2,undefined,undefined
o2.f() // Shall display undefined,undefined,3,4
In the above example we see that when "UserDefinedFunction" was invoked through o1, "this" takes value of o1 and the value of its properties "a" and "b" get displayed. The value of "c" and "d" were shown as undefined as o1 does not define these properties
Similarly when "UserDefinedFunction" was invoked through o2, "this" takes value of o2 and the value of its properties "c" and "d" get displayed.The value of "a" and "b" were shown as undefined as o2 does not define these properties.
Inside Indirect "Non Bound Function" Call through functionName.call and functionName.apply:
When a "Non Bound Function" is called through functionName.call or functionName.apply, the "current object" (and hence the value of "this") is set to the value of "this" parameter (first parameter) passed to call/apply. The following code demonstrates the same.
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction
}
var o2={
c:3,
d:4,
f:UserDefinedFunction
}
UserDefinedFunction.call(o1) // Shall display 1,2,undefined,undefined
UserDefinedFunction.apply(o1) // Shall display 1,2,undefined,undefined
UserDefinedFunction.call(o2) // Shall display undefined,undefined,3,4
UserDefinedFunction.apply(o2) // Shall display undefined,undefined,3,4
o1.f.call(o2) // Shall display undefined,undefined,3,4
o1.f.apply(o2) // Shall display undefined,undefined,3,4
o2.f.call(o1) // Shall display 1,2,undefined,undefined
o2.f.apply(o1) // Shall display 1,2,undefined,undefined
The above code clearly shows that the "this" value for any "NON Bound Function" can be altered through call/apply. Also,if the "this" parameter is not explicitly passed to call/apply, "current object" (and hence the value of "this") is set to "window" in Non strict mode and "undefined" in strict mode.
Inside "Bound Function" Call (i.e. a function that has been bound by calling functionName.bind):
A bound function is a function whose "this" value has been fixed. The following code demonstrated how "this" works in case of bound function
function UserDefinedFunction()
{
alert(this.a + "," + this.b + "," + this.c + "," + this.d)
}
var o1={
a:1,
b:2,
f:UserDefinedFunction,
bf:null
}
var o2={
c:3,
d:4,
f:UserDefinedFunction,
bf:null
}
var bound1=UserDefinedFunction.bind(o1); // permanantly fixes "this" value of function "bound1" to Object o1
bound1() // Shall display 1,2,undefined,undefined
var bound2=UserDefinedFunction.bind(o2); // permanantly fixes "this" value of function "bound2" to Object o2
bound2() // Shall display undefined,undefined,3,4
var bound3=o1.f.bind(o2); // permanantly fixes "this" value of function "bound3" to Object o2
bound3() // Shall display undefined,undefined,3,4
var bound4=o2.f.bind(o1); // permanantly fixes "this" value of function "bound4" to Object o1
bound4() // Shall display 1,2,undefined,undefined
o1.bf=UserDefinedFunction.bind(o2) // permanantly fixes "this" value of function "o1.bf" to Object o2
o1.bf() // Shall display undefined,undefined,3,4
o2.bf=UserDefinedFunction.bind(o1) // permanantly fixes "this" value of function "o2.bf" to Object o1
o2.bf() // Shall display 1,2,undefined,undefined
bound1.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
bound1.apply(o2) // Shall still display 1,2,undefined,undefined. "apply" cannot alter the value of "this" for bound function
o2.bf.call(o2) // Shall still display 1,2,undefined,undefined. "call" cannot alter the value of "this" for bound function
o2.bf.apply(o2) // Shall still display 1,2,undefined,undefined."apply" cannot alter the value of "this" for bound function
As given in the code above, "this" value for any "Bound Function" CANNOT be altered through call/apply. Also, if the "this" parameter is not explicitly passed to bind, "current object" (and hence the value of "this" ) is set to "window" in Non strict mode and "undefined" in strict mode. One more thing. Binding an already bound function does not change the value of "this". It remains set as the value set by first bind function.
While Object Creation through "new":
Inside a constructor function, the "current object" (and hence the value of "this") references the object that is currently being created through "new" irrespective of the bind status of the function. However if the constructor is a bound function it shall get called with predefined set of arguments as set for the bound function.
Inside Inline DOM event handler:
Please look at the following HTML Snippet
<button onclick='this.style.color=white'>Hello World</button>
<div style='width:100px;height:100px;' onclick='OnDivClick(event,this)'>Hello World</div>
The "this" in above examples refer to "button" element and the "div" element respectively.
In the first example, the font color of the button shall be set to white when it is clicked.
In the second example when the "div" element is clicked it shall call the OnDivClick function with its second parameter referencing the clicked div element. However the value of "this" within OnDivClick SHALL NOT reference the clicked div element. It shall be set as the "window object" or "undefined" in Non strict and Strict Modes respectively (if OnDivClick is an unbound function) or set to a predefined Bound value (if OnDivClick is a bound function)
The following summarizes the entire article
In Global Context "this" always refers to the "window" object
Whenever a function is invoked, it is invoked in context of an object ("current object"). If the current object is not explicitly provided, the current object is the "window object" in NON Strict Mode and "undefined" in Strict Mode by default.
The value of "this" within a Non Bound function is the reference to object in context of which the function is invoked ("current object")
The value of "this" within a Non Bound function can be overriden by call and apply methods of the function.
The value of "this" is fixed for a Bound function and cannot be overriden by call and apply methods of the function.
Binding and already bound function does not change the value of "this". It remains set as the value set by first bind function.
The value of "this" within a constructor is the object that is being created and initialized
The value of "this" within an inline DOM event handler is reference to the element for which the event handler is given.
Hello this is a snippet from an old project of mine that uses curl to get ip information from some free ip databases services which reply in json format. I think it might help you.
$ip_srv = array("http://freegeoip.net/json/$this->ip","http://smart-ip.net/geoip-json/$this->ip");
getUserLocation($ip_srv);
Function:
function getUserLocation($services) {
$ctx = stream_context_create(array('http' => array('timeout' => 15))); // 15 seconds timeout
for ($i = 0; $i < count($services); $i++) {
// Configuring curl options
$options = array (
CURLOPT_RETURNTRANSFER => true, // return web page
//CURLOPT_HEADER => false, // don't return headers
CURLOPT_HTTPHEADER => array('Content-type: application/json'),
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_USERAGENT => "test", // who am i
CURLOPT_AUTOREFERER => true, // set referer on redirect
CURLOPT_CONNECTTIMEOUT => 5, // timeout on connect
CURLOPT_TIMEOUT => 5, // timeout on response
CURLOPT_MAXREDIRS => 10 // stop after 10 redirects
);
// Initializing curl
$ch = curl_init($services[$i]);
curl_setopt_array ( $ch, $options );
$content = curl_exec ( $ch );
$err = curl_errno ( $ch );
$errmsg = curl_error ( $ch );
$header = curl_getinfo ( $ch );
$httpCode = curl_getinfo ( $ch, CURLINFO_HTTP_CODE );
curl_close ( $ch );
//echo 'service: ' . $services[$i] . '</br>';
//echo 'err: '.$err.'</br>';
//echo 'errmsg: '.$errmsg.'</br>';
//echo 'httpCode: '.$httpCode.'</br>';
//print_r($header);
//print_r(json_decode($content, true));
if ($err == 0 && $httpCode == 200 && $header['download_content_length'] > 0) {
return json_decode($content, true);
}
}
}
No you cannot force a file that is already committed in the repo to be removed just because it is added to the .gitignore
You have to git rm --cached
to remove the files that you don't want in the repo. ( --cached since you probably want to keep the local copy but remove from the repo. ) So if you want to remove all the exe's from your repo do
git rm --cached /\*.exe
(Note that the asterisk * is quoted from the shell - this lets git, and not the shell, expand the pathnames of files and subdirectories)
To escape special characters in a LIKE expression you prefix them with an escape character. You get to choose which escape char to use with the ESCAPE keyword. (MSDN Ref)
For example this escapes the % symbol, using \ as the escape char:
select * from table where myfield like '%15\% off%' ESCAPE '\'
If you don't know what characters will be in your string, and you don't want to treat them as wildcards, you can prefix all wildcard characters with an escape char, eg:
set @myString = replace(
replace(
replace(
replace( @myString
, '\', '\\' )
, '%', '\%' )
, '_', '\_' )
, '[', '\[' )
(Note that you have to escape your escape char too, and make sure that's the inner replace
so you don't escape the ones added from the other replace
statements). Then you can use something like this:
select * from table where myfield like '%' + @myString + '%' ESCAPE '\'
Also remember to allocate more space for your @myString variable as it will become longer with the string replacement.
See here: https://superuser.com/questions/42537/is-there-any-sudo-command-for-windows
According to that the command looks like this for admin:
runas /noprofile /user:Administrator cmd
Though, the question is asked long back, I see this same issue recently after installing Android Studio 2.1.0v, and JDK 7.80 on my PC Windows 10, 32 bit OS. I got this error.
No JVM installation found. Please install a 32 bit JDK. If you already have a JDK installed define a JAVA_HOME variable in Computer > System Properties > System Settings > Environment Variables.
I tried different ways to fix this nothing worked. But As per System Requirements in this Android developer website link.
Its solved after installing JDK 8(jdk-8u101-windows-i586.exe) JDK download site link.
Hope it helps somebody.
For Angular 8 or posterior @ViewChild have an additional parameter called opts, which have two properties: read and static, read is optional. You can use it like so:
// ...
@ViewChild('mydiv', { static: false }) public mydiv: ElementRef;
constructor() {
// ...
<div #mydiv></div>
NOTE: Static: false is not required anymore in Angular 9. (just { static: true }
when you are going to use that variable inside ngOnInit)
I managed to solve mine, by changing
add_executable(file1.cpp)
to
add_executable(ProjectName file1.cpp)
NUMBER (precision, scale)
means precision
number of total digits, of which scale
digits are right of the decimal point.
NUMBER(2,2)
in other words means a number with 2 digits, both of which are decimals. You may mean to use NUMBER(4,2)
to get 4 digits, of which 2 are decimals. Currently you can just insert values with a zero integer part.
I came across this issue twice once in upgrading to 3.2.18 from 3.2.1 and 4.3.5 from 3.2.8. In both cases, this error is because of different version of spring modules
Use one of these as per your requirements.
Open the linked document in a new window or tab:
<a href="xyz.html" target="_blank"> Link </a>
Open the linked document in the same frame as it was clicked (this is default):
<a href="xyz.html" target="_self"> Link </a>
Open the linked document in the parent frame:
<a href="xyz.html" target="_parent"> Link </a>
Open the linked document in the full body of the window:
<a href="xyz.html" target="_top"> Link </a>
Open the linked document in a named frame:
<a href="xyz.html" target="framename"> Link </a>
You can click on the Project window, press Alt-Insert, and select Folder->Assets Folder. Android Studio will add it automatically to the correct location.
You are most likely looking at your Project with the new(ish) "Android View". Note that this is a view and not the actual folder structure on disk (which hasn't changed since the introduction of Gradle as the new build tool). You can switch to the old "Project View" by clicking on the word "Android" at the top of the Project window and selecting "Project".
You can use addEventListener
to pass this
to a JavaScript function.
HTML
<button id="button">Year</button>
JavaScript
(function () {
var btn = document.getElementById('button');
btn.addEventListener('click', function () {
Date('#year');
}, false);
})();
function Data(string)
{
$('.filter').removeClass('active');
$(this).parent().addClass('active') ;
}
If you're using Webpack:
webpack.config.js:
plugins: [
<... your plugins here>,
new webpack.ProvidePlugin({
$: "jquery",
jQuery: "jquery",
"window.jQuery": "jquery",
"window.Tether": 'tether'
})
]
This will append all the functions that are defined in your_module in a list.
result=[]
for i in dir(your_module):
if type(getattr(your_module, i)).__name__ == "function":
result.append(getattr(your_module, i))
The lambda:
() -> { System.out.println("Do nothing!"); };
actually represents an implementation for an interface like:
public interface Something {
void action();
}
which is completely different than the one you've defined. That's why you get an error.
Since you can't extend your @FunctionalInterface
, nor introduce a brand new one, then I think you don't have much options. You can use the Optional<T>
interfaces to denote that some of the values (return type or method parameter) is missing, though. However, this won't make the lambda body simpler.
You can first concatenate the strings in the list with the separator ';' using the function join
and then use the split
function in order create the list:
l = ['Facebook;Google+;MySpace', 'Apple;Android']
l1 = ";".join(l)).split(";")
print l1
outputs
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']
When you use git push origin :staleStuff
, it automatically removes origin/staleStuff
, so when you ran git remote prune origin
, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune
to get rid of branches you have removed.
So what exactly git remote prune
does? Main idea: local branches (not tracking branches) are not touched by git remote prune
command and should be removed manually.
Now, a real-world example for better understanding:
You have a remote repository with 2 branches: master
and feature
. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):
refs/heads/master
(short name master
)refs/heads/feature
(short name feature
)refs/remotes/origin/master
(short name origin/master
)refs/remotes/origin/feature
(short name origin/feature
)Now, a typical scenario:
feature
, merges it into master
and removes feature
branch from remote repository.git fetch
(or git pull
), no references are removed from your local repository, so you still have all those 4 references.git remote prune origin
.feature
branch no longer exists, so refs/remotes/origin/feature
is a stale branch which should be removed. refs/heads/feature
, because git remote prune
does not remove any refs/heads/*
references.It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge
configuration parameter. This parameter is not really required for anything to work (probably except git pull
), so it might be missing.
(updated with example & useful info from comments)
The correct way to display the alert is to simply return a string. Don't call the alert()
method yourself.
<script type="text/javascript">
$(window).on('beforeunload', function() {
if (iWantTo) {
return 'you are an idiot!';
}
});
</script>
See also: https://developer.mozilla.org/en-US/docs/Web/Events/beforeunload
An easy one as an extension method
public static class Extensions
{
public static Stream ConvertToBase64(this Stream stream)
{
byte[] bytes;
using (var memoryStream = new MemoryStream())
{
stream.CopyTo(memoryStream);
bytes = memoryStream.ToArray();
}
string base64 = Convert.ToBase64String(bytes);
return new MemoryStream(Encoding.UTF8.GetBytes(base64));
}
}
By changing runProguard to minifyEnabled, part of the issue gets fixed.
But the fix can cause "Library Projects cannot set application Id" (you can find the fix for this here Android Studio 1.0 and error "Library projects cannot set applicationId").
By removing application Id in the build.gradle file, you should be good to go.
Ensure they are being called in the php.ini file
If the PDO is displayed in the list of currently installed php modules, you will want to check the php.ini file in the relevant folder to ensure they are being called. Somewhere in the php.ini file you should see the following:
extension=pdo.so
extension=pdo_sqlite.so
extension=pdo_mysql.so
extension=sqlite.so
If they are not present, simply add the lines above to the bottom of the php.ini file and save it.
Actually, all of those examples on the web wherein the common content/file type like "js", "css", "img", etc is been used as library name are misleading.
To start, let's look at how existing JSF implementations like Mojarra and MyFaces and JSF component libraries like PrimeFaces and OmniFaces use it. No one of them use resource libraries this way. They use it (under the covers, by @ResourceDependency
or UIViewRoot#addComponentResource()
) the following way:
<h:outputScript library="javax.faces" name="jsf.js" />
<h:outputScript library="primefaces" name="jquery/jquery.js" />
<h:outputScript library="omnifaces" name="omnifaces.js" />
<h:outputScript library="omnifaces" name="fixviewstate.js" />
<h:outputScript library="omnifaces.combined" name="[dynamicname].js" />
<h:outputStylesheet library="primefaces" name="primefaces.css" />
<h:outputStylesheet library="primefaces-aristo" name="theme.css" />
<h:outputStylesheet library="primefaces-vader" name="theme.css" />
It should become clear that it basically represents the common library/module/theme name where all of those resources commonly belong to.
This way it's so much easier to specify and distinguish where those resources belong to and/or are coming from. Imagine that you happen to have a primefaces.css
resource in your own webapp wherein you're overriding/finetuning some default CSS of PrimeFaces; if PrimeFaces didn't use a library name for its own primefaces.css
, then the PrimeFaces own one wouldn't be loaded, but instead the webapp-supplied one, which would break the look'n'feel.
Also, when you're using a custom ResourceHandler
, you can also apply more finer grained control over resources coming from a specific library when library
is used the right way. If all component libraries would have used "js" for all their JS files, how would the ResourceHandler
ever distinguish if it's coming from a specific component library? Examples are OmniFaces CombinedResourceHandler
and GraphicResourceHandler
; check the createResource()
method wherein the library is checked before delegating to next resource handler in chain. This way they know when to create CombinedResource
or GraphicResource
for the purpose.
Noted should be that RichFaces did it wrong. It didn't use any library
at all and homebrewed another resource handling layer over it and it's therefore impossible to programmatically identify RichFaces resources. That's exactly the reason why OmniFaces CombinedResourceHander
had to introduce a reflection-based hack in order to get it to work anyway with RichFaces resources.
Your own webapp does not necessarily need a resource library. You'd best just omit it.
<h:outputStylesheet name="css/style.css" />
<h:outputScript name="js/script.js" />
<h:graphicImage name="img/logo.png" />
Or, if you really need to have one, you can just give it a more sensible common name, like "default" or some company name.
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
Or, when the resources are specific to some master Facelets template, you could also give it the name of the template, so that it's easier to relate each other. In other words, it's more for self-documentary purposes. E.g. in a /WEB-INF/templates/layout.xhtml
template file:
<h:outputStylesheet library="layout" name="css/style.css" />
<h:outputScript library="layout" name="js/script.js" />
And a /WEB-INF/templates/admin.xhtml
template file:
<h:outputStylesheet library="admin" name="css/style.css" />
<h:outputScript library="admin" name="js/script.js" />
For a real world example, check the OmniFaces showcase source code.
Or, when you'd like to share the same resources over multiple webapps and have created a "common" project for that based on the same example as in this answer which is in turn embedded as JAR in webapp's /WEB-INF/lib
, then also reference it as library (name is free to your choice; component libraries like OmniFaces and PrimeFaces also work that way):
<h:outputStylesheet library="common" name="css/style.css" />
<h:outputScript library="common" name="js/script.js" />
<h:graphicImage library="common" name="img/logo.png" />
Another main advantage is that you can apply resource library versioning the right way on resources provided by your own webapp (this doesn't work for resources embedded in a JAR). You can create a direct child subfolder in the library folder with a name in the \d+(_\d+)*
pattern to denote the resource library version.
WebContent
|-- resources
| `-- default
| `-- 1_0
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
When using this markup:
<h:outputStylesheet library="default" name="css/style.css" />
<h:outputScript library="default" name="js/script.js" />
<h:graphicImage library="default" name="img/logo.png" />
This will generate the following HTML with the library version as v
parameter:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_0" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_0"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_0" alt="" />
So, if you have edited/updated some resource, then all you need to do is to copy or rename the version folder into a new value. If you have multiple version folders, then the JSF ResourceHandler
will automatically serve the resource from the highest version number, according to numerical ordering rules.
So, when copying/renaming resources/default/1_0/*
folder into resources/default/1_1/*
like follows:
WebContent
|-- resources
| `-- default
| |-- 1_0
| | :
| |
| `-- 1_1
| |-- css
| | `-- style.css
| |-- img
| | `-- logo.png
| `-- js
| `-- script.js
:
Then the last markup example would generate the following HTML:
<link rel="stylesheet" type="text/css" href="/contextname/javax.faces.resource/css/style.css.xhtml?ln=default&v=1_1" />
<script type="text/javascript" src="/contextname/javax.faces.resource/js/script.js.xhtml?ln=default&v=1_1"></script>
<img src="/contextname/javax.faces.resource/img/logo.png.xhtml?ln=default&v=1_1" alt="" />
This will force the webbrowser to request the resource straight from the server instead of showing the one with the same name from the cache, when the URL with the changed parameter is been requested for the first time. This way the endusers aren't required to do a hard refresh (Ctrl+F5 and so on) when they need to retrieve the updated CSS/JS resource.
Please note that library versioning is not possible for resources enclosed in a JAR file. You'd need a custom ResourceHandler
. See also How to use JSF versioning for resources in jar.
Updated with Swift 5 Generally we use three type of Local Notifications
Where you can send simple text notification or with action button and attachment.
Using UserNotifications package in your app, the following example Request for notification permission, prepare and send notification as per user action AppDelegate itself, and use view controller listing different type of local notification test.
AppDelegate
import UIKit
import UserNotifications
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
let notificationCenter = UNUserNotificationCenter.current()
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
//Confirm Delegete and request for permission
notificationCenter.delegate = self
let options: UNAuthorizationOptions = [.alert, .sound, .badge]
notificationCenter.requestAuthorization(options: options) {
(didAllow, error) in
if !didAllow {
print("User has declined notifications")
}
}
return true
}
func applicationWillResignActive(_ application: UIApplication) {
}
func applicationDidEnterBackground(_ application: UIApplication) {
}
func applicationWillEnterForeground(_ application: UIApplication) {
}
func applicationWillTerminate(_ application: UIApplication) {
}
func applicationDidBecomeActive(_ application: UIApplication) {
UIApplication.shared.applicationIconBadgeNumber = 0
}
//MARK: Local Notification Methods Starts here
//Prepare New Notificaion with deatils and trigger
func scheduleNotification(notificationType: String) {
//Compose New Notificaion
let content = UNMutableNotificationContent()
let categoryIdentifire = "Delete Notification Type"
content.sound = UNNotificationSound.default
content.body = "This is example how to send " + notificationType
content.badge = 1
content.categoryIdentifier = categoryIdentifire
//Add attachment for Notification with more content
if (notificationType == "Local Notification with Content")
{
let imageName = "Apple"
guard let imageURL = Bundle.main.url(forResource: imageName, withExtension: "png") else { return }
let attachment = try! UNNotificationAttachment(identifier: imageName, url: imageURL, options: .none)
content.attachments = [attachment]
}
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
let identifier = "Local Notification"
let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger)
notificationCenter.add(request) { (error) in
if let error = error {
print("Error \(error.localizedDescription)")
}
}
//Add Action button the Notification
if (notificationType == "Local Notification with Action")
{
let snoozeAction = UNNotificationAction(identifier: "Snooze", title: "Snooze", options: [])
let deleteAction = UNNotificationAction(identifier: "DeleteAction", title: "Delete", options: [.destructive])
let category = UNNotificationCategory(identifier: categoryIdentifire,
actions: [snoozeAction, deleteAction],
intentIdentifiers: [],
options: [])
notificationCenter.setNotificationCategories([category])
}
}
//Handle Notification Center Delegate methods
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
completionHandler([.alert, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter,
didReceive response: UNNotificationResponse,
withCompletionHandler completionHandler: @escaping () -> Void) {
if response.notification.request.identifier == "Local Notification" {
print("Handling notifications with the Local Notification Identifier")
}
completionHandler()
}
}
and ViewController
import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
var appDelegate = UIApplication.shared.delegate as? AppDelegate
let notifications = ["Simple Local Notification",
"Local Notification with Action",
"Local Notification with Content",]
override func viewDidLoad() {
super.viewDidLoad()
}
// MARK: - Table view data source
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return notifications.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath)
cell.textLabel?.text = notifications[indexPath.row]
return cell
}
func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
let notificationType = notifications[indexPath.row]
let alert = UIAlertController(title: "",
message: "After 5 seconds " + notificationType + " will appear",
preferredStyle: .alert)
let okAction = UIAlertAction(title: "Okay, I will wait", style: .default) { (action) in
self.appDelegate?.scheduleNotification(notificationType: notificationType)
}
alert.addAction(okAction)
present(alert, animated: true, completion: nil)
}
}
The Boost::serialization
library handles this rather elegantly. I've used it in several projects. There's an example program, showing how to use it, here.
The only native way to do it is to use streams. That's essentially all the Boost::serialization
library does, it extends the stream method by setting up a framework to write objects to a text-like format and read them from the same format.
For built-in types, or your own types with operator<<
and operator>>
properly defined, that's fairly simple; see the C++ FAQ for more information.
Q1:Could the time it takes for a transaction to execute make the associated process more likely to be flagged as a deadlock victim.
No. The SELECT is the victim because it had only read data, therefore the transaction has a lower cost associated with it so is chosen as the victim:
By default, the Database Engine chooses as the deadlock victim the session running the transaction that is least expensive to roll back. Alternatively, a user can specify the priority of sessions in a deadlock situation using the
SET DEADLOCK_PRIORITY
statement. DEADLOCK_PRIORITY can be set to LOW, NORMAL, or HIGH, or alternatively can be set to any integer value in the range (-10 to 10).
Q2. If I execute the select with a NOLOCK hint, will this remove the problem?
No. For several reasons:
Q3. I suspect that a datetime field that is checked as part of the WHERE clause in the select statement is causing the slow lookup time. Can I create an index based on this field? Is it advisable?
Probably. The cause of the deadlock is almost very likely to be a poorly indexed database.10 minutes queries are acceptable in such narrow conditions, that I'm 100% certain in your case is not acceptable.
With 99% confidence I declare that your deadlock is cased by a large table scan conflicting with updates. Start by capturing the deadlock graph to analyze the cause. You will very likely have to optimize the schema of your database. Before you do any modification, read this topic Designing Indexes and the sub-articles.
what about ...
import pandas as pd
import matplotlib.pyplot as plt
values = [[1,2], [2,5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'], index=['Index 1','Index 2'])
(df2.plot(lw=2,
colormap='jet',
marker='.',
markersize=10,
title='Video streaming dropout by category')
.set(xlabel='x axis',
ylabel='y axis'))
plt.show()
If you really have to avoid operators then use Math.signum()
Returns the signum function of the argument; zero if the argument is zero, 1.0 if the argument is greater than zero, -1.0 if the argument is less than zero.
EDIT : As per the comments, this works for only double and float values. For integer values you can use the method:
After reading the answer from Gilles, I decided to see if the $BASH_COMMAND
var was also available (and the desired value) in an EXIT
trap - and it is!
So, the following bash script works as expected:
#!/bin/bash
exit_trap () {
local lc="$BASH_COMMAND" rc=$?
echo "Command [$lc] exited with code [$rc]"
}
trap exit_trap EXIT
set -e
echo "foo"
false 12345
echo "bar"
The output is
foo
Command [false 12345] exited with code [1]
bar
is never printed because set -e
causes bash to exit the script when a command fails and the false command always fails (by definition). The 12345
passed to false
is just there to show that the arguments to the failed command are captured as well (the false
command ignores any arguments passed to it)
I use lists to filter dataframes by whether or not they have a value %in% a list.
I had been manually creating lists by exporting a 1 column dataframe to Excel where I would add " ", around each element, before pasting into R: list <- c("el1", "el2", ...) which was usually followed by FilteredData <- subset(Data, Column %in% list).
After searching stackoverflow and not finding an intuitive way to convert a 1 column dataframe into a list, I am now posting my first ever stackoverflow contribution:
# assuming you have a 1 column dataframe called "df"
list <- c()
for(i in 1:nrow(df)){
list <- append(list, df[i,1])
}
View(list)
# This list is not a dataframe, it is a list of values
# You can filter a dataframe using "subset([Data], [Column] %in% list")
var pdf = MyPdf.pdf;
window.open(pdf);
This will open the pdf document in a full window from JavaScript
A function to open windows would look like this:
function openPDF(pdf){
window.open(pdf);
return false;
}
Had a similar issue with all of our 2008 servers. The security log stopped working altogether because of a GPO that took the group Authenticated Users and read permission away from the key HKLM\System\CurrentControlSet\Services\EventLog\security
Putting this back per Microsoft's recommendation corrected the issue. I suspect giving all authenticated users read at a higher level will also correct your problem.
If all your branches make side-effects or are computationally expensive the following would a semantically-preserving refactoring:
index := func() int {
if val > 0 {
return printPositiveAndReturn(val)
} else {
return slowlyReturn(-val) // or slowlyNegate(val)
}
}(); # exactly one branch will be evaluated
with normally no overhead (inlined) and, most importantly, without cluttering your namespace with a helper functions that are only used once (which hampers readability and maintenance). Live Example
Note if you were to naively apply Gustavo's approach:
index := printPositiveAndReturn(val);
if val <= 0 {
index = slowlyReturn(-val); // or slowlyNegate(val)
}
you'd get a program with a different behavior; in case val <= 0
program would print a non-positive value while it should not! (Analogously, if you reversed the branches, you would introduce overhead by calling a slow function unnecessarily.)
KDiff3 is not XML specific, but it is free. It does a nice job of comparing and merging text files.
Try this code:
Collection<Employee> nonDuplicatedEmployees = employees.stream()
.<Map<Integer, Employee>> collect(HashMap::new,(m,e)->m.put(e.getId(), e), Map::putAll)
.values();
In my own experience, it is always better to store files as files. The reason is that the filesystem is optimised for file storeage, whereas a database is not. Of course, there are some exceptions (e.g. the much heralded next-gen MS filesystem is supposed to be built on top of SQL server), but in general that's my rule.
<img src="myimage.jpg" ondragstart="return false;" />
I assume I have import datetime
before running each of the lines of code below
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
prints "01/25/13"
.
If you can't live with the leading zero, try this:
dt = datetime.datetime.strptime("2013-1-25", '%Y-%m-%d')
print '{0}/{1}/{2:02}'.format(dt.month, dt.day, dt.year % 100)
This prints "1/25/13"
.
EDIT: This may not work on every platform:
datetime.datetime.strptime("2013-1-25", '%Y-%m-%d').strftime('%m/%d/%y')
Traversal over the large map entrySet()
is much better than the keySet()
. Check this tutorial how they optimise the traversal over the large object with the help of entrySet(
) and how it helps for performance tuning.
Use spring-boot:run command to start spring boot application:
Precondition: 1. Add following property to pom.xml
<property>
<start-class>com.package.name.YourApplicationMainClass</start-class>
</property>
2. Build your project
Then configure maven command with spring-boot:run.
Right Click Project | Run As | Run Configuration... | Add new Maven Configuration with command spring-boot:run
You can expend the following function in order to pull out more parameters from the DB before the insert:
--
-- insert_employee (Function)
--
CREATE OR REPLACE FUNCTION insert_employee(p_emp_id in number, p_emp_name in varchar2, p_emp_address in varchar2, p_emp_state in varchar2, p_emp_position in varchar2, p_emp_manager in varchar2)
RETURN VARCHAR2 AS
p_state_id varchar2(30) := '';
BEGIN
select state_id
into p_state_id
from states where lower(emp_state) = state_name;
INSERT INTO Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager) VALUES
(p_emp_id, p_emp_name, p_emp_address, p_state_id, p_emp_position, p_emp_manager);
return 'SUCCESS';
EXCEPTION
WHEN others THEN
RETURN 'FAIL';
END;
/
For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).
Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.
var options = {
enableHighAccuracy: true,
timeout: 6000,
maximumAge: 0,
desiredAccuracy: 30,
fallbackToIP: true, // if HTML5 geolocation fails or rejected
addressLookup: true, // get detailed address information
timezone: true,
map: "my-map" // this will even create a map for you
};
geolocator.locate(options, function (err, location) {
console.log(err || location);
});
It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...
Clustered basically means that the data is in that physical order in the table. This is why you can have only one per table.
Unclustered means it's "only" a logical order.
//
syntaxregex.test(string)
, not string.test(regex)
So
jQuery(function () {
$(".mail").keyup(function () {
var VAL = this.value;
var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');
if (email.test(VAL)) {
alert('Great, you entered an E-Mail-address');
}
});
});
As Nikolai has said you can use the gdb 'set' command to change the value of a variable.
You can also use the 'set' command to change memory locations. eg. Expanding on Nikolai's example:
(gdb) l
6 {
7 int i;
8 struct file *f, *ftmp;
9
(gdb) set variable i = 10
(gdb) p i
$1 = 10
(gdb) p &i
$2 = (int *) 0xbfbb0000
(gdb) set *((int *) 0xbfbb0000) = 20
(gdb) p i
$3 = 20
This should work for any valid pointer, and can be cast to any appropriate data type.
Any !important can be overridden by another !important, the normal CSS precedence rules still apply.
Example:
#an-element{
background: #F00 !important;
}
#an-element{
background: #0F0 !important; //Makes #an-element green
}
Then you could add a style attribute (using JavaScript/jQuery) to override the CSS
$(function () {
$("#an-element").attr('style', 'background: #00F !important;');
//Makes #an-element blue
});
See the result here
var percent = Math.floor(100 * number1 / number2 - 100) + ' %';
Here is a solution that only scrolls to top of Component if first time visiting for EACH component (in case you need to do something different per component):
In each Component:
export class MyComponent implements OnInit {
firstLoad: boolean = true;
...
ngOnInit() {
if(this.firstLoad) {
window.scroll(0,0);
this.firstLoad = false;
}
...
}
Quite an old article on mssqlcity attempts to explain the types of locks:
Shared locks are used for operations that do not change or update data, such as a SELECT statement.
Update locks are used when SQL Server intends to modify a page, and later promotes the update page lock to an exclusive page lock before actually making the changes.
Exclusive locks are used for the data modification operations, such as UPDATE, INSERT, or DELETE.
What it doesn't discuss are Intent (which basically is a modifier for these lock types). Intent (Shared/Exclusive) locks are locks held at a higher level than the real lock. So, for instance, if your transaction has an X lock on a row, it will also have an IX lock at the table level (which stops other transactions from attempting to obtain an incompatible lock at a higher level on the table (e.g. a schema modification lock) until your transaction completes or rolls back).
The concept of "sharing" a lock is quite straightforward - multiple transactions can have a Shared lock for the same resource, whereas only a single transaction may have an Exclusive lock, and an Exclusive lock precludes any transaction from obtaining or holding a Shared lock.
Map can contain multiple arguments, the standard way is
map(add, a, b)
In your question, it should be
map(add, a, [2]*len(a))
You have a few options:
First, you can use the JoinPoint#getArgs()
method which returns an Object[]
containing all the arguments of the advised method. You might have to do some casting depending on what you want to do with them.
Second, you can use the args
pointcut expression like so:
// use '..' in the args expression if you have zero or more parameters at that point
@Before("execution(* com.mkyong.customer.bo.CustomerBo.addCustomer(..)) && args(yourString,..)")
then your method can instead be defined as
public void logBefore(JoinPoint joinPoint, String yourString)
Best way to deal with this issue using ngIf
Because this well prevent getting that element render in front-end,
If you use [hidden]="true"
or style hide [style.display]
it will only hide element in front end and someone can change the value and visible it easily,
In my opinion best way to hide element is ngIf
<div *ngIf="myVar">stuff</div>
and also If you have multiple element (need to implement else also) you can Use <ng-template>
option
<ng-container *ngIf="myVar; then loadAdmin else loadMenu"></ng-container>
<ng-template #loadMenu>
<div>loadMenu</div>
</ng-template>
<ng-template #loadAdmin>
<div>loadAdmin</div>
</ng-template>
Thanks Burhan Khalid. Your advice to make a a soft link make my installation finally work.
To recap:
You need both the basic version and the SDK version of instant client
You need to set both LD_LIBRARY_PATH and ORACLE_HOME
None of this is documented anywhere, which is quite unbelievable and quite frustrating. I spent over 3 hours yesterday with failed builds because I didn't know to create a soft link.
NumberFormat and DecimalFormat are definitely what you want. Also, note the NumberFormat.setRoundingMode()
method. You can use it to control how rounding or truncation is applied during formatting.
DataSet ds = new DataSet();
using (OleDbConnection connection = new OleDbConnection(connectionString))
using (OleDbCommand command = new OleDbCommand(query, connection))
using (OleDbDataAdapter adapter = new OleDbDataAdapter(command))
{
adapter.Fill(ds);
}
return ds;
You can try these snippets.
In [16]:mydata = {'x' : [10, 50, 18, 32, 47, 20], 'y' : ['12', '11', 'N/A', '13', '15', 'N/A']} In [17]:df=pd.DataFrame(mydata) In [18]:df.y[df.y=="N/A"]=np.nan Out[19]:df x y 0 10 12 1 50 11 2 18 NaN 3 32 13 4 47 15 5 20 NaN
I always do input prompts, like this:
<input style="color: #C0C0C0;" value="[email protected]"
onfocus="this.value=''; this.style.color='#000000'">
Of course, if your user fills in the field, changes focus and comes back to the field, the field will once again be cleared. If you do it like that, be sure that's what you want. You can make it a one time thing by setting a semaphore, like this:
<script language = "text/Javascript">
cleared[0] = cleared[1] = cleared[2] = 0; //set a cleared flag for each field
function clearField(t){ //declaring the array outside of the
if(! cleared[t.id]){ // function makes it static and global
cleared[t.id] = 1; // you could use true and false, but that's more typing
t.value=''; // with more chance of typos
t.style.color='#000000';
}
}
</script>
Your <input> field then looks like this:
<input id = 0; style="color: #C0C0C0;" value="[email protected]"
onfocus=clearField(this)>
You can use:
max(d, key = d.get)
# which is equivalent to
max(d, key = lambda k : d.get(k))
To return the key, value pair use:
max(d.items(), key = lambda k : k[1])
In an SQL query, if the inner query executes for every row of the outer query. If the inner query is executed for once and the result is consumed by the outer query, then it is called as non co-related query.
It appears you might be a bit confused as to how the .Add method works. I will refer directly to your code in my explanation.
Basically in C#, the .Add method of a List of objects does not COPY new added objects into the list, it merely copies a reference to the object (it's address) into the List. So the reason every value in the list is pointing to the same value is because you've only created 1 new DyObj. So your list essentially looks like this.
DyObjectsList[0] = &DyObj; // pointing to DyObj
DyObjectsList[1] = &DyObj; // pointing to the same DyObj
DyObjectsList[2] = &DyObj; // pointing to the same DyObj
...
The easiest way to fix your code is to create a new DyObj for every .Add. Putting the new inside of the block with the .Add would accomplish this goal in this particular instance.
var DyObjectsList = new List<dynamic>;
if (condition1) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = true;
DyObj.Message = "Message 1";
DyObjectsList .Add(DyObj);
}
if (condition2) {
dynamic DyObj = new ExpandoObject();
DyObj.Required = false;
DyObj.Message = "Message 2";
DyObjectsList .Add(DyObj);
}
your resulting List essentially looks like this
DyObjectsList[0] = &DyObj0; // pointing to a DyObj
DyObjectsList[1] = &DyObj1; // pointing to a different DyObj
DyObjectsList[2] = &DyObj2; // pointing to another DyObj
Now in some other languages this approach wouldn't work, because as you leave the block, the objects declared in the scope of the block could go out of scope and be destroyed. Thus you would be left with a collection of pointers, pointing to garbage.
However in C#, if a reference to the new DyObjs exists when you leave the block (and they do exist in your List because of the .Add operation) then C# does not release the memory associated with that pointer. Therefore the Objects you created in that block persist and your List contains pointers to valid objects and your code works.
<input type="file">
with a <label>
tag;<span>
or <a>
;input[type="file"]
invisible via display: none
.Join like this:
ON a.userid = b.sourceid AND a.listid = b.destinationid;
So let's say you have a local branch foo, a remote called origin and a remote branch origin/master.
To push the contents of foo to origin/master, you first need to set its upstream:
git checkout foo
git branch -u origin/master
Then you can push to this branch using:
git push origin HEAD:master
In the last command you can add --force to replace the entire history of origin/master with that of foo.
Actually, you could simply set splash Activity
with NoActionBar
and set your main activity
with action bar.
You can simply use multiprocessing.Pool
:
from multiprocessing import Pool
def process_image(name):
sci=fits.open('{}.fits'.format(name))
<process>
if __name__ == '__main__':
pool = Pool() # Create a multiprocessing Pool
pool.map(process_image, data_inputs) # process data_inputs iterable with pool
<?php
echo"<script language='javascript'>
</script>
";
?>
Chances are that you've not included the header file that declares system()
.
In order to be able to compile C++ code that uses functions which you don't (manually) declare yourself, you have to pull in the declarations. These declarations are normally stored in so-called header files that you pull into the current translation unit using the #include
preprocessor directive. As the code does not #include
the header file in which system()
is declared, the compilation fails.
To fix this issue, find out which header file provides you with the declaration of system()
and include that. As mentioned in several other answers, you most likely want to add #include <cstdlib>
I think ("\") may be causing the problem because \ is the escape character. change it to ("\\")
Working solution October 2018, for videos including audio channel
$(document).ready(function() {
$('video').prop('muted',true).play()
});
Have a look at another of mine, more in-depth answer: https://stackoverflow.com/a/57723549/3049675
An alternative way, supporting decimals, different separators and negatives.
var number_format = function(number, decimal_pos, decimal_sep, thousand_sep) {
var ts = ( thousand_sep == null ? ',' : thousand_sep )
, ds = ( decimal_sep == null ? '.' : decimal_sep )
, dp = ( decimal_pos == null ? 2 : decimal_pos )
, n = Math.floor(Math.abs(number)).toString()
, i = n.length % 3
, f = ((number < 0) ? '-' : '') + n.substr(0, i)
;
for(;i<n.length;i+=3) {
if(i!=0) f+=ts;
f+=n.substr(i,3);
}
if(dp > 0)
f += ds + parseFloat(number).toFixed(dp).split('.')[1]
return f;
}
Some corrections by @Jignesh Sanghani, don't forget to upvote his comment.
The best solution is to install the different Python versions in multiple paths.
eg. C:\Python27 for 2.7, and C:\Python33 for 3.3.
Read this for more info: How to run multiple Python versions on Windows
I had to set the JVM timezone for Windows 2003 Server because it always returned GMT for new Date();
-Duser.timezone=America/Los_Angeles
Or your appropriate time zone. Finding a list of time zones proved to be a bit challenging also...
Here are two list;
http://wrapper.tanukisoftware.com/doc/english/prop-timezone.html
Best option to do this according to WP Codex is as follow.
Use the global variable $post:
<?php
global $post;
$post_slug = $post->post_name;
?>
I would strongl suggest the use of the javascript escape() method
you can use this with jQuery by grabbing a form value like so:
var encodedString = escape($("#myFormFieldID").val());
I have fast solution. Just create a file ArrayUtil.java
import java.util.ArrayList;
import java.util.Collection;
import org.json.JSONArray;
import org.json.JSONException;
public class ArrayUtil
{
public static ArrayList<Object> convert(JSONArray jArr)
{
ArrayList<Object> list = new ArrayList<Object>();
try {
for (int i=0, l=jArr.length(); i<l; i++){
list.add(jArr.get(i));
}
} catch (JSONException e) {}
return list;
}
public static JSONArray convert(Collection<Object> list)
{
return new JSONArray(list);
}
}
Usage:
ArrayList<Object> list = ArrayUtil.convert(jArray);
or
JSONArray jArr = ArrayUtil.convert(list);
I use this :
1-Declare a temp table variable in the script your building:
DECLARE @ShiftPeriodList TABLE(id INT NOT NULL);
2-Allocate to temp table:
IF (SOME CONDITION)
BEGIN
INSERT INTO @ShiftPeriodList SELECT ShiftId FROM [hr].[tbl_WorkShift]
END
IF (SOME CONDITION2)
BEGIN
INSERT INTO @ShiftPeriodList
SELECT ws.ShiftId
FROM [hr].[tbl_WorkShift] ws
WHERE ws.WorkShift = 'Weekend(VSD)' OR ws.WorkShift = 'Weekend(SDL)'
END
3-Reference the table when you need it in a WHERE statement :
INSERT INTO SomeTable WHERE ShiftPeriod IN (SELECT * FROM @ShiftPeriodList)
Anyone who is just starting with Haskell and trying to print an Int, use:
module Lib
( someFunc
) where
someFunc :: IO ()
x = 123
someFunc = putStrLn (show x)
Under Linux you can use the very powerful recode command to try and convert between the different charsets as well as any line ending issues. recode -l will show you all of the formats and encodings that the tool can convert between. It is likely to be a VERY long list.
Php has a super sexy function for this, just pass the array to it:
$json = json_encode($var);
$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
console.info(msg);
}
});
simples :)
In my case, I've a sampleViewController
's view added as a subview, then tries to present a popover from the view of sampleViewController
(here self
instead a UIViewController
instance):
[self.view addSubview:sampleViewController.view];
The right way should be below:
// make sure the vc has been added as a child view controller as well
[self addChildViewController:sampleViewController];
[self.view addSubview:sampleViewController.view];
[sampleViewController didMoveToParentViewController:self];
B.t.w., this also works for the case that present a popover form a tableview cell, you just need to make sure the tableview controller has been added as child view controller as well.
Use position: fixed
, and anchor it to the top
and right
sides of the page:
#fixed-div {
position: fixed;
top: 1em;
right: 1em;
}
IE6 does not support position: fixed
, however. If you need this functionality in IE6, this purely-CSS solution seems to do the trick. You'll need a wrapper <div>
to contain some of the styles for it to work, as seen in the stylesheet.
That's not the behavior I'm seeing:
irb(main):001:0> metrics = {"sitea.com" => 745, "siteb.com" => 9, "sitec.com" =>
10 }
=> {"siteb.com"=>9, "sitec.com"=>10, "sitea.com"=>745}
irb(main):002:0> metrics.sort {|a1,a2| a2[1]<=>a1[1]}
=> [["sitea.com", 745], ["sitec.com", 10], ["siteb.com", 9]]
Is it possible that somewhere along the line your numbers are being converted to strings? Is there more code you're not posting?
In my view page:
<p:dataTable ...>
<p:column>
<p:commandLink actionListener="#{inquirySOController.viewDetail}"
process="@this" update=":mainform:dialog_content"
oncomplete="dlg2.show()">
<h:graphicImage library="images" name="view.png"/>
<f:param name="trxNo" value="#{item.map['trxNo']}"/>
</p:commandLink>
</p:column>
</p:dataTable>
backing bean
public void viewDetail(ActionEvent e) {
String trxNo = getFacesContext().getRequestParameterMap().get("trxNo");
for (DTO item : list) {
if (item.get("trxNo").toString().equals(trxNo)) {
System.out.println(trxNo);
setSelectedItem(item);
break;
}
}
}
Just add an onclick
event to the button
:
<button onclick="location.href = 'www.yoursite.com';" id="myButton" class="float-left submit-button" >Home</button>
But you shouldn't really have it inline like that, instead, put it in a JS block and give the button
an ID:
<button id="myButton" class="float-left submit-button" >Home</button>
<script type="text/javascript">
document.getElementById("myButton").onclick = function () {
location.href = "www.yoursite.com";
};
</script>
Quite simple :
For the tab control, you need to handle the _SelectedIndexChanged event:
Private Sub TabControl1_SelectedIndexChanged(sender As Object, e As System.EventArgs) _
Handles TabControl1.SelectedIndexChanged
If TabControl1.SelectedTab.Name = "TabPage1" Then
TextBox2.Focus()
End If
If TabControl1.SelectedTab.Name = "TabPage2" Then
TextBox4.Focus()
End If
You need to use parentheses: myList.insert([1, 2, 3])
. When you leave out the parentheses, python thinks you are trying to access myList.insert
at position 1, 2, 3
, because that's what brackets are used for when they are right next to a variable.
Simple INNER JOIN VIEW code....
CREATE VIEW room_view
AS SELECT a.*,b.*
FROM j4_booking a INNER JOIN j4_scheduling b
on a.room_id = b.room_id;
If you do not want to change the display format permanently, and perhaps apply a new format later on, I personally favour the use of a resource manager (the with
statement in Python). In your case you could do something like this:
with pd.option_context('display.float_format', '${:0.2f}'.format):
print(df)
If you happen to need a different format further down in your code, you can change it by varying just the format in the snippet above.
Wouldn't
(int) Math.Min(Int32.MaxValue, longValue)
be the correct way, mathematically speaking?
To execute a binary, use: ./binary_name
.
If you get an error:
bash: ./binary_name: cannot execute binary file
it'll be because it was compiled using a tool chain that was for a different target to that which you're attempting to run the binary on.
For example, if you compile 'binary_name.c' with arm-none-linux-gnueabi-gcc
and try run the generated binary on an x86 machine, you will get the aforementioned error.
CSS3 has a new filter attribute which will only work in webkit browsers supported in webkit browsers and in Firefox. It does not have support in IE or Opera mini:
img {_x000D_
-webkit-filter: invert(1);_x000D_
filter: invert(1);_x000D_
}
_x000D_
<img src="http://i.imgur.com/1H91A5Y.png">
_x000D_
You can use either of these functions:
// This should work in node.js and other ES5 compliant implementations.
function isEmptyObject(obj) {
return !Object.keys(obj).length;
}
// This should work both there and elsewhere.
function isEmptyObject(obj) {
for (var key in obj) {
if (Object.prototype.hasOwnProperty.call(obj, key)) {
return false;
}
}
return true;
}
Example usage:
if (isEmptyObject(query)) {
// There are no queries.
} else {
// There is at least one query,
// or at least the query object is not empty.
}
As other said, the comment in XML are like this
<!-- this is a comment -->
Notice that they can span on multiple lines
<!--
This is a comment
on multiple lines
-->
But they cannot be nested
<!-- This <!-- is a comment --> This is not -->
Also you cannot use them inside tags
<EditText <!--This is not valid--> android:layout_width="fill_parent" />
To get all the differences between two tables, you can use like me this SQL request :
SELECT 'TABLE1-ONLY' AS SRC, T1.*
FROM (
SELECT * FROM Table1
EXCEPT
SELECT * FROM Table2
) AS T1
UNION ALL
SELECT 'TABLE2-ONLY' AS SRC, T2.*
FROM (
SELECT * FROM Table2
EXCEPT
SELECT * FROM Table1
) AS T2
;
the problem is because you have got the query over multiple lines using the " " that PHP is actually sending all the white spaces in to MySQL which is causing it to error out.
Either put it on one line or append on each line :o)
Sqlyog must be trimming white spaces on each line which explains why its working.
Example:
$qr2="INSERT INTO wp_bp_activity
(
user_id,
(this stuff)component,
(is) `type`,
(a) `action`,
(problem) content,
primary_link,
item_id,....
I wrote two using statements inside a try/catch block and I could see the exception was being caught the same way if it's placed within the inner using statement just as ShaneLS example.
try
{
using (var con = new SqlConnection(@"Data Source=..."))
{
var cad = "INSERT INTO table VALUES (@r1,@r2,@r3)";
using (var insertCommand = new SqlCommand(cad, con))
{
insertCommand.Parameters.AddWithValue("@r1", atxt);
insertCommand.Parameters.AddWithValue("@r2", btxt);
insertCommand.Parameters.AddWithValue("@r3", ctxt);
con.Open();
insertCommand.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{
MessageBox.Show("Error: " + ex.Message, "UsingTest", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
No matter where's the try/catch placed, the exception will be caught without issues.
Use the following instead:
boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );
This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.
Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.
xCode 7.3.1 iOS 9.3.2
_siteLabel.layer.masksToBounds = true;
_siteLabel.layer.cornerRadius = 8;
If you have a lot of commits to rebase, and some part of them are giving conflicts, that really hurts. But I can suggest a less-known approach how to "squash all the conflicts".
First, checkout temp branch and start standard merge
git checkout -b temp
git merge origin/master
You will have to resolve conflicts, but only once and only real ones. Then stage all files and finish merge.
git commit -m "Merge branch 'origin/master' into 'temp'"
Then return to your branch (let it be alpha) and start rebase, but with automatical resolving any conflicts.
git checkout alpha
git rebase origin/master -X theirs
Branch has been rebased, but project is probably in invalid state. That's OK, we have one final step. We just need to restore project state, so it will be exact as on branch 'temp'. Technically we just need to copy its tree (folder state) via low-level command git commit-tree. Plus merging into current branch just created commit.
git merge --ff $(git commit-tree temp^{tree} -m "Fix after rebase" -p HEAD)
And delete temporary branch
git branch -D temp
That's all. We did a rebase via hidden merge.
Also I wrote a script, so that can be done in a dialog manner, you can find it here.
This error will occur if the configuration file of the hosting application of your WCF service does not have the proper configuration.
Remember this comment from configuration:
When deploying the service library project, the content of the config file must be added to the host's app.config file. System.Configuration does not support config files for libraries.
If you have a WCF Service hosted in IIS, during runtime via VS.NET it will read the app.config of the service library project, but read the host's web.config once deployed. If web.config does not have the identical <system.serviceModel>
configuration you will receive this error. Make sure to copy over the configuration from app.config once it has been perfected.
Open a new worksheet on the related instance (Alt-F10)
and run the following query
SELECT view_name, owner
FROM sys.all_views
ORDER BY owner, view_name
I found what I think is a faster solution. Install Git for Windows from here: http://git-scm.com/download/win
That automatically adds its path to the system variable during installation if you tell the installer to do so (it asks for that). So you don't have to edit anything manually.
Just close and restart Android Studio if it's open and you're ready to go.
To clarify. What is important to know is that:
Here is a working snippet of code, where we do a little bit of date manipulation to ensure Mongo (here i am using mongoose module and want results for rows whose date attribute is less than (before) the date given as myDate param) can handle it correctly:
var inputDate = new Date(myDate.toISOString());
MyModel.find({
'date': { $lte: inputDate }
})
A variation of the materialized view "Possible alternative" outlined by Erwin Brandstetter is possible.
Say, for example, that you don't want duplicates in the randomized values that are returned. So you will need to set a boolean value on the primary table containing your (non-randomized) set of values.
Assuming this is the input table:
id_values id | used
----+--------
1 | FALSE
2 | FALSE
3 | FALSE
4 | FALSE
5 | FALSE
...
Populate the ID_VALUES
table as needed. Then, as described by Erwin, create a materialized view that randomizes the ID_VALUES
table once:
CREATE MATERIALIZED VIEW id_values_randomized AS
SELECT id
FROM id_values
ORDER BY random();
Note that the materialized view does not contain the used column, because this will quickly become out-of-date. Nor does the view need to contain other columns that may be in the id_values
table.
In order to obtain (and "consume") random values, use an UPDATE-RETURNING on id_values
, selecting id_values
from id_values_randomized
with a join, and applying the desired criteria to obtain only relevant possibilities. For example:
UPDATE id_values
SET used = TRUE
WHERE id_values.id IN
(SELECT i.id
FROM id_values_randomized r INNER JOIN id_values i ON i.id = r.id
WHERE (NOT i.used)
LIMIT 5)
RETURNING id;
Change LIMIT
as necessary -- if you only need one random value at a time, change LIMIT
to 1
.
With the proper indexes on id_values
, I believe the UPDATE-RETURNING should execute very quickly with little load. It returns randomized values with one database round-trip. The criteria for "eligible" rows can be as complex as required. New rows can be added to the id_values
table at any time, and they will become accessible to the application as soon as the materialized view is refreshed (which can likely be run at an off-peak time). Creation and refresh of the materialized view will be slow, but it only needs to be executed when new id's are added to the id_values
table.
Map.Entry interface come pretty close to c++ pair. Look at the concrete implementation, like AbstractMap.SimpleEntry and AbstractMap.SimpleImmutableEntry First item is getKey() and second is getValue().
you can use moment.js to format with local time:
Date.prototype.toISOString = function () {
return moment(this).format("YYYY-MM-DDTHH:mm:ss");
};
CASE
is an expression - it returns a single scalar value (per row). It can't return a complex part of the parse tree of something else, like an ORDER BY
clause of a SELECT
statement.
It looks like you just need:
ORDER BY
CASE WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount END desc,
CASE WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount END desc,
Case WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount END DESC,
CASE WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount END DESC,
Case WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount END DESC,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
Or possibly:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
It's a little tricky to tell which of the above (or something else) is what you're looking for because you've a) not explained what actual sort order you're trying to achieve, and b) not supplied any sample data and expected results, from which we could attempt to deduce the actual sort order you're trying to achieve.
This may be the answer we're looking for:
ORDER BY
CASE
WHEN TblList.PinRequestCount <> 0 THEN 5
WHEN TblList.HighCallAlertCount <> 0 THEN 4
WHEN TblList.HighAlertCount <> 0 THEN 3
WHEN TblList.MediumCallAlertCount <> 0 THEN 2
WHEN TblList.MediumAlertCount <> 0 THEN 1
END desc,
CASE
WHEN TblList.PinRequestCount <> 0 THEN TblList.PinRequestCount
WHEN TblList.HighCallAlertCount <> 0 THEN TblList.HighCallAlertCount
WHEN TblList.HighAlertCount <> 0 THEN TblList.HighAlertCount
WHEN TblList.MediumCallAlertCount <> 0 THEN TblList.MediumCallAlertCount
WHEN TblList.MediumAlertCount <> 0 THEN TblList.MediumAlertCount
END desc,
TblList.LastName ASC, TblList.FirstName ASC, TblList.MiddleName ASC
How about this? (If you're using jQuery)
var $window = $(window);
var $body = $(window.document.body);
window.onscroll = function() {
var overlay = $body.children(".ui-widget-overlay").first();
// Check if the overlay is visible and restore the previous scroll state
if (overlay.is(":visible")) {
var scrollPos = $body.data("scroll-pos") || { x: 0, y: 0 };
window.scrollTo(scrollPos.x, scrollPos.y);
}
else {
// Just store the scroll state
$body.data("scroll-pos", { x: $window.scrollLeft(), y: $window.scrollTop() });
}
};
The below url is doing same as above answers. Instead of downloading some jar files and doing much activities, you can try to decompile by:
-background white -alpha remove -alpha off
Example:
convert image.png -background white -alpha remove -alpha off white.png
Feel free to replace white
with any other color you want. Imagemagick documentation says this about the -alpha remove
operation:
This operation is simple and fast, and does the job without needing any extra memory use, or other side effects that may be associated with alternative transparency removal techniques. It is thus the preferred way of removing image transparency.
Dynamic Base Url (codeigniter)
Just overwrite the line in config/config.php with the following:
$config['base_url'] = 'http://'.$_SERVER['HTTP_HOST'].'/';
You should put this line in your application context:
<context:component-scan base-package="com.cinebot.service" />
Read more about Automatically detecting classes and registering bean definitions in documentation.
I don't suggest you just hidding the stricts errors on your project. Intead, you should turn your method to static or try to creat a new instance of the object:
$var = new YourClass();
$var->method();
You can also use the new way to do the same since PHP 5.4:
(new YourClass)->method();
I hope it helps you!
This is mainly for future readers. As the question (at least the title) focuses on "connecting to sql server database from node js", I would like to chip in about "mssql" node module.
At this moment, we have a stable version of Microsoft SQL Server driver for NodeJs ("msnodesql") available here: https://www.npmjs.com/package/msnodesql. While it does a great job of native integration to Microsoft SQL Server database (than any other node module), there are couple of things to note about.
"msnodesql" require a few pre-requisites (like python, VC++, SQL native client etc.) to be installed on the host machine. That makes your "node" app "Windows" dependent. If you are fine with "Windows" based deployment, working with "msnodesql" is the best.
On the other hand, there is another module called "mssql" (available here https://www.npmjs.com/package/mssql) which can work with "tedious" or "msnodesql" based on configuration. While this module may not be as comprehensive as "msnodesql", it pretty much solves most of the needs.
If you would like to start with "mssql", I came across a simple and straight forward video, which explains about connecting to Microsoft SQL Server database using NodeJs here: https://www.youtube.com/watch?v=MLcXfRH1YzE
Source code for the above video is available here: http://techcbt.com/Post/341/Node-js-basic-programming-tutorials-videos/how-to-connect-to-microsoft-sql-server-using-node-js
Just in case, if the above links are not working, I am including the source code here:
var sql = require("mssql");_x000D_
_x000D_
var dbConfig = {_x000D_
server: "localhost\\SQL2K14",_x000D_
database: "SampleDb",_x000D_
user: "sa",_x000D_
password: "sql2014",_x000D_
port: 1433_x000D_
};_x000D_
_x000D_
function getEmp() {_x000D_
var conn = new sql.Connection(dbConfig);_x000D_
_x000D_
conn.connect().then(function () {_x000D_
var req = new sql.Request(conn);_x000D_
req.query("SELECT * FROM emp").then(function (recordset) {_x000D_
console.log(recordset);_x000D_
conn.close();_x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
conn.close();_x000D_
}); _x000D_
})_x000D_
.catch(function (err) {_x000D_
console.log(err);_x000D_
});_x000D_
_x000D_
//--> another way_x000D_
//var req = new sql.Request(conn);_x000D_
//conn.connect(function (err) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// return;_x000D_
// }_x000D_
// req.query("SELECT * FROM emp", function (err, recordset) {_x000D_
// if (err) {_x000D_
// console.log(err);_x000D_
// }_x000D_
// else { _x000D_
// console.log(recordset);_x000D_
// }_x000D_
// conn.close();_x000D_
// });_x000D_
//});_x000D_
_x000D_
}_x000D_
_x000D_
getEmp();
_x000D_
The above code is pretty self explanatory. We define the db connection parameters (in "dbConfig" JS object) and then use "Connection" object to connect to SQL Server. In order to execute a "SELECT" statement, in this case, it uses "Request" object which internally works with "Connection" object. The code explains both flavors of using "promise" and "callback" based executions.
The above source code explains only about connecting to sql server database and executing a SELECT query. You can easily take it to the next level by following documentation of "mssql" node available at: https://www.npmjs.com/package/mssql
UPDATE: There is a new video which does CRUD operations using pure Node.js REST standard (with Microsoft SQL Server) here: https://www.youtube.com/watch?v=xT2AvjQ7q9E. It is a fantastic video which explains everything from scratch (it has got heck a lot of code and it will not be that pleasing to explain/copy the entire code here)
@author MADMILK
@echo off
:getback1
set /p jump1=Do you want to compile? Write yes/no :
if %jump1% = yes
goto loop
if %jump1% = no
goto getback2
:: Important part here
:getback2
set /p jump2=Do you want to run a java program? Write yes/no :
if %jump2% = yes
goto loop2
if %jump2% = no
goto getback1
:: Make a folder anywhere what you want to use for scripts, for example i make one.
cd desktop
:: This is the folder where is gonna be your script(s)
mkdir My Scripts
cd My Scripts
title Java runner/compiler
echo REMEMBER! LOWER CASES AND UPPER CASES ARE IMPORTANT!
:loop
echo This is the java compiler program.
set /p jcVal=What java program do you want to compile? :
javac %jcVal%
:loop2
echo This is the java code runner program.
set /p javaVal=What java program do you want to run? :
java %javaVal%
pause >nul
echo Press NOTHING to leave
I have see Eclipse - java.lang.ClassNotFoundException when running junit tests. I had deleted one of the external jar files which was added to the project. After removing the reference of this jar file to the project from Eclipse. i could run the Junit tests .
If you want to display for example all .config
(or .ini
) file name and file content into one doc for user reference (and by this I mean user not knowing shell command i.e. 95% of them), you can try this :
FORFILES /M *myFile.ini /C "cmd /c echo File name : @file >> %temp%\stdout.txt && type @path >> %temp%\stdout.txt && echo. >> %temp%\stdout.txt" | type %temp%\stdout.txt
Explanation :
Ps : The last pipe command is pointing the %temp%
file and output the aggregate content. If you wish to copy/paste in some documentation, just open the stdout.txt file in textpad.
You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:
http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html
Follow 3 simple steps to secure API/Secret key (Old answer)
We can use Gradle to secure the API key or Secret key.
1. gradle.properties (Project properties) : Create variable with key.
GoolgeAPIKey = "Your API/Secret Key"
2. build.gradle (Module: app) : Set variable in build.gradle to access it in activity or fragment. Add below code to buildTypes {}.
buildTypes.each {
it.buildConfigField 'String', 'GoogleSecAPIKEY', GoolgeAPIKey
}
3. Access it in Activity/Fragment by app's BuildConfig :
BuildConfig.GoogleSecAPIKEY
The above solution is helpful in the open source project to commit over Git. (Thanks to David Rawson and riyaz-ali for your comment).
As per the Matthew and Pablo Cegarra comments the above way is not secure and Decompiler will allow someone to view the BuildConfig with our secret keys.
Solution :
We can use NDK to Secure API Keys. We can store keys in the native C/C++ class and access them in our Java classes.
Please follow this blog to secure API keys using NDK.
I had the same problem with spring boot. It resolved when i set package to marshaller.
@Bean
public Jaxb2Marshaller marshaller() throws Exception
{
Jaxb2Marshaller marshaller = new Jaxb2Marshaller();
marshaller.setPackagesToScan("com.octory.ws.dto");
return marshaller;
}
@Bean
public WebServiceTemplate webServiceTemplate(final Jaxb2Marshaller marshaller)
{
WebServiceTemplate webServiceTemplate = new WebServiceTemplate();
webServiceTemplate.setMarshaller(marshaller);
webServiceTemplate.setUnmarshaller(marshaller);
return webServiceTemplate;
}
while(document.getElementById("DropList").childNodes.length>0)
{
document.getElementById("DropList").removeChild(document.getElementById("DropList").childNodes[0]);
}
This is an older thread,but I will post my answer for others. I have to recreate the project in a different workspace after the changes to make it work, as discussed in JavaServer Faces 2.2 requires Dynamic Web Module 2.5 or newer
I had the same issue, in my case the following was missing from my xxx-servlet.xml config file
<mvc:annotation-driven/>
As soon I added this it it worked.
My biggest headache was working without a namespaced path. Something like this:
./src/app.js
./src/ui/menu.js
./node_modules/lodash/
Before I used to set my environment to do this:
require('app.js')
require('ui/menu')
require('lodash')
I found far more convenient avoiding an implicit src
path, which hides important context information.
My aim is to require like this:
require('src/app.js')
require('src/ui/menu')
require('test/helpers/auth')
require('lodash')
As you see, all my app code lives within a mandatory path namespace. This makes quite clear which require call takes a library, app code or a test file.
For this I make sure that my resolve paths are just node_modules
and the current app folder, unless you namespace your app inside your source folder like src/my_app
This is my default with webpack
resolve: {
extensions: ['', '.jsx', '.js', '.json'],
root: path.resolve(__dirname),
modulesDirectories: ['node_modules']
}
It would be even better if you set the environment var NODE_PATH
to your current project file. This is a more universal solution and it will help if you want to use other tools without webpack: testing, linting...
It's quite simple.
All you need to do is:
This is a pretty old question but i think still relevant. Also the accepted answer works only for String. Meanwhile there is Mockito 2.1 and some imports have changed, so i would like to share my current answer:
import static org.mockito.AdditionalAnswers.returnsFirstArg;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.Mockito.when;
@Mock
private MyClass myClass;
// this will return anything you pass, but it's pretty unrealistic
when(myClass.myFunction(any())).then(returnsFirstArg());
// it is more "life-like" to accept only the right type
when(myClass.myFunction(any(ClassOfArgument.class))).then(returnsFirstArg());
The myClass.myFunction would look like:
public class MyClass {
public ClassOfArgument myFunction(ClassOfArgument argument){
return argument;
}
}
.navbar {
background-color: transparent;
background: transparent;
border-color: transparent;
}
.navbar li { color: #000 }
To extend the given answer with few useful tricks:
var markers = //some array;
var bounds = new google.maps.LatLngBounds();
for(i=0;i<markers.length;i++) {
bounds.extend(markers[i].getPosition());
}
//center the map to a specific spot (city)
map.setCenter(center);
//center the map to the geometric center of all markers
map.setCenter(bounds.getCenter());
map.fitBounds(bounds);
//remove one zoom level to ensure no marker is on the edge.
map.setZoom(map.getZoom()-1);
// set a minimum zoom
// if you got only 1 marker or all markers are on the same address map will be zoomed too much.
if(map.getZoom()> 15){
map.setZoom(15);
}
//Alternatively this code can be used to set the zoom for just 1 marker and to skip redrawing.
//Note that this will not cover the case if you have 2 markers on the same address.
if(count(markers) == 1){
map.setMaxZoom(15);
map.fitBounds(bounds);
map.setMaxZoom(Null)
}
UPDATE:
Further research in the topic show that fitBounds() is a asynchronic
and it is best to make Zoom manipulation with a listener defined before calling Fit Bounds.
Thanks @Tim, @xr280xr, more examples on the topic : SO:setzoom-after-fitbounds
google.maps.event.addListenerOnce(map, 'bounds_changed', function(event) {
this.setZoom(map.getZoom()-1);
if (this.getZoom() > 15) {
this.setZoom(15);
}
});
map.fitBounds(bounds);
To Expand on what @PythonIsGreat said, I create a global function that will do it for me:
var css = function(){
var args = $.merge([true, {}], Array.prototype.splice.call(arguments, 0));
return $.extend.apply(null, args);
}
This deeply extends the objects into a new object and allows for a variable number of objects as parameters. This allows you to do something like this:
return(
<div style={css(styles.base, styles.first, styles.second,...)} ></div>
);
var styles = {
base:{
//whatever
},
first:{
//whatever
},
second:{
//whatever
}
}
you can just use this code to hit the script using cron job using cpanel:
wget https://www.example.co.uk/unique-code
Do you want to address the individual bytes of a 32-bit int? One possible method is a union:
union
{
unsigned int integer;
unsigned char byte[4];
} foo;
int main()
{
foo.integer = 123456789;
printf("%u %u %u %u\n", foo.byte[3], foo.byte[2], foo.byte[1], foo.byte[0]);
}
Note: corrected the printf to reflect unsigned values.
Application program interface (API) is a set of routines, protocols, and tools for building software applications. An API specifies how software components should interact and APIs are used when programming graphical user interface (GUI) components. A good API makes it easier to develop a program by providing all the building blocks. A programmer then puts the blocks together.