UIActionSheet
is deprecated in iOS 8.
I am using following:
// Create the AlertController
let actionSheetController = UIAlertController(title: "Please select", message: "How you would like to utilize the app?", preferredStyle: .ActionSheet)
// Create and add the Cancel action
let cancelAction = UIAlertAction(title: "Cancel", style: .Cancel) { action -> Void in
// Just dismiss the action sheet
}
actionSheetController.addAction(cancelAction)
// Create and add first option action
let takePictureAction = UIAlertAction(title: "Consumer", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_customer", sender: self)
}
actionSheetController.addAction(takePictureAction)
// Create and add a second option action
let choosePictureAction = UIAlertAction(title: "Service provider", style: .Default) { action -> Void in
self.performSegueWithIdentifier("segue_setup_provider", sender: self)
}
actionSheetController.addAction(choosePictureAction)
// We need to provide a popover sourceView when using it on iPad
actionSheetController.popoverPresentationController?.sourceView = sender as UIView
// Present the AlertController
self.presentViewController(actionSheetController, animated: true, completion: nil)
To refresh menu from Fragment simply call:
getActivity().invalidateOptionsMenu();
In Android M the top solution won't work. I've written a helper class to fix that which you should call from your Application class and all Activities (I would suggest creating a BaseActivity and then make all the Activities inherit from it.
Note: This will also support properly RTL layout direction.
Helper class:
public class LocaleUtils {
private static Locale sLocale;
public static void setLocale(Locale locale) {
sLocale = locale;
if(sLocale != null) {
Locale.setDefault(sLocale);
}
}
public static void updateConfig(ContextThemeWrapper wrapper) {
if(sLocale != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
Configuration configuration = new Configuration();
configuration.setLocale(sLocale);
wrapper.applyOverrideConfiguration(configuration);
}
}
public static void updateConfig(Application app, Configuration configuration) {
if (sLocale != null && Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
//Wrapping the configuration to avoid Activity endless loop
Configuration config = new Configuration(configuration);
// We must use the now-deprecated config.locale and res.updateConfiguration here,
// because the replacements aren't available till API level 24 and 17 respectively.
config.locale = sLocale;
Resources res = app.getBaseContext().getResources();
res.updateConfiguration(config, res.getDisplayMetrics());
}
}
}
Application:
public class App extends Application {
public void onCreate(){
super.onCreate();
LocaleUtils.setLocale(new Locale("iw"));
LocaleUtils.updateConfig(this, getBaseContext().getResources().getConfiguration());
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
LocaleUtils.updateConfig(this, newConfig);
}
}
BaseActivity:
public class BaseActivity extends Activity {
public BaseActivity() {
LocaleUtils.updateConfig(this);
}
}
Rather than:
first_element = myList[i[0]]
You probably want:
first_element = myList[i][0]
You can change your approach slightly - use Console.ReadKey()
to stop your app, but do your work in a background thread:
static void Main(string[] args)
{
var myWorker = new MyWorker();
myWorker.DoStuff();
Console.WriteLine("Press any key to stop...");
Console.ReadKey();
}
In the myWorker.DoStuff()
function you would then invoke another function on a background thread (using Action<>()
or Func<>()
is an easy way to do it), then immediately return.
Single quotes should be used for string values like in the VALUES() list.
Backticks are generally used to indicate an identifier and as well be safe from accidentally using the reserved keywords.
In combination of PHP and MySQL, double quotes and single quotes make your query writing time so much easier.
If you have a checkbox with an id checkbox_id.You can set its state with JS with prop('checked', false)
or prop('checked', true)
$('#checkbox_id').prop('checked', false);
You can rewrite it to use the ELSE condition of a CASE
:
SELECT status,
CASE status
WHEN 'i' THEN 'Inactive'
WHEN 't' THEN 'Terminated'
ELSE 'Active'
END AS StatusText
FROM stage.tst
In combination with what Guffa described, you could use the technique described in
Explanation of <script type = "text/template"> ... </script> to store the HTML document in a special script
element (see the link for an explanation on how this works). That's a lot easier than storing the HTML document in a string.
how to determine if a commit with particular hash have been pushed to the origin already?
# list remote branches that contain $commit
git branch -r --contains $commit
String
objects in Java use the UTF-16 encoding that can't be modified.
The only thing that can have a different encoding is a byte[]
. So if you need UTF-8 data, then you need a byte[]
. If you have a String
that contains unexpected data, then the problem is at some earlier place that incorrectly converted some binary data to a String
(i.e. it was using the wrong encoding).
CSS
solution works without a glitch!
https://www.w3schools.com/code/tryit.asp?filename=GJ4PCJMVQ4LN https://www.w3schools.com/code/tryit.asp?filename=GJ4PPLCCEBRG
.col-info:hover>.popoverIcon {
visibility: visible;
}
}
.popoverIcon {
visibility: hidden;
}
_x000D_
<div *ngFor="let i of [1,2,3,4]">
<div class="col-info">
<span class=" popoverIcon ">Show {{i}}</span>
</div>
</div>
_x000D_
We can also read by the name.
Say we have saved the value with name 'user' like this
localStorage.setItem('user', user_Detail);
Then we can read it by using
localStorage.getItem('user');
I used it and it is working smooth, no need to do the for loop
I might be misunderstanding your question, so apologies if I am.
If you're looking for the words "Quid", "Application Number", etc. to be bold, just wrap them in <strong>
tags:
<strong>Quid</strong>: ...
Hope that helps!
You can use index arrays, simply pass your ind_pos
as an index argument as below:
a = np.array([0,88,26,3,48,85,65,16,97,83,91])
ind_pos = np.array([1,5,7])
print(a[ind_pos])
# [88,85,16]
Index arrays do not necessarily have to be numpy arrays, they can be also be lists or any sequence-like object (though not tuples).
Sure, you can do nested ternary operators but they are hard to read.
var variable = (condition) ? (true block) : ((condition2) ? (true block2) : (else block2))
Here's the explanation I use in teaching Python classes:
An ITERABLE is:
for x in iterable: ...
oriter()
that will return an ITERATOR: iter(obj)
or__iter__
that returns a fresh ITERATOR,
or it may have a __getitem__
method suitable for indexed lookup.An ITERATOR is an object:
__next__
method that:
StopIteration
__iter__
method that returns self
).Notes:
__next__
method in Python 3 is spelt next
in Python 2, andnext()
calls that method on the object passed to it.For example:
>>> s = 'cat' # s is an ITERABLE
# s is a str object that is immutable
# s has no state
# s has a __getitem__() method
>>> t = iter(s) # t is an ITERATOR
# t has state (it starts by pointing at the "c"
# t has a next() method and an __iter__() method
>>> next(t) # the next() function returns the next value and advances the state
'c'
>>> next(t) # the next() function returns the next value and advances
'a'
>>> next(t) # the next() function returns the next value and advances
't'
>>> next(t) # next() raises StopIteration to signal that iteration is complete
Traceback (most recent call last):
...
StopIteration
>>> iter(t) is t # the iterator is self-iterable
based on @Guffa answer
because I lost more than 2 hours to center a very wide image,
for me with a image dimendion of 2500x100px and viewport 1600x1200 or Full HD 1900x1200
works centered like that:
.imageContainer {
height: 100px;
overflow: hidden;
position: relative;
}
.imageCenter {
width: auto;
position: absolute;
left: -10%;
top: 0;
margin-left: -500px;
}
.imageCenter img {
display: block;
margin: 0 auto;
}
I Hope this helps others to finish faster the task :)
You need to get mac for it. There are several tool chains available (like win-chain) that actually lets you write and build i Phone applications on windows. There are several associated tutorials to build the Objective C code on Windows. But there is a problem, the apps hence developed will work on Jail broken i Phones only.
We’ve seen few hacks to get over that and make it to App Store, but as Apple keeps on updating SDKs, tool chains need regular updates. It’s a hassle to make it up all the time.If you want to get ready app you can also take help from arcapps its launches apps at a reasonable price. iphone app development
When reading sp_lock information, use the OBJECT_NAME( ) function to get the name of a table from its ID number, for example:
SELECT object_name(16003073)
EDIT :
There is another proc provided by microsoft which reports objects without the ID translation : http://support.microsoft.com/kb/q255596/
To calculate the sum of a column in a DataTable use the DataTable.Compute method.
Example of usage from the linked MSDN article:
DataTable table = dataSet.Tables["YourTableName"];
// Declare an object variable.
object sumObject;
sumObject = table.Compute("Sum(Amount)", string.Empty);
Display the result in your Total Amount Label like so:
lblTotalAmount.Text = sumObject.ToString();
Alternatively, you can use numpy underlying function:
>>> import numpy as np
>>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
>>> df['new_column'] = np.multiply(df['A'], df['B'])
>>> df
A B new_column
0 10 20 200
1 20 30 600
2 30 10 300
or vectorize arbitrary function in general case:
>>> def fx(x, y):
... return x*y
...
>>> df['new_column'] = np.vectorize(fx)(df['A'], df['B'])
>>> df
A B new_column
0 10 20 200
1 20 30 600
2 30 10 300
I've had this same problem, and I wrote a one-liner in shell to do it.
rm -rf $(mvn help:evaluate -Dexpression=settings.localRepository\
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN -B \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn | grep -vF '[INFO]')/*
I did it as a one-liner because I wanted to have a Jenkins-project to simply run this whenever I needed, so I wouldn't have to log on to stuff, etc. If you allow yourself a shell-script for it, you can write it cleaner:
#!/usr/bin/env bash
REPOSITORY=$(mvn help:evaluate \
-Dexpression=settings.localRepository \
-Dorg.slf4j.simpleLogger.defaultLogLevel=WARN \
-Dorg.slf4j.simpleLogger.log.org.apache.maven.cli.transfer.Slf4jMavenTransferListener=warn \
--batch-mode \
| grep -vF '[INFO]')
rm -rf $REPOSITORY/*
Should work, but I have not tested all of that script. (I've tested the first command, but not the whole script.) This approach has the downside of running a large complicated command first. It is idempotent, so you can test it out for yourself. The deletion is its own command afterwards, and this lets you try it all out and check that it does what you think it does, because you shouldn't trust deletion commands without verification. However, it is smart for one good reason: It's portable. It respects your settings.xml file. If you're running this command, and tell maven to use a specific xml file (the -s or --settings argument), this will still work. So you don't have to fiddle with making sure everything is the same everywhere.
It's a bit wieldy, but it's a decent way of doing business, IMO.
This answer will not work correctly with root paths containing equal signs (=
). (Thanks @dbenham for pointing that out.)
EDITED: Fixed the issue with paths containing !
, again spotted by @dbenham (thanks!).
Alternatively to calculating the length and extracting substrings you could use a different approach:
store the root path;
clear the root path from the file paths.
Here's my attempt (which worked for me):
@ECHO OFF
SETLOCAL DisableDelayedExpansion
SET "r=%__CD__%"
FOR /R . %%F IN (*) DO (
SET "p=%%F"
SETLOCAL EnableDelayedExpansion
ECHO(!p:%r%=!
ENDLOCAL
)
The r
variable is assigned with the current directory. Unless the current directory is the root directory of a disk drive, it will not end with (No longer the case, as the script now reads the \
, which we amend by appending the character.__CD__
variable, whose value always ends with \
(thanks @jeb!), instead of CD
.)
In the loop, we store the current file path into a variable. Then we output the variable, stripping the root path along the way.
Use the colnames()
function:
R> X <- data.frame(bad=1:3, worse=rnorm(3))
R> X
bad worse
1 1 -2.440467
2 2 1.320113
3 3 -0.306639
R> colnames(X) <- c("good", "better")
R> X
good better
1 1 -2.440467
2 2 1.320113
3 3 -0.306639
You can also subset:
R> colnames(X)[2] <- "superduper"
Maybe, you can use moment.js which in my opinion is the best JavaScript library for parsing, formatting and working with dates client-side. You could use something like:
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');_x000D_
var jsDate = momentDate.toDate();_x000D_
_x000D_
// Now, you can run any JavaScript Date method_x000D_
_x000D_
jsDate.toLocaleString();
_x000D_
The advantage of using a library like moment.js is that your code will work perfectly even in legacy browsers like IE 8+.
Here is the documenation about parsing methods: https://momentjs.com/docs/#/parsing/
If you just want to get the information of current directory, you can type:
pwd
and you don't need to use the Nautilus, or you can use a teamviewer software to remote connect to the computer, you can get everything you want.
pat = re.compile ('[^\w-]')
def onlyallowed(s):
return not pat.search (s)
I found this somewhere else. I like this answer!
SELECT [Hourly], COUNT(*) as [Count]
FROM
(SELECT dateadd(hh, datediff(hh, '20010101', [date_created]), '20010101') as [Hourly]
FROM table) idat
GROUP BY [Hourly]
You can use $_SERVER['REQUEST_URI']
to get requested path. Then, you'll need to remove the parameters...
$uri_parts = explode('?', $_SERVER['REQUEST_URI'], 2);
Then, add in the hostname and protocol.
echo 'http://' . $_SERVER['HTTP_HOST'] . $uri_parts[0];
You'll have to detect protocol as well, if you mix http:
and https://
. That I leave as an exercise for you. $_SERVER['REQUEST_SCHEME']
returns the protocol.
Putting it all together:
echo $_SERVER['REQUEST_SCHEME'] .'://'. $_SERVER['HTTP_HOST'] . explode('?', $_SERVER['REQUEST_URI'], 2)[0];
...returns, for example:
http://example.com/directory/file.php
This beautiful code here creates a table with each td having array values. Not my code, but it helped me!
var rows = 6, cols = 7;
for(var i = 0; i < rows; i++) {
$('table').append('<tr></tr>');
for(var j = 0; j < cols; j++) {
$('table').find('tr').eq(i).append('<td></td>');
$('table').find('tr').eq(i).find('td').eq(j).attr('data-row', i).attr('data-col', j);
}
}
Why use the canvas to resize images? Modern browsers all use bicubic interpolation — the same process used by Photoshop (if you're doing it right) — and they do it faster than the canvas process. Just specify the image size you want (use only one dimension, height or width, to resize proportionally).
This is supported by most browsers, including later versions of IE. Earlier versions may require browser-specific CSS.
A simple function (using jQuery) to resize an image would be like this:
function resizeImage(img, percentage) {
var coeff = percentage/100,
width = $(img).width(),
height = $(img).height();
return {"width": width*coeff, "height": height*coeff}
}
Then just use the returned value to resize the image in one or both dimensions.
Obviously there are different refinements you could make, but this gets the job done.
Paste the following code into the console of this page and watch what happens to the gravatars:
function resizeImage(img, percentage) {
var coeff = percentage/100,
width = $(img).width(),
height = $(img).height();
return {"width": width*coeff, "height": height*coeff}
}
$('.user-gravatar32 img').each(function(){
var newDimensions = resizeImage( this, 150);
this.style.width = newDimensions.width + "px";
this.style.height = newDimensions.height + "px";
});
It's about the ABI, in order to let both C and C++ application use C interfaces without any issue.
Since C language is very easy, code generation was stable for many years for different compilers, such as GCC, Borland C\C++, MSVC etc.
While C++ becomes more and more popular, a lot things must be added into the new C++ domain (for example finally the Cfront was abandoned at AT&T because C could not cover all the features it needs). Such as template feature, and compilation-time code generation, from the past, the different compiler vendors actually did the actual implementation of C++ compiler and linker separately, the actual ABIs are not compatible at all to the C++ program at different platforms.
People might still like to implement the actual program in C++ but still keep the old C interface and ABI as usual, the header file has to declare extern "C" {}, it tells the compiler generate compatible/old/simple/easy C ABI for the interface functions if the compiler is C compiler not C++ compiler.
With EF or LINQ to SQL:
var item = db.Items.OrderByDescending(i => i.Value).FirstOrDefault();
With LINQ to Objects I suggest to use morelinq extension MaxBy
(get morelinq from nuget):
var item = items.MaxBy(i => i.Value);
use isset
for this purpose
<?php
$index = 1;
if(isset($_POST['filename'])) {
$filename = $_POST['filename'];
echo $filename;
}
?>
df.index
Index
object. list(df.index)
df.index['Row 2':'Row 5']
400 Bad Request is proper HTTP status code for your use case. The code is defined by HTTP/0.9-1.1 RFC.
The request could not be understood by the server due to malformed syntax. The client SHOULD NOT repeat the request without modifications.
http://tools.ietf.org/html/rfc2616#section-10.4.1
422 Unprocessable Entity is defined by RFC 4918 - WebDav. Note that there is slight difference in comparison to 400, see quoted text below.
This error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.
To keep uniform interface you should use 422 only in a case of XML responses and you should also support all status codes defined by Webdav extension, not just 422.
http://tools.ietf.org/html/rfc4918#page-78
See also Mark Nottingham's post on status codes:
it’s a mistake to try to map each part of your application “deeply” into HTTP status codes; in most cases the level of granularity you want to be aiming for is much coarser. When in doubt, it’s OK to use the generic status codes 200 OK, 400 Bad Request and 500 Internal Service Error when there isn’t a better fit.
There's a jQuery plugin out there called pjax it states: "It's ajax with real permalinks, page titles, and a working back button that fully degrades."
The plugin uses HTML5 pushState and AJAX to dynamically change pages without a full load. If pushState isn't supported, PJAX performs a full page load, ensuring backwards compatibility.
What pjax does is that it listens on specified page elements such as <a>
. Then when the <a href=""></a>
element is invoked, the target page is fetched with either the X-PJAX
header, or a specified fragment.
Example:
<script type="text/javascript">
$(document).pjax('a', '#pjax-container');
</script>
Putting this code in the page header will listen on all links in the document and set the element that you are both fetching from the new page and replacing on the current page.
(meaning you want to replace #pjax-container
on the current page with #pjax-container
from the remote page)
When <a>
is invoked, it will fetch the link with the request header X-PJAX
and will look for the contents of #pjax-container
in the result. If the result is #pjax-container
, the container on the current page will be replaced with the new result.
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript" src="jquery.min.js"></script>
<script type="text/javascript" src="jquery.pjax.js"></script>
<script type="text/javascript">
$(document).pjax('a', '#pjax-container');
</script>
</head>
<body>
<h1>My Site</h1>
<div class="container" id="pjax-container">
Go to <a href="/page2">next page</a>.
</div>
</body>
</html>
If #pjax-container
is not the first element found in the response, PJAX will not recognize the content and perform a full page load on the requested link. To fix this, the server backend code would need to be set to only send #pjax-container
.
Example server side code of page2
:
//if header X-PJAX == true in request headers, send
<div class="container" id="pjax-container">
Go to <a href="/page1">next page</a>.
</div>
//else send full page
If you can't change server-side code, then the fragment option is an alternative.
$(document).pjax('a', '#pjax-container', {
fragment: '#pjax-container'
});
Note that fragment
is an older pjax option and appears to fetch the child element of requested element.
For me it was an old version of npm
.
Run npm install npm@latest -g
and then npm install
Below is the method that worked for me on API 23-25 emulators. The explanation is provided for API 24 but works almost identically for other versions.
Credits: Jon Doe, zaidorx, pjl.
Warm advice for readers: please just go over the steps before following them, as some are automated via provided scripts.
In the AVD manager of Android studio (tested on v2.2.3), create a new emulator with the "Android 7.0 (Google APIs)" target:
Download the latest Open GApps package for the emulator's architecture (CPU/ABI). In my case it was x86_64
, but it can be something else depending on your choice of image during the device creation wizard. Interestingly, the architecture seems more important than the correct Android version (i.e. gapps for 6.0 also work on a 7.0 emulator).
Extract the .apk
files using from the following paths (relative to open_gapps-x86_64-7.0-pico-201#####.zip
):
.zip\Core\gmscore-x86_64.tar.lz\gmscore-x86_64\nodpi\priv-app\PrebuiltGmsCore\
.zip\Core\gsfcore-all.tar.lz\gsfcore-all\nodpi\priv-app\GoogleServicesFramework\
.zip\Core\gsflogin-all.tar.lz\gsflogin-all\nodpi\priv-app\GoogleLoginService\
.zip\Core\vending-all.tar.lz\vending-all\nodpi\priv-app\Phonesky\
Note that Open GApps use the Lzip compression, which can be opened using either the tool found on the Lzip website1,2, or on Mac using homebrew: brew install lzip
. Then e.g. lzip -d gmscore-x86_64.tar.lz
.
I'm providing a batch file that utilizes 7z.exe
and lzip.exe
to extract all required .apk
s automatically (on Windows):
@echo off
echo.
echo #################################
echo Extracting Gapps...
echo #################################
7z x -y open_gapps-*.zip -oGAPPS
echo Extracting Lzips...
lzip -d GAPPS\Core\gmscore-x86_64.tar.lz
lzip -d GAPPS\Core\gsfcore-all.tar.lz
lzip -d GAPPS\Core\gsflogin-all.tar.lz
lzip -d GAPPS\Core\vending-all.tar.lz
move GAPPS\Core\*.tar
echo.
echo #################################
echo Extracting tars...
echo #################################
7z e -y -r *.tar *.apk
echo.
echo #################################
echo Cleaning up...
echo #################################
rmdir /S /Q GAPPS
del *.tar
echo.
echo #################################
echo All done! Press any key to close.
echo #################################
pause>nul
To use this, save the script in a file (e.g. unzip_gapps.bat
) and put everything relevant in one folder, as demonstrated below:
Update the su
binary to be able to modify the permissions of the files we will later upload. A new su
binary can be found in the SuperSU by Chainfire package "Recovery flashable" zip
. Get the zip, extract it somewhere, create the a batch file with the following contents in the same folder, and finally run it:
adb root
adb remount
adb push eu.chainfire.supersu_2.78.apk /system/app/
adb push x64/su /system/xbin/su
adb shell chmod 755 /system/xbin/su
adb shell ln -s /system/xbin/su /system/bin/su
adb shell "su --daemon &"
adb shell rm /system/app/SdkSetup.apk
Put all .apk
files in one folder and create a batch file with these contents3:
START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
adb wait-for-device
adb root
adb shell stop
adb remount
adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore
adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework
adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService
adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
adb shell su root "chmod 777 /system/priv-app/**"
adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
adb shell start
Notice that the path E:\...\android-sdk\tools\emulator.exe
should be modified according to the location of the Android SDK on your system.
Execute the above batch file (the console should look like this afterwards):
O:\123>START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24 -no-boot-anim -writable-system
O:\123>adb wait-for-device
Hax is enabled
Hax ram_size 0x60000000
HAX is working and emulator runs in fast virt mode.
emulator: Listening for console connections on port: 5554
emulator: Serial number of this emulator (for ADB): emulator-5554
O:\123>adb root
O:\123>adb shell stop
O:\123>adb remount
remount succeeded
O:\123>adb push PrebuiltGmsCore.apk /system/priv-app/PrebuiltGmsCore/
[100%] /system/priv-app/PrebuiltGmsCore/PrebuiltGmsCore.apk
O:\123>adb push GoogleServicesFramework.apk /system/priv-app/GoogleServicesFramework/
[100%] /system/priv-app/GoogleServicesFramework/GoogleServicesFramework.apk
O:\123>adb push GoogleLoginService.apk /system/priv-app/GoogleLoginService/
[100%] /system/priv-app/GoogleLoginService/GoogleLoginService.apk
O:\123>adb push Phonesky.apk /system/priv-app/Phonesky/Phonesky.apk
[100%] /system/priv-app/Phonesky/Phonesky.apk
O:\123>adb shell su root "chmod 777 /system/priv-app/**"
O:\123>adb shell su root "chmod 777 /system/priv-app/PrebuiltGmsCore/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleServicesFramework/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/GoogleLoginService/*"
O:\123>adb shell su root "chmod 777 /system/priv-app/Phonesky/*"
O:\123>adb shell start
When the emulator loads - close it, delete the Virtual Device and then create another one using the same system image. This fixes the unresponsive Play Store app, "Google Play Services has stopped" and similar problems. It works because in the earlier steps we have actually modified the system image itself (take a look at the Date modified on android-sdk\system-images\android-24\google_apis\x86_64\system.img
). This means that every device created from now on with the system image will have gapps installed!
Start the new AVD. If it takes unusually long to load, close it and instead start it using:
START /B E:\...\android-sdk\tools\emulator.exe @Nexus_6_API_24
adb wait-for-device
adb shell "su --daemon &"
After the AVD starts you will see the image below - notice the Play Store icon in the corner!
3 - I'm not sure all of these commands are needed, and perhaps some of them are overkill... it seems to work - which is what counts. :)
What about:
@echo off
set myvar="the list: "
for /r %%i in (*.doc) DO call :concat %%i
echo %myvar%
goto :eof
:concat
set myvar=%myvar% %1;
goto :eof
echo $myarray[0]->['email'];
Try this only if it you are passing the stdclass object
change it to chart.googleapis.com for the path, otherwise SSL won't work
You cannot insert data because you have a quota of 0 on the tablespace. To fix this, run
ALTER USER <user> quota unlimited on <tablespace name>;
or
ALTER USER <user> quota 100M on <tablespace name>;
as a DBA user (depending on how much space you need / want to grant).
You can use this for header: Important: Put the following on your PHP pages that you want to include the content.
<?php
//at top:
require('header.php');
?>
<?php
// at bottom:
require('footer.php');
?>
You can also include a navbar globaly just use this instead:
<?php
// At top:
require('header.php');
?>
<?php
// At bottom:
require('footer.php');
?>
<?php
//Wherever navbar goes:
require('navbar.php');
?>
In header.php:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
</head>
<body>
Do Not close Body or Html tags!
Include html here:
<?php
//Or more global php here:
?>
Footer.php:
Code here:
<?php
//code
?>
Navbar.php:
<p> Include html code here</p>
<?php
//Include Navbar PHP code here
?>
Is your employer aware that he can "steal" back any ideas that other people get from your code? I mean, if they can read your work, so can you theirs. Maybe looking at how you can benefit from the situation would yield a better return of your investment than fearing how much you could lose.
[EDIT] Answer to Nick's comment:
Nothing gained and nothing lost. The customer has what he wants (and paid for it since he did the change himself). Since he doesn't release the change, it's as if it didn't happen for everyone else.
Now if the customer sells the software, they have to change the copyright notice (which is illegal, so you can sue and will win -> simple case).
If they don't change the copyright notice, the 2nd level customers will notice that the software comes from you original and wonder what is going on. Chances are that they will contact you and so you will learn about the reselling of your work.
Again we have two cases: The original customer sold only a few copies. That means they didn't make much money anyway, so why bother. Or they sold in volume. That means better chances for you to learn about what they do and do something about it.
But in the end, most companies try to comply to the law (once their reputation is ruined, it's much harder to do business). So they will not steal your work but work with you to improve it. So if you include the source (with a license that protects you from simple reselling), chances are that they will simply push back changes they made since that will make sure the change is in the next version and they don't have to maintain it. That's win-win: You get changes and they can make the change themselves if they really, desperately need it even if you're unwilling to include it in the official release.
You can use:
String.prototype.replaceAll = function(search, replace) {
if (replace === undefined) {
return this.toString();
}
return this.split(search).join(replace);
}
New Table...
def exit(self):
self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)
This worked for me to destroy my Tkinter frame on clicking the exit button.
For a long time I have used the alternative:
('netscape' in window) && / rv:/.test(navigator.userAgent)
because I don't trust user agent strings. Some bugs are not detectable using feature detection, so detecting the browser is required for some workarounds.
Also if you are working around a bug in Gecko, then the bug is probably also in derivatives of Firefox, and this code should work with derivatives too (Do Waterfox and Pale Moon have 'Firefox' in the user agent string?).
Do one of the two jQuery serializers inside your form submit to get all inputs having a submitted value.
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serializeArray();
var formData = JSON.stringify(criteria);
serializeArray() will produce an array of names and values
0: {name: "OwnLast", value: "Bird"}
1: {name: "OwnFirst", value: "Bob"}
2: {name: "OutBldg[]", value: "PDG"}
3: {name: "OutBldg[]", value: "PDA"}
var criteria = $(this).find('input,select').filter(function () {
return ((!!this.value) && (!!this.name));
}).serialize();
serialize() creates a text string in standard URL-encoded notation
"OwnLast=Bird&OwnFirst=Bob&OutBldg%5B%5D=PDG&OutBldg%5B%5D=PDA"
Re-raising exceptions:
# Python 2 syntax
try:
some_operation()
except SomeError, e:
if is_fatal(e):
raise
handle_nonfatal(e)
# Python 3 syntax
try:
some_operation()
except SomeError as e:
if is_fatal(e):
raise
handle_nonfatal(e)
The 'raise' statement with no arguments inside an error handler tells Python to re-raise the exception with the original traceback intact, allowing you to say "oh, sorry, sorry, I didn't mean to catch that, sorry, sorry."
If you wish to print, store or fiddle with the original traceback, you can get it with sys.exc_info(), and printing it like Python would is done with the 'traceback' module.
You can use this following code. work just on chrome browser.
function failed(e) {_x000D_
// video playback failed - show a message saying why_x000D_
switch (e.target.error.code) {_x000D_
case e.target.error.MEDIA_ERR_ABORTED:_x000D_
alert('You aborted the video playback.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_NETWORK:_x000D_
alert('A network error caused the video download to fail part-way.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_DECODE:_x000D_
alert('The video playback was aborted due to a corruption problem or because the video used features your browser did not support.');_x000D_
break;_x000D_
case e.target.error.MEDIA_ERR_SRC_NOT_SUPPORTED:_x000D_
alert('The video could not be loaded, either because the server or network failed or because the format is not supported.');_x000D_
break;_x000D_
default:_x000D_
alert('An unknown error occurred.');_x000D_
break;_x000D_
}_x000D_
}
_x000D_
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">_x000D_
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">_x000D_
_x000D_
<head>_x000D_
<meta http-equiv="content-type" content="text/html; charset=iso-8859-1" />_x000D_
<meta name="author" content="Amin Developer!" />_x000D_
_x000D_
<title>Untitled 1</title>_x000D_
</head>_x000D_
<body>_x000D_
_x000D_
<p><video src="http://jell.yfish.us/media/Jellyfish-3-Mbps.mkv" type='video/x-matroska; codecs="theora, vorbis"' autoplay controls onerror="failed(event)" ></video></p>_x000D_
<p><a href="YOU mkv FILE LINK GOES HERE TO DOWNLOAD">Download the video file</a>.</p>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
Try reindex.
UPDATE: As pointed out in the comments, this was in reply to the original question.
[1,3].inject([1,1,1,2,2,3]) do |memo,element|
memo.tap do |memo|
i = memo.find_index(e)
memo.delete_at(i) if i
end
end
I just added an @ symbol and it started working. Like this: @$product->save();
Solution in Swift 3:
button.setTitleColor(UIColor.red, for: .normal)
This will set the title color of button.
Just wrap your inner message inside a div on which you apply your padding : http://jsfiddle.net/Ez9C4/
<div id="message">
<div style="padding: 5px;">
<div id="inner-message" class="alert alert-error">
<button type="button" class="close" data-dismiss="alert">×</button>
test error message
</div>
</div>
</div>
After many attempts I was finally able to get this working. Essentially what I did was download and use the vmware converter to merge the two disks into one. After that I was able to attach the newly created disk to VitrualBox.
The steps involved are very simple:
BEFORE YOU DO ANYTHING!
1) MAKE A BACKUP!!! Even if you follow these instruction, you could screw things up, so make a backup. Just shutdown the VM and then make a copy of the directory where VM resides.
2) Uninstall VMware Tools from the VM that you are going to convert. If for some reason you forget this step, you can still uninstall it after getting everything running under VirtualBox by following these steps. Do yourself the favor and just do it now.
NOW THE FUN PART!!!
1) Download and install the VMware Converter. I used 5.0.1 build-875114, just use the latest.
2) Download and install VirtualBox
3) Fire up VMWare convertor:
4) Click on Convert machine
6) Browse to the .vmx
for your VM and click Next
.
7) Give the new VM a name and select the location where you want to put it. Click Next
8) Click Next
on the Options
screen. You shouldn't have to change anything here.
9) Click Finish
on the Summary
screen to begin the conversion.
10) The conversion should start. This will take a LOOONG time so be patient.
11) Hopefully all went well, if it did, you should see that the conversion is completed:
12) Now open up VirtualBox and click New
.
13) Give your VM a name and select what Type
and Version
it is. Click Next
.
14) Select the size of the memory you want to give it. Click Next
.
15) For the Hard Drive
, click Use and existing hard drive file
and select the newly converted .vmdk
file.
16) Now Click Settings
and select the Storage
menu. The issue is that by default VirtualBox will add the drive as an IDE. This won't work and we need as we need to put it on a SCSI controller.
17) Select the IDE controller and the Remove Controller
button.
18) Now click the Add Controller
button and select Add SCSI Controller
19) Click the Add Hard Disk
button.
20) Click Choose existing disk
21) Select your .vmdk
file. Click OK
22) Select the System
menu.
23) Click Enable IO APIC
. Then click OK
24) Congrats!!! Your VM is now confgiured! Click Start
to startup the VM!
Nice question, a while ago I've experimented a bit with this, but haven't used it a lot because it's still not bulletproof. I divided the plot area into a 32x32 grid and calculated a 'potential field' for the best position of a label for each line according the following rules:
The code was something like this:
import matplotlib.pyplot as plt
import numpy as np
from scipy import ndimage
def my_legend(axis = None):
if axis == None:
axis = plt.gca()
N = 32
Nlines = len(axis.lines)
print Nlines
xmin, xmax = axis.get_xlim()
ymin, ymax = axis.get_ylim()
# the 'point of presence' matrix
pop = np.zeros((Nlines, N, N), dtype=np.float)
for l in range(Nlines):
# get xy data and scale it to the NxN squares
xy = axis.lines[l].get_xydata()
xy = (xy - [xmin,ymin]) / ([xmax-xmin, ymax-ymin]) * N
xy = xy.astype(np.int32)
# mask stuff outside plot
mask = (xy[:,0] >= 0) & (xy[:,0] < N) & (xy[:,1] >= 0) & (xy[:,1] < N)
xy = xy[mask]
# add to pop
for p in xy:
pop[l][tuple(p)] = 1.0
# find whitespace, nice place for labels
ws = 1.0 - (np.sum(pop, axis=0) > 0) * 1.0
# don't use the borders
ws[:,0] = 0
ws[:,N-1] = 0
ws[0,:] = 0
ws[N-1,:] = 0
# blur the pop's
for l in range(Nlines):
pop[l] = ndimage.gaussian_filter(pop[l], sigma=N/5)
for l in range(Nlines):
# positive weights for current line, negative weight for others....
w = -0.3 * np.ones(Nlines, dtype=np.float)
w[l] = 0.5
# calculate a field
p = ws + np.sum(w[:, np.newaxis, np.newaxis] * pop, axis=0)
plt.figure()
plt.imshow(p, interpolation='nearest')
plt.title(axis.lines[l].get_label())
pos = np.argmax(p) # note, argmax flattens the array first
best_x, best_y = (pos / N, pos % N)
x = xmin + (xmax-xmin) * best_x / N
y = ymin + (ymax-ymin) * best_y / N
axis.text(x, y, axis.lines[l].get_label(),
horizontalalignment='center',
verticalalignment='center')
plt.close('all')
x = np.linspace(0, 1, 101)
y1 = np.sin(x * np.pi / 2)
y2 = np.cos(x * np.pi / 2)
y3 = x * x
plt.plot(x, y1, 'b', label='blue')
plt.plot(x, y2, 'r', label='red')
plt.plot(x, y3, 'g', label='green')
my_legend()
plt.show()
And the resulting plot:
1: No difference. It is kept around to allow old S-code to continue to function. This is documented a "Note" in ?Math
2: Yes: But you already know it:
`^`(x,y)
#[1] 1024
In R the mathematical operators are really functions that the parser takes care of rearranging arguments and function names for you to simulate ordinary mathematical infix notation. Also documented at ?Math
.
Edit: Let me add that knowing how R handles infix operators (i.e. two argument functions) is very important in understanding the use of the foundational infix "[[" and "["-functions as (functional) second arguments to lapply
and sapply
:
> sapply( list( list(1,2,3), list(4,3,6) ), "[[", 1)
[1] 1 4
> firsts <- function(lis) sapply(lis, "[[", 1)
> firsts( list( list(1,2,3), list(4,3,6) ) )
[1] 1 4
I guess it depends on what you want. For simple objects, I guess you could use the second methods. When your objects grow larger and you're planning on using similar objects, I guess the first method would be better. That way you can also extend it using prototypes.
Example:
function Circle(radius) {
this.radius = radius;
}
Circle.prototype.getCircumference = function() {
return Math.PI * 2 * this.radius;
};
Circle.prototype.getArea = function() {
return Math.PI * this.radius * this.radius;
}
I am not a big fan of the third method, but it's really useful for dynamically editing properties, for example var foo='bar'; var bar = someObject[foo];
.
No curly braces required you can directly write
@if($user->status =='waiting')
<td><a href="#" class="viewPopLink btn btn-default1" role="button" data-id="{{ $user->travel_id }}" data-toggle="modal" data-target="#myModal">Approve/Reject<a></td>
@else
<td>{{ $user->status }}</td>
@endif
CSS:
#sidebar {float: right; width: 200px; background: #eee;}
#content {overflow: hidden; background: #dad;}
HTML:
<div id="sidebar">I'm 200px wide</div>
<div id="content"> I take up the remaining space <br> and I don't wrap under the right column</div>
The above should work, you can put that code in wrapper if you want the give it width and center it too, overflow:hidden
on the column without a width is the key to getting it to contain, vertically, as in not wrap around the side columns (can be left or right)
IE6 might need zoom:1
set on the #content div too if you need it's support
ActiveModel::Dirty
didn't work for me because the @model.update_attributes()
hid the changes. So this is how I detected changes it in an update
method in a controller:
def update
@model = Model.find(params[:id])
detect_changes
if @model.update_attributes(params[:model])
do_stuff if attr_changed?
end
end
private
def detect_changes
@changed = []
@changed << :attr if @model.attr != params[:model][:attr]
end
def attr_changed?
@changed.include :attr
end
If you're trying to detect a lot of attribute changes it could get messy though. Probably shouldn't do this in a controller, but meh.
I don't think you can use "exists" on an integer in Perl, only on collections. Can you give an example of what you mean in Perl which matches your example in Java.
Given an expression that specifies a hash element or array element, returns true if the specified element in the hash or array has ever been initialized, even if the corresponding value is undefined.
This indicates it only applies to hash or array elements!
This is how to get the last record from all MongoDB documents from the "foo" collection.(change foo,x,y.. etc.)
db.foo.aggregate([{$sort:{ x : 1, date : 1 } },{$group: { _id: "$x" ,y: {$last:"$y"},yz: {$last:"$yz"},date: { $last : "$date" }}} ],{ allowDiskUse:true })
you can add or remove from the group
help articles: https://docs.mongodb.com/manual/reference/operator/aggregation/group/#pipe._S_group
https://docs.mongodb.com/manual/reference/operator/aggregation/last/
Normal array
can serve as a dictionary data structure. In general it has multipurpose usage: array, list (vector), hash table, dictionary, collection, stack, queue etc.
$names = [
'bob' => 27,
'billy' => 43,
'sam' => 76,
];
$names['bob'];
And because of wide design it gains no full benefits of specific data structure. You can implement your own dictionary by extending an ArrayObject
or you can use SplObjectStorage
class which is map (dictionary) implementation allowing objects to be assigned as keys.
if your pod has name like name-xxx-yyy
, it could be controlled by a replicasets.apps named name-xxx
, you should delete that replicaset first before deleting the pod
kubectl delete replicasets.apps name-xxx
"File -> Invalidate Cache and Restart" will resolve all dependencies.
This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.
Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.
$param = isset($_GET['param']) ? $_GET['param'] : 'default';
There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:
$result = $x ?: 'default';
It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset
or a null coalescing operator which is introduced in PHP7:
$param = $_GET['param'] ?? 'default';
1.mysql_set_charset('utf8');
// set this line on top of your page in which you are using json.
latin1_swedish_ci
". Here's a batch file, called base64encode.bat, that encodes base64.
@echo off
if not "%1" == "" goto :arg1exists
echo usage: base64encode input-file [output-file]
goto :eof
:arg1exists
set base64out=%2
if "%base64out%" == "" set base64out=con
(
set base64tmp=base64.tmp
certutil -encode "%1" %base64tmp% > nul
findstr /v /c:- %base64tmp%
erase %base64tmp%
) > %base64out%
You could use pandas.
Here is an example with a list:
In: import pandas as P
In: P.set_option('display.precision',3)
In: L = [3.4534534, 2.1232131, 6.231212, 6.3423423, 9.342342423]
In: P.Series(data=L)
Out:
0 3.45
1 2.12
2 6.23
3 6.34
4 9.34
dtype: float64
If you have a dict d, and you want its keys as rows:
In: d
Out: {1: 0.453523, 2: 2.35423234234, 3: 3.423432432, 4: 4.132312312}
In: P.DataFrame(index=d.keys(), data=d.values())
Out:
0
1 0.45
2 2.35
3 3.42
4 4.13
And another way of giving dict to a DataFrame:
P.DataFrame.from_dict(d, orient='index')
Try:
For Mac users, you only need to use the fn key if the setting "Use all F1, F2 etc. keys as function keys" (under System Preferences -> Keyboard) is checked.
Good example without custom validate methods, but with metadata plugin and some extra html.
There must be a user in the AllowUsers section, in the config file /etc/ssh/ssh_config, in the remote machine. You might have to restart sshd after editing the config file.
And then you can copy for example the file "test.txt" from a remote host to the local host
scp [email protected]:test.txt /local/dir
@cool_cs you can user ~ symbol ~/Users/djorge/Desktop if it's your home dir.
In UNIX, absolute paths must start with '/'.
Maybe your changes are not lost. Check "git reflog"
I quote the article below:
"Basically every action you perform inside of Git where data is stored, you can find it inside of the reflog. Git tries really hard not to lose your data, so if for some reason you think it has, chances are you can dig it out using git reflog"
See details:
http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html
Yes you can handle with the catch operator like this and show alert as you want but firstly you have to import Rxjs
for the same like this way
import {Observable} from 'rxjs/Rx';
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status === 500) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 400) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 409) {
return Observable.throw(new Error(error.status));
}
else if (error.status === 406) {
return Observable.throw(new Error(error.status));
}
});
}
also you can handel error (with err block) that is throw by catch block while .map
function,
like this -
...
.subscribe(res=>{....}
err => {//handel here});
as required for any status without checking particluar one you can try this: -
return this.http.request(new Request(this.requestoptions))
.map((res: Response) => {
if (res) {
if (res.status === 201) {
return [{ status: res.status, json: res }]
}
else if (res.status === 200) {
return [{ status: res.status, json: res }]
}
}
}).catch((error: any) => {
if (error.status < 400 || error.status ===500) {
return Observable.throw(new Error(error.status));
}
})
.subscribe(res => {...},
err => {console.log(err)} );
Call and apply both are used to force the this
value when a function is executed. The only difference is that call
takes n+1
arguments where 1 is this
and 'n' arguments
. apply
takes only two arguments, one is this
the other is argument array.
The advantage I see in apply
over call
is that we can easily delegate a function call to other function without much effort;
function sayHello() {
console.log(this, arguments);
}
function hello() {
sayHello.apply(this, arguments);
}
var obj = {name: 'my name'}
hello.call(obj, 'some', 'arguments');
Observe how easily we delegated hello
to sayHello
using apply
, but with call
this is very difficult to achieve.
There's a very simple hack that fixes this issue
Here's a codesandbox that illustrates the solution: https://codesandbox.io/s/00w06z1n5l
HTML
<div id="parent">
<div class="hack">
<div class="child">
</div>
</div>
</div>
CSS
.parent { position: relative; width: 100%; }
.hack { position: absolute; left:0; right:0; top:0;}
.child { position: absolute; left: 0; right: 0; bottom:0; }
you can play with the positioning of the hack div to affect where the child positions itself.
Here's a snippet:
html {_x000D_
font-family: sans-serif;_x000D_
text-align: center;_x000D_
}_x000D_
_x000D_
.container {_x000D_
border: 2px solid gray;_x000D_
height: 400px;_x000D_
display: flex;_x000D_
flex-direction: column;_x000D_
}_x000D_
_x000D_
.stuff-the-middle {_x000D_
background: papayawhip_x000D_
url("https://camo.githubusercontent.com/6609e7239d46222bbcbd846155351a8ce06eb11f/687474703a2f2f692e696d6775722e636f6d2f4e577a764a6d6d2e706e67");_x000D_
flex: 1;_x000D_
}_x000D_
_x000D_
.parent {_x000D_
background: palevioletred;_x000D_
position: relative;_x000D_
}_x000D_
_x000D_
.hack {_x000D_
position: absolute;_x000D_
left: 0;_x000D_
top:0;_x000D_
right: 0;_x000D_
}_x000D_
.child {_x000D_
height: 40px;_x000D_
background: rgba(0, 0, 0, 0.5);_x000D_
position: absolute;_x000D_
bottom: 0;_x000D_
left: 0;_x000D_
right: 0;_x000D_
}
_x000D_
<div class="container">_x000D_
<div class="stuff-the-middle">_x000D_
I have stuff annoyingly in th emiddle_x000D_
</div>_x000D_
<div class="parent">_x000D_
<div class="hack">_x000D_
<div class="child">_x000D_
I'm inside of my parent but absolutely on top_x000D_
</div>_x000D_
</div>_x000D_
I'm the parent_x000D_
<br /> You can modify my height_x000D_
<br /> and my child is always on top_x000D_
<br /> absolutely on top_x000D_
<br /> try removing this text_x000D_
</div>_x000D_
</div>
_x000D_
For military time formatting,
select TO_CHAR(SYSDATE, 'yyyy-mm-dd hh24:mm:ss') from DUAL
--2018-07-10 15:07:15
If you want your date to round DOWN to Month, Day, Hour, Minute, you can try
SELECT TO_CHAR( SYSDATE, 'yyyy-mm-dd hh24:mi:ss') "full-date" --2018-07-11 10:40:26
, TO_CHAR( TRUNC(SYSDATE, 'year'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-year"-- 2018-01-01 00:00:00
, TO_CHAR( TRUNC(SYSDATE, 'month'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-month" -- 2018-07-01 00:00:00
, TO_CHAR( TRUNC(SYSDATE, 'day'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-Sunday" -- 2018-07-08 00:00:00
, TO_CHAR( TRUNC(SYSDATE, 'dd'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-day" -- 2018-07-11 00:00:00
, TO_CHAR( TRUNC(SYSDATE, 'hh'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-hour" -- 2018-07-11 10:00:00
, TO_CHAR( TRUNC(SYSDATE, 'mi'), 'yyyy-mm-dd hh24:mi:ss') "trunc-to-minute" -- 2018-07-11 10:40:00
from DUAL
For formats literals, you can find help in https://docs.oracle.com/cd/B28359_01/server.111/b28286/functions242.htm#SQLRF52037
CREATE TABLE fractest( c1 TIME(3), c2 DATETIME(3), c3 TIMESTAMP(3) );
INSERT INTO fractest VALUES
('17:51:04.777', '2018-09-08 17:51:04.777', '2018-09-08 17:51:04.777');
You only need to do
pg_ctl register
then execute servcies.msc
enable the "PostgresSQL" and set to auto
then, your postgresql will run like the "server".
<select name="select_box" multiple>
<option>123</option>
<option>456</option>
<option>789</option>
</select>
I would suggest doing this in a more functional style :P
function CreateMessageboard(BoardMessages) {
var htmlMessageboardString = BoardMessages
.map(function(BoardMessage) {
return MessageToHTMLString(BoardMessage);
})
.join('');
}
Try this
I guess this is essentially putting it in a string, but this avoids the rounding error:
import decimal
def display(x):
digits = 15
temp = str(decimal.Decimal(str(x) + '0' * digits))
return temp[:temp.find('.') + digits + 1]
You can use distutils.dir_util.copy_tree
. It works just fine and you don't have to pass every argument, only src
and dst
are mandatory.
However in your case you can't use a similar tool likeshutil.copytree
because it behaves differently: as the destination directory must not exist this function can't be used for overwriting its contents.
If you want to use the cp
tool as suggested in the question comments beware that using the subprocess
module is currently the recommended way for spawning new processes as you can see in the documentation of the os.system function.
Or you can trigger a custom event when one function completes, then bind it to the document:
function a() {
// first function code here
$(document).trigger('function_a_complete');
}
function b() {
// second function code here
}
$(document).bind('function_a_complete', b);
Using this method, function 'b' can only execute AFTER function 'a', as the trigger only exists when function a is finished executing.
Section 3 of RFC4122 provides the formal definition of UUID string representations. It's 36 characters (32 hex digits + 4 dashes).
Sounds like you need to figure out where the invalid 60-char IDs are coming from and decide 1) if you want to accept them, and 2) what the max length of those IDs might be based on whatever API is used to generate them.
A. If you use maven, an useful way to debug clashing jars is:
mvn dependency:tree
For example, for an exception:
java.lang.SecurityException: class "javax.servlet.HttpConstraintElement"'s signer information does not match signer information of other classes in the same package
we do:
mvn dependency:tree|grep servlet
Its output:
[INFO] +- javax.servlet:servlet-api:jar:2.5:compile
[INFO] +- javax.servlet:jstl:jar:1.2:compile
[INFO] | +- org.eclipse.jetty.orbit:javax.servlet.jsp:jar:2.2.0.v201112011158:compile
[INFO] | +- org.eclipse.jetty.orbit:javax.servlet.jsp.jstl:jar:1.2.0.v201105211821:compile
[INFO] | +- org.eclipse.jetty.orbit:javax.servlet:jar:3.0.0.v201112011016:compile
[INFO] +- org.eclipse.jetty:jetty-servlet:jar:9.0.0.RC2:compile
shows clashing servlet-api 2.5 and javax.servlet 3.0.0.x.
B. Other useful hints (how to debug the security exception and how to exclude maven deps) are at the question at Signer information does not match.
All three way you can use for newline character :
'\n'
"\n"
"""\n"""
If you are using MS Excel 2003 then go to view->Tool bar->Pivot Table From this tool bar we can do refresh by clicking ! this symbol.
JavascriptExecutor is best to scroll down a web page
window.scrollTo
Function in JavascriptExecutor can do this
JavascriptExecutor js = ((JavascriptExecutor) driver);
js.executeScript("window.scrollTo(0,100");
Above code will scroll down by 100 y coordinates
I have the same problem right now but this article helps me. Updates for the year 2020!
I got the solution from this article:
https://dev.to/imamcu07/embed-or-display-image-to-html-page-from-google-drive-3ign
These are the steps from the article:
After Replace ID: https://drive.google.com/thumbnail?id=14hz3ySPn-zBd4Tu3NtY1F05LSGdFfWvp
<img>
tag.And now it should work.
You can always try this:
/home/user/anaconda3/bin/pip install -r requirements.txt
This simply uses the pip installed in the conda environment. If pip is not preinstalled in your environment you can always run the following command
conda install pip
Cleaned up what chuycepeda has and put it into a textarea to send back in a form.
google.maps.event.addListener(drawingManager, 'overlaycomplete', function (event) {
var str_input = '{';
if (event.type == google.maps.drawing.OverlayType.POLYGON) {
$.each(event.overlay.getPath().getArray(), function (key, latlng) {
var lat = latlng.lat();
var lon = latlng.lng();
str_input += lat + ', ' + lon + ',';
});
}
str_input = str_input.substr(0, str_input.length - 1) + '}';
$('textarea#Geofence').val(str_input);
});
In this case, you could use life
to reference the parent object. Or you could store a reference to life
in the users object. There can't be a fixed parent
available to you in the language, because users is just a reference to an object, and there could be other references...
var death = { residents : life.users };
life.users.smallFurryCreaturesFromAlphaCentauri = { exist : function() {} };
// death.residents.smallFurryCreaturesFromAlphaCentauri now exists
// - because life.users references the same object as death.residents!
You might find it helpful to use something like this:
function addChild(ob, childName, childOb)
{
ob[childName] = childOb;
childOb.parent = ob;
}
var life= {
mameAndDestroy : function(group){ },
kiss : function(group){ }
};
addChild(life, 'users', {
guys : function(){ this.parent.mameAndDestroy(this.girls); },
girls : function(){ this.parent.kiss(this.boys); },
});
// life.users.parent now exists and points to life
If you want to use a color from colors.xml , experiment :
public View getView(int position, View convertView, ViewGroup parent) {
...
View rowView = inflater.inflate(this.rowLayoutID, parent, false);
rowView.setBackgroundColor(rowView.getResources().getColor(R.color.my_bg_color));
TextView title = (TextView) rowView.findViewById(R.id.txtRowTitle);
title.setTextColor(
rowView.getResources().getColor(R.color.my_title_color));
...
}
You can use too:
private static final int bgColor = 0xAAAAFFFF;
public View getView(int position, View convertView, ViewGroup parent) {
...
View rowView = inflater.inflate(this.rowLayoutID, parent, false);
rowView.setBackgroundColor(bgColor);
...
}
I have a project where one file in src/
imports another file in the same directory. To get PyCharm to recognize I had to to go to File > Settings > Project > Project Structure > select src
folder and click "Mark as: Sources"
From https://www.jetbrains.com/help/pycharm/configuring-folders-within-a-content-root.html
Source roots contain the actual source files and resources. PyCharm uses the source roots as the starting point for resolving imports
My tests just seems so tightly bound to the method (testing all codepath, expecting some inner methods to be called a number of times, with certain arguments), that it seems that if I ever refactor the method, the tests will fail even if the final behavior of the method did not change.
I think you are doing it wrong.
A unit test should:
It should not look inside the method to see what it is doing, so changing the internals should not cause the test to fail. You should not directly test that private methods are being called. If you are interested in finding out whether your private code is being tested then use a code coverage tool. But don't get obsessed by this: 100% coverage is not a requirement.
If your method calls public methods in other classes, and these calls are guaranteed by your interface, then you can test that these calls are being made by using a mocking framework.
You should not use the method itself (or any of the internal code it uses) to generate the expected result dynamically. The expected result should be hard-coded into your test case so that it does not change when the implementation changes. Here's a simplified example of what a unit test should do:
testAdd()
{
int x = 5;
int y = -2;
int expectedResult = 3;
Calculator calculator = new Calculator();
int actualResult = calculator.Add(x, y);
Assert.AreEqual(expectedResult, actualResult);
}
Note that how the result is calculated is not checked - only that the result is correct. Keep adding more and more simple test cases like the above until you have have covered as many scenarios as possible. Use your code coverage tool to see if you have missed any interesting paths.
Eloquent has a method for that (Laravel 4.*/5.*);
Model::whereNotNull('sent_at')
Laravel 3:
Model::where_not_null('sent_at')
I added below settings in application.yml and worked fine.
security:
route-patterns-to-be-skipped:
- /**/*
this can be converted as security.route-paterns-to-be-skipped=/**/*
for application.properties
Using the title attribute:
<div id="sub1 sub2 sub3" title="some text on mouse over">some text</div>
Please note that for the sake of simplicity I have made reference to only the first code snippet i.e.,
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
protected void onCreate(Bundle savedValues) {
...
// Capture our button from layout
Button button = (Button)findViewById(R.id.corky);
// Register the onClick listener with the implementation above
button.setOnClickListener(mCorkyListener);
...
}
setOnClickListener(View.OnClickListener l)
is a public method of View class. Button class extends the View class and can therefore call setOnClickListener(View.OnClickListener l)
method.
setOnClickListener registers a callback to be invoked when the view (button in your case) is clicked. This answers should answer your first two questions:
1. Where does setOnClickListener
fit in the above logic?
Ans. It registers a callback when the button is clicked. (Explained in detail in the next paragraph).
2. Which one actually listens to the button click?
Ans. setOnClickListener
method is the one that actually listens to the button click.
When I say it registers a callback to be invoked, what I mean is it will run the View.OnClickListener l
that is the input parameter for the method. In your case, it will be mCorkyListener
mentioned in button.setOnClickListener(mCorkyListener);
which will then execute the method onClick(View v)
mentioned within
// Create an anonymous implementation of OnClickListener
private OnClickListener mCorkyListener = new OnClickListener() {
public void onClick(View v) {
// do something when the button is clicked
}
};
Moving on further, OnClickListener
is an Interface definition for a callback to be invoked when a view (button in your case) is clicked. Simply saying, when you click that button, the methods within mCorkyListener
(because it is an implementation of OnClickListener
) are executed. But, OnClickListener
has just one method which is OnClick(View v)
. Therefore, whatever action that needs to be performed on clicking the button must be coded within this method.
Now that you know what setOnClickListener
and OnClickListener
mean, I'm sure you'll be able to differentiate between the two yourself. The third term View.OnClickListener
is actually OnClickListener
itself. The only reason you have View.
preceding it is because of the difference in the import
statment in the beginning of the program. If you have only import android.view.View;
as the import statement you will have to use View.OnClickListener
. If you mention either of these import statements:
import android.view.View.*;
or import android.view.View.OnClickListener;
you can skip the View.
and simply use OnClickListener
.
The dict.items
iterates over the key-value pairs of a dictionary. Therefore for key, value in dictionary.items()
will loop over each pair. This is documented information and you can check it out in the official web page, or even easier, open a python console and type help(dict.items)
. And now, just as an example:
>>> d = {'hello': 34, 'world': 2999}
>>> for key, value in d.items():
... print key, value
...
world 2999
hello 34
The AttributeError
is an exception thrown when an object does not have the attribute you tried to access. The class dict
does not have any predictors
attribute (now you know where to check it :) ), and therefore it complains when you try to access it. As easy as that.
At the time of writing, there was a bug in chrome which required an xmlns
attribute in order to trigger rendering:
<xsl:stylesheet xmlns="http://www.w3.org/1999/xhtml" ... >
This was the problem I was running into when serving the xml file from a server.
If unlike me, you are viewing the xml file from a file:///
url, then the solutions mentioning --allow-file-access-from-files
are the ones you want
This is a sample code I used to counter the problem.
\begin{frame}{Topic 1}
Topic of the figures
\begin{figure}
\captionsetup[subfloat]{position=top,labelformat=empty}
\only<1>{\subfloat[Fig. 1]{\includegraphics{figure1.jpg}}}
\only<2>{\subfloat[Fig. 2]{\includegraphics{figure2.jpg}}}
\only<3>{\subfloat[Fig. 3]{\includegraphics{figure3.jpg}}}
\end{figure}
\end{frame}
If PowerShell is available, the Send-MailMessage commandlet is a single one-line command that could easily be called from a batch file to handle email notifications. Below is a sample of the line you would include in your batch file to call the PowerShell script (the %xVariable%
is a variable you might want to pass from your batch file to the PowerShell script):
--[BATCH FILE]--
:: ...your code here...
C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe -windowstyle hidden -command C:\MyScripts\EmailScript.ps1 %xVariable%
Below is an example of what you might include in your PowerShell script (you must include the PARAM line as the first non-remark line in your script if you included passing the %xVariable%
from your batch file:
--[POWERSHELL SCRIPT]--
Param([String]$xVariable)
# ...your code here...
$smtp = "smtp.[emaildomain].com"
$to = "[Send to email address]"
$from = "[From email address]"
$subject = "[Subject]"
$body = "[Text you want to include----the <br> is a line feed: <br> <br>]"
$body += "[This could be a second line of text]" + "<br> "
$attachment="[file name if you would like to include an attachment]"
send-MailMessage -SmtpServer $smtp -To $to -From $from -Subject $subject -Body $body -BodyAsHtml -Attachment $attachment -Priority high
There are two ways:
I had encountered this same need, and I used a combination of Linq's Skip() and Take() methods. I multiply the number I take by the number of iterations this far, and that gives me the number of items to skip, then I take the next group.
var categories = Properties.Settings.Default.MovementStatsCategories;
var items = summariesWithinYear
.Select(s => s.sku).Distinct().ToList();
//need to run by chunks of 10,000
var count = items.Count;
var counter = 0;
var numToTake = 10000;
while (count > 0)
{
var itemsChunk = items.Skip(numToTake * counter).Take(numToTake).ToList();
counter += 1;
MovementHistoryUtilities.RecordMovementHistoryStatsBulk(itemsChunk, categories, nLogger);
count -= numToTake;
}
In order to move a View anywhere on the screen, I would recommend placing it in a full screen layout. By doing so, you won't have to worry about clippings or relative coordinates.
You can try this sample code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:id="@+id/rootLayout">
<Button
android:id="@+id/btn1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="MOVE" android:layout_centerHorizontal="true"/>
<ImageView
android:id="@+id/img1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="10dip"/>
<ImageView
android:id="@+id/img2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_centerVertical="true" android:layout_alignParentRight="true"/>
<ImageView
android:id="@+id/img3"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_alignParentBottom="true" android:layout_marginBottom="100dip"/>
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" android:clipChildren="false" android:clipToPadding="false">
<ImageView
android:id="@+id/img4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/ic_launcher" android:layout_marginLeft="60dip" android:layout_marginTop="150dip"/>
</LinearLayout>
</RelativeLayout>
Your activity
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
((Button) findViewById( R.id.btn1 )).setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
ImageView img = (ImageView) findViewById( R.id.img1 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img2 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img3 );
moveViewToScreenCenter( img );
img = (ImageView) findViewById( R.id.img4 );
moveViewToScreenCenter( img );
}
});
}
private void moveViewToScreenCenter( View view )
{
RelativeLayout root = (RelativeLayout) findViewById( R.id.rootLayout );
DisplayMetrics dm = new DisplayMetrics();
this.getWindowManager().getDefaultDisplay().getMetrics( dm );
int statusBarOffset = dm.heightPixels - root.getMeasuredHeight();
int originalPos[] = new int[2];
view.getLocationOnScreen( originalPos );
int xDest = dm.widthPixels/2;
xDest -= (view.getMeasuredWidth()/2);
int yDest = dm.heightPixels/2 - (view.getMeasuredHeight()/2) - statusBarOffset;
TranslateAnimation anim = new TranslateAnimation( 0, xDest - originalPos[0] , 0, yDest - originalPos[1] );
anim.setDuration(1000);
anim.setFillAfter( true );
view.startAnimation(anim);
}
The method moveViewToScreenCenter
gets the View's absolute coordinates and calculates how much distance has to move from its current position to reach the center of the screen. The statusBarOffset
variable measures the status bar height.
I hope you can keep going with this example. Remember that after the animation your view's position is still the initial one. If you tap the MOVE button again and again the same movement will repeat. If you want to change your view's position do it after the animation is finished.
Why do you need to state both
x
andy
before the:
?
Because it's a function definition and it needs to know what parameters the function accepts, and in what order. It can't just look at the expression and use the variables names in that, because some of those names you might want to use existing local or global variable values for, and even if it did that, it wouldn't know what order it should expect to get them.
Your error message means that Tk is calling your lambda with one argument, while your lambda is written to accept no arguments. If you don't need the argument, just accept one and don't use it. (Demosthenex has the code, I would have posted it but was beaten to it.)
Another way to restore the menu bar is to trigger the View: Toggle Menu Bar
command in the command palette (F1).
When you install Python, it will not overwrite other installs of other major versions. So installing Python 2.5.x will not overwrite Python 2.6.x, although installing 2.6.6 will overwrite 2.6.5.
So you can just install it. Then you call the Python version you want. For example:
C:\Python2.5\Python.exe
for Python 2.5 on windows and
C:\Python2.6\Python.exe
for Python 2.6 on windows, or
/usr/local/bin/python-2.5
or
/usr/local/bin/python-2.6
on Windows Unix (including Linux and OS X).
When you install on Unix (including Linux and OS X) you will get a generic python
command installed, which will be the last one you installed. This is mostly not a problem as most scripts will explicitly call /usr/local/bin/python2.5 or something just to protect against that. But if you don't want to do that, and you probably don't you can install it like this:
./configure
make
sudo make altinstall
Note the "altinstall" that means it will install it, but it will not replace the python
command.
On Windows you don't get a global python
command as far as I know so that's not an issue.
Some folk dislike this approach because of an "inappropriate" use of error handling, but I think it's considered acceptable in VBA... An alternative approach is to loop though all the sheets until you find a match.
Function WorksheetExists(shtName As String, Optional wb As Workbook) As Boolean
Dim sht As Worksheet
If wb Is Nothing Then Set wb = ThisWorkbook
On Error Resume Next
Set sht = wb.Sheets(shtName)
On Error GoTo 0
WorksheetExists = Not sht Is Nothing
End Function
Basically, pip comes with python itself.Therefore it carries no meaning for using pip itself to install or upgrade python. Thus,try to install python through installer itself,visit the site "https://www.python.org/downloads/" for more help. Thank you.
Prevent saving changes that require table re-creation
Five swift clicks
- Tools
- Options
- Designers
- Prevent saving changes that require table re-creation
- OK.
After saving, repeat the proceudure to re-tick the box. This safe-guards against accidental data loss.
Further explanation
By default SQL Server Management Studio prevents the dropping of tables, because when a table is dropped its data contents are lost.*
When altering a column's datatype in the table Design view, when saving the changes the database drops the table internally and then re-creates a new one.
*Your specific circumstances will not pose a consequence since your table is empty. I provide this explanation entirely to improve your understanding of the procedure.
Well, here the positioning of the css and script links makes a to of difference. Bootstrap executes in CSS and then Scripts fashion. So if you have even one script written at incorrect place it makes a lot of difference. You can follow the below snippet and change your code accordingly.
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
<meta charset="utf-8">_x000D_
<meta name="viewport" content="width=device-width, initial-scale=1">_x000D_
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<!-- <link rel="stylesheet" type="text/css" href="css/bootstrap-datetimepicker.css"> -->_x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.15.1/moment.min.js"></script>_x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker.min.css"> _x000D_
<link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/css/bootstrap-datetimepicker-standalone.css"> _x000D_
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.43/js/bootstrap-datetimepicker.min.js"></script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<div class="container">_x000D_
<div class="row">_x000D_
<div class='col-sm-6'>_x000D_
<div class="form-group">_x000D_
<div class='input-group date' id='datetimepicker1'>_x000D_
<input type='text' class="form-control" />_x000D_
<span class="input-group-addon">_x000D_
<span class="glyphicon glyphicon-calendar"></span>_x000D_
</span>_x000D_
</div>_x000D_
</div>_x000D_
</div>_x000D_
<script type="text/javascript">_x000D_
$(function () {_x000D_
$('#datetimepicker1').datetimepicker();_x000D_
});_x000D_
</script>_x000D_
</div>_x000D_
</div>_x000D_
</body>_x000D_
</html>
_x000D_
Try this:
onclick="myfunction(
'/myController/myAction',
function(){myfuncionOnOK('/myController2/myAction2','myParameter2');},
function(){myfuncionOnCancel('/myController3/myAction3','myParameter3');}
);"
Then you just need to call these two functions passed to myfunction
:
function myfunction(url, f1, f2) {
// …
f1();
f2();
}
In a special case within ASP.NET If you want to know if the page is redirected by a specified .aspx page and not another one, just put the information in a session name and take necessary action in the receiving Page_Load Event.
the method modify()
that you called in the last is called in global context
if you want to override modify()
you first have to inherit A
or B
.
Maybe you're trying to do this:
In this case C
inherits A
function A() {
this.modify = function() {
alert("in A");
}
}
function B() {
this.modify = function() {
alert("in B");
}
}
C = function() {
this.modify = function() {
alert("in C");
};
C.prototype.modify(); // you can call this method where you need to call modify of the parent class
}
C.prototype = new A();
Installing psqlODBC on 64bit Windows
Though you can install 32 bit ODBC drivers on Win X64 as usual, you can't configure 32-bit DSNs via ordinary control panel or ODBC datasource administrator.
How to configure 32 bit ODBC drivers on Win x64
Configure ODBC DSN from %SystemRoot%\syswow64\odbcad32.exe
%SystemRoot%\syswow64\odbcad32.exe
You may have to play with it and try different scenarios, think outside-the-box, remember this is open source.
I liked paxdiablo's script, but wanted a version that ran indefinitely. This version runs ping until a connection is established and then prints a message saying so.
echo "Testing..."
PING_CMD="ping -t 3 -c 1 google.com > /dev/null 2>&1"
eval $PING_CMD
if [[ $? -eq 0 ]]; then
echo "Already connected."
else
echo -n "Waiting for connection..."
while true; do
eval $PING_CMD
if [[ $? -eq 0 ]]; then
echo
echo Connected.
break
else
sleep 0.5
echo -n .
fi
done
fi
I also have a Gist of this script which I'll update with fixes and improvements as needed.
try this one
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_gravity="right"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<TextView
android:id="@+id/lblExpenseCancel"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="10dp"
android:layout_marginTop="9dp"
android:text="cancel"
android:textColor="#ffff0000"
android:textSize="20sp" />
<Button
android:id="@+id/btnAddExpense"
android:layout_width="wrap_content"
android:layout_height="45dp"
android:layout_alignParentRight="true"
android:layout_marginLeft="10dp"
android:layout_marginRight="15dp"
android:textColor="#ff0000ff"
android:text="add" />
</RelativeLayout>
</LinearLayout>
HTML tags vs. elements vs. attributes
HTML elements
An element in HTML represents some kind of structure or semantics and generally consists of a start tag, content, and an end tag. The following is a paragraph element:
<p> This is the content of the paragraph element. </p>
HTML tags
Tags are used to mark up the start and end of an HTML element.
<p></p>
HTML attributes
An attribute defines a property for an element, consists of an attribute/value pair, and appears within the element’s start tag. An element’s start tag may contain any number of space separated attribute/value pairs.
The most popular misuse of the term “tag” is referring to alt attributes as “alt tags”. There is no such thing in HTML. Alt is an attribute, not a tag.
<img src="foobar.gif" alt="A foo can be balanced on a bar by placing its fubar on the bar's foobar.">
Source: 456bereastreet.com: HTML tags vs. elements vs. attributes
Ok, the question seems to have been answered fairly well, the UNICODE overload should take a wide character array as its second parameter. So if the command line parameter is "Hello"
that would probably end up as "H\0e\0l\0l\0o\0\0\0"
and your program would only print the 'H'
before it sees what it thinks is a null terminator.
So now you may wonder why it even compiles and links.
Well it compiles because you are allowed to define an overload to a function.
Linking is a slightly more complex issue. In C, there is no decorated symbol information so it just finds a function called main. The argc and argv are probably always there as call-stack parameters just in case even if your function is defined with that signature, even if your function happens to ignore them.
Even though C++ does have decorated symbols, it almost certainly uses C-linkage for main, rather than a clever linker that looks for each one in turn. So it found your wmain and put the parameters onto the call-stack in case it is the int wmain(int, wchar_t*[])
version.
You don't need function overloading, as you have the *args and **kwargs arguments.
The fact is that function overloading is based on the idea that passing different types you will execute different code. If you have a dynamically typed language like Python, you should not distinguish by type, but you should deal with interfaces and their compliance with the code you write.
For example, if you have code that can handle either an integer, or a list of integers, you can try iterating on it and if you are not able to, then you assume it's an integer and go forward. Of course it could be a float, but as far as the behavior is concerned, if a float and an int appear to be the same, then they can be interchanged.
You could use the Fisher-Yates Shuffle (code adapted from this site):
function shuffle(array) {
let counter = array.length;
// While there are elements in the array
while (counter > 0) {
// Pick a random index
let index = Math.floor(Math.random() * counter);
// Decrease counter by 1
counter--;
// And swap the last element with it
let temp = array[counter];
array[counter] = array[index];
array[index] = temp;
}
return array;
}
set vimdiff to ignore case
Having started vim diff with
gvim -d main.sql backup.sql &
I find that annoyingly one file has MySQL keywords in lowercase the other uppercase showing differences on practically every other line
:set diffopt+=icase
this updates the screen dynamically & you can just as easily switch it off again
You can also use the undocumented sp_MSforeachtable stored procedure as such if you are looking to do this for every table:
sp_MSforeachtable @command1 ="PRINT 'TABLE NAME: ' + '?' DECLARE @RowCount INT SET @RowCount = (SELECT COUNT(*) FROM ?) PRINT @RowCount"
I don't know of an easy way to do that. You COULD do this:
I can edit with details if that sounds appealing.
JVM Java Virtual Machine , actually executes the java bytecode. It is the execution block on the JAVA platform. It converts the bytecode to the machine code.
JRE Java Runtime Environment , provides the minimum requirements for executing a Java application; it consists of the Java Virtual Machine (JVM), core classes, and supporting files.
JDK Java Development Kit, it has all the tools to develop your application software. It is as JRE+JVM
Open JDK is a free and open source implementation of the Java Platform.
A list comprehension is a simple approach:
j2 = [x for x in j if x >= 5]
Alternately, you can use filter
for the exact same result:
j2 = filter(lambda x: x >= 5, j)
Note that the original list j
is unmodified.
std::unique_ptr has no copy constructor. You create an instance and then ask the std::vector to copy that instance during initialisation.
error: deleted function 'std::unique_ptr<_Tp, _Tp_Deleter>::uniqu
e_ptr(const std::unique_ptr<_Tp, _Tp_Deleter>&) [with _Tp = int, _Tp_D
eleter = std::default_delete<int>, std::unique_ptr<_Tp, _Tp_Deleter> =
std::unique_ptr<int>]'
The class satisfies the requirements of MoveConstructible and MoveAssignable, but not the requirements of either CopyConstructible or CopyAssignable.
The following works with the new emplace calls.
std::vector< std::unique_ptr< int > > vec;
vec.emplace_back( new int( 1984 ) );
See using unique_ptr with standard library containers for further reading.
Try the following code:
first = [1, 2, 3, 4]
second = [2, 3, 4, 5]
third = map(sum, zip(first, second))
This way works fine for me:
var request = new RestSharp.RestRequest("RESOURCE", RestSharp.Method.POST) { RequestFormat = RestSharp.DataFormat.Json }
.AddBody(BODY);
var response = Client.Execute(request);
// Handle response errors
HandleResponseErrors(response);
if (Errors.Length == 0)
{ }
else
{ }
Hope this helps! (Although it is a bit late)
If you want to see the array as an array, you can say
alert(JSON.stringify(aCustomers));
instead of all those document.write
s.
However, if you want to display them cleanly, one per line, in your popup, do this:
alert(aCustomers.join("\n"));
The question was:
I would like to handle errors from Guzzle when the server returns 4xx and 5xx status codes
The other answers are mostly incomplete. 404 and 500 will throw different exceptions.
Also, the question is do you just want to handle the errors or do you want to get the body? I think in most cases it would be sufficient to handle the errors and not get the message body.
I would look at the documentation to check how your version of Guzzle handles it because this may change: https://docs.guzzlephp.org/en/stable/quickstart.html#exceptions
Guzzle 7 (from the docs):
. \RuntimeException
+-- TransferException (implements GuzzleException)
+-- RequestException
+-- BadResponseException
¦ +-- ServerException
¦ +-- ClientException
+-- ConnectException
+-- TooManyRedirectsException
So, you code might look like this:
try {
$response = $client->request('GET', $url);
if ($response->getStatusCode() >= 300) {
$statusCode = $response->getStatusCode();
// handle error
} else {
// is valid URL
}
} catch (TooManyRedirectsException $e) {
// handle too many redirects
} catch (ClientException | ServerException $e) {
// ClientException - A GuzzleHttp\Exception\ClientException is thrown for 400 level errors if the http_errors request option is set to true.
// ServerException - A GuzzleHttp\Exception\ServerException is thrown for 500 level errors if the http_errors request option is set to true.
if ($e->hasResponse()) {
$statusCode = $e->getResponse()->getStatusCode();
}
} catch (ConnectException $e) {
// ConnectException - A GuzzleHttp\Exception\ConnectException exception is thrown in the event of a networking error. This may be any libcurl error, including certificate problems
$handlerContext = $e->getHandlerContext();
if ($handlerContext['errno'] ?? 0) {
// this is the libcurl error code, not the HTTP status code!!!
$errno = (int)($handlerContext['errno']);
}
} catch (\Exception $e) {
// fallback, in case of other exception
}
If you really need the body, you can retrieve it as usual:
https://docs.guzzlephp.org/en/stable/quickstart.html#using-responses
$body = $response->getBody();
Consider the following servlet conf:
<servlet>
<servlet-name>NewServlet</servlet-name>
<servlet-class>NewServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>NewServlet</servlet-name>
<url-pattern>/NewServlet/*</url-pattern>
</servlet-mapping>
Now, when I hit the URL http://localhost:8084/JSPTemp1/NewServlet/jhi
, it will invoke NewServlet
as it is mapped with the pattern described above.
Here:
getRequestURI() = /JSPTemp1/NewServlet/jhi
getPathInfo() = /jhi
We have those ones:
getPathInfo()
returns
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
getRequestURI()
returns
a String containing the part of the URL from the protocol name up to the query string
The issue here is that ng-repeat
creates its own scope, so when you do selected=$index
it creates a new a selected
property in that scope rather than altering the existing one. To fix this you have two options:
Change the selected property to a non-primitive (ie object or array, which makes javascript look up the prototype chain) then set a value on that:
$scope.selected = {value: 0};
<a ng-click="selected.value = $index">A{{$index}}</a>
or
Use the $parent
variable to access the correct property. Though less recommended as it increases coupling between scopes
<a ng-click="$parent.selected = $index">A{{$index}}</a>
Note that -lm
may not always need to be specified even if you use some C math functions.
For example, the following simple program:
#include <stdio.h>
#include <math.h>
int main() {
printf("output: %f\n", sqrt(2.0));
return 0;
}
can be compiled and run successfully with the following command:
gcc test.c -o test
Tested on gcc 7.5.0 (on Ubuntu 16.04) and gcc 4.8.0 (on CentOS 7).
The post here gives some explanations:
The math functions you call are implemented by compiler built-in functions
See also:
I had a very similar problem. It was solved by deleting gradle's cache (~/.gradle/caches on linux), which forced android studio to re download and re generate everything.
It is also very important to distinguish a SENDING multicast socket from a RECEIVING multicast socket.
I agree with all the answers above regarding RECEIVING multicast sockets. The OP noted that binding a RECEIVING socket to an interface did not help. However, it is necessary to bind a multicast SENDING socket to an interface.
For a SENDING multicast socket on a multi-homed server, it is very important to create a separate socket for each interface you want to send to. A bound SENDING socket should be created for each interface.
// This is a fix for that bug that causes Servers to pop offline/online.
// Servers will intermittently pop offline/online for 10 seconds or so.
// The bug only happens if the machine had a DHCP gateway, and the gateway is no longer accessible.
// After several minutes, the route to the DHCP gateway may timeout, at which
// point the pingponging stops.
// You need 3 machines, Client machine, server A, and server B
// Client has both ethernets connected, and both ethernets receiving CITP pings (machine A pinging to en0, machine B pinging to en1)
// Now turn off the ping from machine B (en1), but leave the network connected.
// You will notice that the machine transmitting on the interface with
// the DHCP gateway will fail sendto() with errno 'No route to host'
if ( theErr == 0 )
{
// inspired by 'ping -b' option in man page:
// -b boundif
// Bind the socket to interface boundif for sending.
struct sockaddr_in bindInterfaceAddr;
bzero(&bindInterfaceAddr, sizeof(bindInterfaceAddr));
bindInterfaceAddr.sin_len = sizeof(bindInterfaceAddr);
bindInterfaceAddr.sin_family = AF_INET;
bindInterfaceAddr.sin_addr.s_addr = htonl(interfaceipaddr);
bindInterfaceAddr.sin_port = 0; // Allow the kernel to choose a random port number by passing in 0 for the port.
theErr = bind(mSendSocketID, (struct sockaddr *)&bindInterfaceAddr, sizeof(bindInterfaceAddr));
struct sockaddr_in serverAddress;
int namelen = sizeof(serverAddress);
if (getsockname(mSendSocketID, (struct sockaddr *)&serverAddress, (socklen_t *)&namelen) < 0) {
DLogErr(@"ERROR Publishing service... getsockname err");
}
else
{
DLog( @"socket %d bind, %@ port %d", mSendSocketID, [NSString stringFromIPAddress:htonl(serverAddress.sin_addr.s_addr)], htons(serverAddress.sin_port) );
}
Without this fix, multicast sending will intermittently get sendto() errno 'No route to host'. If anyone can shed light on why unplugging a DHCP gateway causes Mac OS X multicast SENDING sockets to get confused, I would love to hear it.
You could do something like this also:
ol {
font-weight: bold;
}
ol > li > * {
font-weight: normal;
}
So you have no "style" attributes in your HTML
You can do this easily by adding a Timer to your form (from the designer) and setting it's Tick-function to run your isonline-function.
I think it is so it can keep consistency with the available options used when settings multiple css styles in one function call through the use of an object, for example...
$(".element").css( { marginLeft : "200px", marginRight : "200px" } );
as you can see the property are not specified as strings. JQuery also supports using string if you still wanted to use the dash, or for properties that perhaps cannot be set without the dash, so the following still works...
$(".element").css( { "margin-left" : "200px", "margin-right" : "200px" } );
without the quotes here, the javascript would not parse correctly as property names cannot have a dash in them.
EDIT: It would appear that JQuery is not actually making the distinction itsleft, instead it is just passing the property specified for the DOM to care about, most likely with style[propertyName];
How to delete a non empty folder using unlinkat() in c?
Here is my work on it:
/*
* Program to erase the files/subfolders in a directory given as an input
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <dirent.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
void remove_dir_content(const char *path)
{
struct dirent *de;
char fname[300];
DIR *dr = opendir(path);
if(dr == NULL)
{
printf("No file or directory found\n");
return;
}
while((de = readdir(dr)) != NULL)
{
int ret = -1;
struct stat statbuf;
sprintf(fname,"%s/%s",path,de->d_name);
if (!strcmp(de->d_name, ".") || !strcmp(de->d_name, ".."))
continue;
if(!stat(fname, &statbuf))
{
if(S_ISDIR(statbuf.st_mode))
{
printf("Is dir: %s\n",fname);
printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
if(ret != 0)
{
remove_dir_content(fname);
printf("Err: %d\n",ret = unlinkat(dirfd(dr),fname,AT_REMOVEDIR));
}
}
else
{
printf("Is file: %s\n",fname);
printf("Err: %d\n",unlink(fname));
}
}
}
closedir(dr);
}
void main()
{
char str[10],str1[20] = "../",fname[300]; // Use str,str1 as your directory path where it's files & subfolders will be deleted.
printf("Enter the dirctory name: ");
scanf("%s",str);
strcat(str1,str);
printf("str1: %s\n",str1);
remove_dir_content(str1); //str1 indicates the directory path
}
DataFrame.to_dict()
converts DataFrame to dictionary.
Example
>>> df = pd.DataFrame(
{'col1': [1, 2], 'col2': [0.5, 0.75]}, index=['a', 'b'])
>>> df
col1 col2
a 1 0.1
b 2 0.2
>>> df.to_dict()
{'col1': {'a': 1, 'b': 2}, 'col2': {'a': 0.5, 'b': 0.75}}
See this Documentation for details
You can simply traverse through the object and return if a match is found.
Here is the code:
returnKeyforValue : function() {
var JsonObj= { "one":1, "two":2, "three":3, "four":4, "five":5 };
for (key in JsonObj) {
if(JsonObj[key] === "Keyvalue") {
return key;
}
}
}
I'd like to clarify one small gotcha here. You must use CustomVideoMode1 before CustomVideoMode2, etc. VirtualBox recognizes these modes in order starting from 1 and if you skip a number, it will not recognize anything at or beyond the number you skipped. This caught me by surprise.
From the LESS website:
If you want to import a CSS file, and don’t want LESS to process it, just use the .css extension:
@import "lib.css"; The directive will just be left as is, and end up in the CSS output.
As jitbit points out in the comments below, this is really only useful for development purposes, as you wouldn't want to have unnecessary @import
s consuming precious bandwidth.
In swift 3.0 Reading from Plist.
func readPropertyList() {
var propertyListFormat = PropertyListSerialization.PropertyListFormat.xml //Format of the Property List.
var plistData: [String: AnyObject] = [:] //Our data
let plistPath: String? = Bundle.main.path(forResource: "data", ofType: "plist")! //the path of the data
let plistXML = FileManager.default.contents(atPath: plistPath!)!
do {//convert the data to a dictionary and handle errors.
plistData = try PropertyListSerialization.propertyList(from: plistXML, options: .mutableContainersAndLeaves, format: &propertyListFormat) as! [String:AnyObject]
} catch {
print("Error reading plist: \(error), format: \(propertyListFormat)")
}
}
Read More HOW TO USE PROPERTY LISTS (.PLIST) IN SWIFT.
Take a look at the write.csv
or the write.table
functions. You just have to supply the file name the user selects to the file
parameter, and the dataframe to the x
parameter:
write.csv(x=df, file="myFileName")
Even though I realise this is an old question, I'd like to suggest using the traceback
module to handle output of the exceptions.
Use traceback.print_exc()
to print the current exception to standard error, just like it would be printed if it remained uncaught, or traceback.format_exc()
to get the same output as a string. You can pass various arguments to either of those functions if you want to limit the output, or redirect the printing to a file-like object.
A more advanced application for that you can find here: CodePlex - ApiChange
Examples:
C:\Downloads\ApiChange>ApiChange.exe -CorFlags c:\Windows\winhlp32.exe
File Name; Type; Size; Processor; IL Only; Signed
winhlp32.exe; Unmanaged; 296960; X86
C:\Downloads\ApiChange>ApiChange.exe -CorFlags c:\Windows\HelpPane.exe
File Name; Type; Size; Processor; IL Only; Signed
HelpPane.exe; Unmanaged; 733696; Amd64
select name, count(*) from table group by name;
i think should do it
I made this helper class in C# (Xamarin) to programmatically set the text property. It which works pretty well for me:
internal static class FontAwesomeManager
{
private static readonly Typeface AwesomeFont = Typeface.CreateFromAsset(App.Application.Context.Assets, "FontAwesome.ttf");
private static readonly Dictionary<FontAwesomeIcon, string> IconMap = new Dictionary<FontAwesomeIcon, string>
{
{FontAwesomeIcon.Bars, "\uf0c9"},
{FontAwesomeIcon.Calendar, "\uf073"},
{FontAwesomeIcon.Child, "\uf1ae"},
{FontAwesomeIcon.Cog, "\uf013"},
{FontAwesomeIcon.Eye, "\uf06e"},
{FontAwesomeIcon.Filter, "\uf0b0"},
{FontAwesomeIcon.Link, "\uf0c1"},
{FontAwesomeIcon.ListOrderedList, "\uf0cb"},
{FontAwesomeIcon.PencilSquareOutline, "\uf044"},
{FontAwesomeIcon.Picture, "\uf03e"},
{FontAwesomeIcon.PlayCircleOutline, "\uf01d"},
{FontAwesomeIcon.SignOut, "\uf08b"},
{FontAwesomeIcon.Sliders, "\uf1de"}
};
public static void Awesomify(this TextView view, FontAwesomeIcon icon)
{
var iconString = IconMap[icon];
view.Text = iconString;
view.SetTypeface(AwesomeFont, TypefaceStyle.Normal);
}
}
enum FontAwesomeIcon
{
Bars,
Calendar,
Child,
Cog,
Eye,
Filter,
Link,
ListOrderedList,
PencilSquareOutline,
Picture,
PlayCircleOutline,
SignOut,
Sliders
}
Should be easy enough to convert to Java, I think. Hope it helps someone!
The above solutions didn't work for me for classes with background images somehow. What I did was I create a default class (the one you need in else) and set class='defaultClass' and then the ng-class="{class1:abc,class2:xyz}"
<span class="booking_warning" ng-class="{ process_success: booking.bookingStatus == 'BOOKING_COMPLETED' || booking.bookingStatus == 'BOOKING_PROCESSED', booking_info: booking.bookingStatus == 'INSTANT_BOOKING_REQUEST_RECEIVED' || booking.bookingStatus == 'BOOKING_PENDING'}"> <strong>{{booking.bookingStatus}}</strong> </span>
P.S: The classes that are in condition should override the default class i.e marked as !important
If you don't mind using a bit of JavaScript, jQuery's fadeTo() works nicely in every browser I've tried.
jQuery(selector).fadeTo(speed, opacity);
In DJango 3.0 the default value of a BooleanField in model.py is set like this:
class model_name(models.Model):
example_name = models.BooleanField(default=False)
I just had need to do this for a config file.
var config = {
x: "CHANGE_ME",
y: "CHANGE_ME",
z: "CHANGE_ME"
}
export default config;
You can do it like this
import { default as config } from "./config";
console.log(config.x); // CHANGE_ME
This is using Typescript mind you.
In python 2.7 you can use NumPy's numpy.std()
gives the population standard deviation.
In Python 3.4 statistics.stdev()
returns the sample standard deviation. The pstdv()
function is the same as numpy.std()
.
In my case charset, datatype every thing was correct. After investigation I found that in parent table there was no index on foreign key column. Once added problem got solved.
Problem Cause
In mac os image rendering back end of matplotlib (what-is-a-backend to render using the API of Cocoa by default). There are Qt4Agg and GTKAgg and as a back-end is not the default. Set the back end of macosx that is differ compare with other windows or linux os.
Solution
~/.matplotlib
. ~/.matplotlib/matplotlibrc
there and add the following code: backend: TkAgg
From this link you can try different diagrams.
you could use key
value to reset state when need, pass props to state it's not a good practice , because you have uncontrolled and controlled component in one place. Data should be in one place handled
read this
https://reactjs.org/blog/2018/06/07/you-probably-dont-need-derived-state.html#recommendation-fully-uncontrolled-component-with-a-key
This is happening because your current CUDA version doesn't support your current GCC version. You need to do the following:
Find the supported GCC version (in my case 5 for CUDA 9)
Install the supported GCC version
sudo apt-get install gcc-5
sudo apt-get install g++-5
Change the softlinks for GCC in the /usr/bin
directory
cd /usr/bin
sudo rm gcc
sudo rm g++
sudo ln -s /usr/bin/gcc-5 gcc
sudo ln -s /usr/bin/g++-5 g++
Change the softlinks for GCC in the /usr/local/cuda-9.0/bin
directory
cd /usr/local/cuda-9.0/bin
sudo rm gcc
sudo rm g++
sudo ln -s /usr/bin/gcc-5 gcc
sudo ln -s /usr/bin/g++-5 g++
Add -DCUDA_HOST_COMPILER=/usr/bin/gcc-5
to your setup.py
file, used for compilation
if torch.cuda.is_available() and CUDA_HOME is not None:
extension = CUDAExtension
sources += source_cuda
define_macros += [("WITH_CUDA", None)]
extra_compile_args["nvcc"] = [
"-DCUDA_HAS_FP16=1",
"-D__CUDA_NO_HALF_OPERATORS__",
"-D__CUDA_NO_HALF_CONVERSIONS__",
"-D__CUDA_NO_HALF2_OPERATORS__",
"-DCUDA_HOST_COMPILER=/usr/bin/gcc-5"
]
Remove the old build directory
rm -rd build/
Compile again by setting CUDAHOSTCXX=/usr/bin/gcc-5
CUDAHOSTCXX=/usr/bin/gcc-5 python setup.py build develop
Note: If you still get the gcc: error trying to exec 'cc1plus': execvp: no such file or directory
error after following these steps, try reinstalling the GCC like this and then compiling again:
sudo apt-get install --reinstall gcc-5
sudo apt-get install --reinstall g++-5
Credits: https://github.com/facebookresearch/maskrcnn-benchmark/issues/25#issuecomment-433382510
Annotate the property like below
[Key]
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int ID { get; set; }
To use identity columns for all value-generated properties on a new model, simply place the following in your context's OnModelCreating():
builder.ForNpgsqlUseIdentityColumns();
This will create make all keys and other properties which have .ValueGeneratedOnAdd() have Identity by default. You can use ForNpgsqlUseIdentityAlwaysColumns() to have Identity always, and you can also specify identity on a property-by-property basis with UseNpgsqlIdentityColumn() and UseNpgsqlIdentityAlwaysColumn().
This is what you are looking for:
^((?!(abc|def)).)*$
the explanation is here: Regular expression to match a line that doesn't contain a word?
It is likely that the delete statement will affect a large fraction of the total rows in the table. Eventually this might lead to a table lock being acquired when deleting. Holding on to a lock (in this case row- or page locks) and acquiring more locks is always a deadlock risk. However I can't explain why the insert statement leads to a lock escalation - it might have to do with page splitting/adding, but someone knowing MySQL better will have to fill in there.
For a start it can be worth trying to explicitly acquire a table lock right away for the delete statement. See LOCK TABLES and Table locking issues.
double d = 4.0;
DecimalFormat nf = DecimalFormat.getInstance(Locale.ENGLISH);
System.out.println(nf.format("#.##"));
Make sure you have the prerequisite, a JVM (http://wiki.eclipse.org/Eclipse/Installation#Install_a_JVM) installed.
This will be a JRE and JDK package.
There are a number of sources which includes: http://www.oracle.com/technetwork/java/javase/downloads/index.html.
int[] SingleDimensionalArray = new int[2]
int[][] MultiDimensionalArray = new int[3][4]
use this code it is working
// index.jsp or login.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
I found a new way to do it without interfaces. You only need to add the below code to the Fragment’s onCreate() method:
//overriding the fragment's oncreate
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//calling onBackPressedDispatcher and adding call back
requireActivity().onBackPressedDispatcher.addCallback(this) {
//do stuff here
}
}
Both the following are set to "google_sdk":
Build.PRODUCT
Build.MODEL
So it should be enough to use either one of the following lines.
"google_sdk".equals(Build.MODEL)
or
"google_sdk".equals(Build.PRODUCT)
The way to do it is to pass the tasks a callback that updates a shared counter. When the shared counter reaches zero you know that all tasks have finished so you can continue with your normal flow.
var ntasks_left_to_go = 4;
var callback = function(){
ntasks_left_to_go -= 1;
if(ntasks_left_to_go <= 0){
console.log('All tasks have completed. Do your stuff');
}
}
task1(callback);
task2(callback);
task3(callback);
task4(callback);
Of course, there are many ways to make this kind of code more generic or reusable and any of the many async programing libraries out there should have at least one function to do this kind of thing.
According to MSDN maxAllowedContentLength
has type uint
, its maximum value is 4,294,967,295 bytes = 3,99 gb
So it should work fine.
See also Request Limits article. Does IIS return one of these errors when the appropriate section is not configured at all?
See also: Maximum request length exceeded
a=5; i=++a + ++a + a++;
is
i = 7 + 6 + 7
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
. then a=7
is provided to post increment => 7 + 6 + 7 =20
and a =8
.
a=5; i=a++ + ++a + ++a;
is
i=7 + 7 + 6
Working: pre/post increment has "right to left" Associativity , and pre has precedence over post , so first of all pre increment will be solve as (++a + ++a) => 7 + 6
.then a=7
is provided to post increment => 7 + 7 + 6 =20
and a =8
.
Even more concise if you are on python 2.7:
>>> t = ((1,'a'),(2,'b'))
>>> {y:x for x,y in t}
{'a':1, 'b':2}
When sending data to a web server, the data has to be a string (here). You can convert a JavaScript object into a string with JSON.stringify()
.
Here is a working example:
var fs = require('fs');
var originalNote = {
title: 'Meeting',
description: 'Meeting John Doe at 10:30 am'
};
var originalNoteString = JSON.stringify(originalNote);
fs.writeFileSync('notes.json', originalNoteString);
var noteString = fs.readFileSync('notes.json');
var note = JSON.parse(noteString);
console.log(`TITLE: ${note.title} DESCRIPTION: ${note.description}`);
Hope it could help.
You can use the CSS property max-width
and use it with ch
unit.
And, as this is a <span>
, use a display: inline-block;
(or block).
Here is an example:
<span style="
display:inline-block;
white-space: nowrap;
overflow: hidden;
text-overflow: ellipsis;
max-width: 13ch;">
Lorem ipsum dolor sit amet
</span>
Which outputs:
Lorem ipsum...
<span style="_x000D_
display:inline-block;_x000D_
white-space: nowrap;_x000D_
overflow: hidden;_x000D_
text-overflow: ellipsis;_x000D_
max-width: 13ch;">_x000D_
Lorem ipsum dolor sit amet_x000D_
</span>
_x000D_
Below is how it worked for me
Shows new environment path
Clones default root environment
Deactivating environment "d:\YourDefaultAnaconda3"... Activating environment "d:\your\location\YourNewEnvironment"...
conda environments: #
YourNewEnvironment
* d:\your\location\YourNewEnvironment
root d:\YourDefaultAnaconda3
I've coded up a simple example for you and annotated the source. The example shows how to grab live json and parse into a JSONObject
for detail extraction:
try{
// Create a new HTTP Client
DefaultHttpClient defaultClient = new DefaultHttpClient();
// Setup the get request
HttpGet httpGetRequest = new HttpGet("http://example.json");
// Execute the request in the client
HttpResponse httpResponse = defaultClient.execute(httpGetRequest);
// Grab the response
BufferedReader reader = new BufferedReader(new InputStreamReader(httpResponse.getEntity().getContent(), "UTF-8"));
String json = reader.readLine();
// Instantiate a JSON object from the request response
JSONObject jsonObject = new JSONObject(json);
} catch(Exception e){
// In your production code handle any errors and catch the individual exceptions
e.printStackTrace();
}
Once you have your JSONObject
refer to the SDK for details on how to extract the data you require.
I think you forgot to change
data={this.props.data}
to
data={this.state.data}
in the render function of CommentBox. I did the same mistake when I was following the tutorial. Thus the whole render function should look like
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.state.data} />
<CommentForm />
</div>
);
}
instead of
render: function() {
return (
<div className="commentBox">
<h1>Comments</h1>
<CommentList data={this.props.data} />
<CommentForm />
</div>
);
Based on @givanse's answer, this is how you could do it with classes
:
class Swipe {
constructor(element) {
this.xDown = null;
this.yDown = null;
this.element = typeof(element) === 'string' ? document.querySelector(element) : element;
this.element.addEventListener('touchstart', function(evt) {
this.xDown = evt.touches[0].clientX;
this.yDown = evt.touches[0].clientY;
}.bind(this), false);
}
onLeft(callback) {
this.onLeft = callback;
return this;
}
onRight(callback) {
this.onRight = callback;
return this;
}
onUp(callback) {
this.onUp = callback;
return this;
}
onDown(callback) {
this.onDown = callback;
return this;
}
handleTouchMove(evt) {
if ( ! this.xDown || ! this.yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
this.xDiff = this.xDown - xUp;
this.yDiff = this.yDown - yUp;
if ( Math.abs( this.xDiff ) > Math.abs( this.yDiff ) ) { // Most significant.
if ( this.xDiff > 0 ) {
this.onLeft();
} else {
this.onRight();
}
} else {
if ( this.yDiff > 0 ) {
this.onUp();
} else {
this.onDown();
}
}
// Reset values.
this.xDown = null;
this.yDown = null;
}
run() {
this.element.addEventListener('touchmove', function(evt) {
this.handleTouchMove(evt).bind(this);
}.bind(this), false);
}
}
You can than use it like this:
// Use class to get element by string.
var swiper = new Swipe('#my-element');
swiper.onLeft(function() { alert('You swiped left.') });
swiper.run();
// Get the element yourself.
var swiper = new Swipe(document.getElementById('#my-element'));
swiper.onLeft(function() { alert('You swiped left.') });
swiper.run();
// One-liner.
(new Swipe('#my-element')).onLeft(function() { alert('You swiped left.') }).run();
Peter, you should really take a look at Canappi, it does all that for you, all you have to do is specify the layout as such:
button mySubmitButton 'Sumbit' (100,100,100,30 + 0,88,0,0) { ... }
From there Canappi will generate the correct objective-c code that detects the device the app is running on and will use:
(100,100,100,30) for iPhone4
(100,**188**,100,30) for iPhone 5
Canappi works like Interface Builder and Story Board combined, except that it is in a textual form. If you already have XIB files, you can convert them so you don't have to recreate the entire UI from scratch.
The only way I can think of for short texts like "MENU" is to put every single letter in a span and justify them in a container afterwards. Like this:
<div class="menu-burger">
<span></span>
<span></span>
<span></span>
<div>
<span>M</span>
<span>E</span>
<span>N</span>
<span>U</span>
</div>
</div>
And then the CSS:
.menu-burger {
width: 50px;
height: 50px;
padding: 5px;
}
...
.menu-burger > div {
display: flex;
justify-content: space-between;
}
take look at my example
<tocheading language="EN">
<subj-group>
<subject>Editors Choice</subject>
<subject>creative common</subject>
</subj-group>
</tocheading>
now how to check if creative common
is exist
tocheading/subj-group/subject/text() = 'creative common'
hope this help you
You can use slice method in javascript array object
<div ng-repeat="item in items.slice(0, 4)">{{item}}</div>
Short n sweet
HTML:
<div id="myElement">Rounded Corner Box</div>
CSS:
#myElement {
background: #EEE;
padding: 2em;
-moz-border-radius: 1em;
-webkit-border-radius: 1em;
border-radius: 1em;
behavior: url(PIE.htc);
border: 1px solid red;
}
PIE.htc file can be downloaded from http://www.css3pie.com
A very late answer, but hope this will help
^(.+?)/([\w]+\.log)$
This uses lazy check for /
, and I just modified the accepted answer
Since you don't mention a plot package , I propose here using Lattice
version( I think there is more ggplot2 answers than lattice ones, at least since I am here in SO).
## reshaping the data( similar to the other answer)
library(reshape2)
dat.m <- melt(TestData,id.vars='Label')
library(lattice)
bwplot(value~Label |variable, ## see the powerful conditional formula
data=dat.m,
between=list(y=1),
main="Bad or Good")
I realise that it's been a very long time but thought I'd add anyway. If you just want the table, and not the create table statement you could use
select into x from db.schema.y where 1=0
to copy the table to a new DB
@Html.ValidationSummary(false,"", new { @class = "text-danger" })
Using this line may be helpful
UIStackView
uses constraints internally to position its arranged subviews. Exactly what constraints are created depends on how the stack view itself is configured. By default, a stack view will create constraints that lay out its arranged subviews in a horizontal line, pinning the leading and trailing views to its own leading and trailing edges. So your code would produce a layout that looks like this:
|[view1][view2]|
The space that is allocated to each subview is determined by a number of factors including the subview's intrinsic content size and it's compression resistance and content hugging priorities. By default, UIView
instances don't define an intrinsic content size. This is something that is generally provided by a subclass, such as UILabel
or UIButton
.
Since the content compression resistance and content hugging priorities of two new UIView
instances will be the same, and neither view provides an intrinsic content size, the layout engine must make its best guess as to what size should be allocated to each view. In your case, it is assigning the first view 100% of the available space, and nothing to the second view.
If you modify your code to use UILabel
instances instead, you will get better results:
UILabel *label1 = [UILabel new];
label1.text = @"Label 1";
label1.backgroundColor = [UIColor blueColor];
UILabel *label2 = [UILabel new];
label2.text = @"Label 2";
label2.backgroundColor = [UIColor greenColor];
[self.stack1 addArrangedSubview:label1];
[self.stack1 addArrangedSubview:label2];
Note that it is not necessary to explictly create any constraints yourself. This is the main benefit of using UIStackView
- it hides the (often ugly) details of constraint management from the developer.
If you are in need of the average and can skip the requirement of calculating the sum, you can compute the average with a single call of reduce:
// Assumes an array with only values that can be parsed to a Float
var reducer = function(cumulativeAverage, currentValue, currentIndex) {
// 1. multiply average by currentIndex to find cumulative sum of previous elements
// 2. add currentValue to get cumulative sum, including current element
// 3. divide by total number of elements, including current element (zero-based index + 1)
return (cumulativeAverage * currentIndex + parseFloat(currentValue))/(currentIndex + 1)
}
console.log([1, 2, 3, 4, 5, 6, 7, 8, 9, 10].reduce(reducer, 0)); // => 5.5
console.log([].reduce(reducer, 0)); // => 0
console.log([0].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
console.log([,,,].reduce(reducer, 0)); // => 0
console.log([].reduce(reducer, 0)); // => 0
$(function() {_x000D_
_x000D_
$("input:disabled").closest("div").click(function() {_x000D_
$(this).find("input:disabled").attr("disabled", false).focus();_x000D_
});_x000D_
_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>_x000D_
_x000D_
<div>_x000D_
<input type="text" disabled />_x000D_
</div>
_x000D_
The tutorial @Henrik mentioned is an excellent resource for learning how to create plots with the ggplot2
package.
An example with your data:
# transforming the data from wide to long
library(reshape2)
dfm <- melt(df, id = "TY")
# creating a scatterplot
ggplot(data = dfm, aes(x = TY, y = value, color = variable)) +
geom_point(size=5) +
labs(title = "Temperatures\n", x = "TY [°C]", y = "Txxx", color = "Legend Title\n") +
scale_color_manual(labels = c("T999", "T888"), values = c("blue", "red")) +
theme_bw() +
theme(axis.text.x = element_text(size = 14), axis.title.x = element_text(size = 16),
axis.text.y = element_text(size = 14), axis.title.y = element_text(size = 16),
plot.title = element_text(size = 20, face = "bold", color = "darkgreen"))
this results in:
As mentioned by @user2739472 in the comments: If you only want to change the legend text labels and not the colours from ggplot's default palette, you can use scale_color_hue(labels = c("T999", "T888"))
instead of scale_color_manual()
.
I personally really hate the alternate syntax. One nice thing about the braces is that most IDEs, vim, etc all have bracket highlighting. In my text editor I can double click a brace and it will highlight the whole chunk so I can see where it ends and begins very easily.
I don't know of a single editor that can highlight endif, endforeach, etc.
C++ (and C for that matter) split the "declaration" and the "implementation" of types, functions and classes. You should "declare" the classes you need in a header-file (.h or .hpp), and put the corresponding implementation in a .cpp-file. Then, when you wish to use (access) a class somewhere, you #include the corresponding headerfile.
Example
ClassOne.hpp:
class ClassOne
{
public:
ClassOne(); // note, no function body
int method(); // no body here either
private:
int member;
};
ClassOne.cpp:
#include "ClassOne.hpp"
// implementation of constructor
ClassOne::ClassOne()
:member(0)
{}
// implementation of "method"
int ClassOne::method()
{
return member++;
}
main.cpp:
#include "ClassOne.hpp" // Bring the ClassOne declaration into "view" of the compiler
int main(int argc, char* argv[])
{
ClassOne c1;
c1.method();
return 0;
}