The information you want can be found by running
mysql --help
or
mysqld --help --verbose
I tried this :
mysql --help | grep Default -A 1
And the output:
(Defaults to on; use --skip-auto-rehash to disable.)
-A, --no-auto-rehash
--
(Defaults to on; use --skip-line-numbers to disable.)
-L, --skip-line-numbers
--
(Defaults to on; use --skip-column-names to disable.)
-N, --skip-column-names
--
(Defaults to on; use --skip-reconnect to disable.)
-s, --silent Be more silent. Print results with a tab as separator,
--
--default-auth=name Default authentication client-side plugin to use.
--binary-mode By default, ASCII '\0' is disallowed and '\r\n' is
--
Default options are read from the following files in the given order:
/etc/my.cnf /etc/mysql/my.cnf /usr/etc/my.cnf ~/.my.cnf
Seems like the list of fixes is growing, even years after since the original question.
Below is the full list for Windows (so far as of circa 02/2020)
If you have Windows 10, with all updates installed and you believe
try Step 6 below. It is likely the cause.
Also to see if your fix worked, you can manually download the Intel HAXM installer here. (Latest version of HAXM may not be the same as what comes from Android Studio) Before starting the install, run the haxm_check.exe
included in the download from command line. If your fix worked, it should show yes
for both NX
and VT
.
If you just double click haxm_check.exe
you won't see anything. Run it from cmd or powershell to see the output.
make sure it is Enabled. If the option is not there, check with your manufacturer and model to make sure it is supported.
systeminfo
. If it shows 'hypervisor is detected' under Hyper-V requirements, even after removing Hyper-V feature, you may have 'Core Isolation' enabled. See below on how to disable it.bcdedit /set hypervisorlaunchtype off
bcdedit /set hypervisorlaunchtype auto
and rebootauto
after the emulator has installed. But may need to set to off
reboot the next time you create an emulator/download and install an emulator image.Edits/New fixes welcome.
hope this helps
This code works form me. Include the jquery.js file.
<!DOCTYPE html>
<html>
<head>
<script src="jquery.js"></script>
<script>
var headerDivWidth=0;
var contentDivWidth=0;
function fixHeader(){
var contentDivId = "contentDiv";
var headerDivId = "headerDiv";
var header = document.createElement('table');
var headerRow = document.getElementById('tableColumnHeadings');
/*Start : Place header table inside <DIV> and place this <DIV> before content table*/
var headerDiv = "<div id='"+headerDivId+"' style='width:500px;overflow-x:hidden;overflow-y:scroll' class='tableColumnHeadings'><table></table></div>";
$(headerRow).wrap(headerDiv);
$("#"+headerDivId).insertBefore("#"+contentDivId);
/*End : Place header table inside <DIV> and place this <DIV> before content table*/
fixColumnWidths(headerDivId,contentDivId);
}
function fixColumnWidths(headerDivId,contentDivId){
/*Start : Place header row cell and content table first row cell inside <DIV>*/
var contentFirstRowCells = $('#'+contentDivId+' table tr:first-child td');
for (k = 0; k < contentFirstRowCells.length; k++) {
$( contentFirstRowCells[k] ).wrapInner( "<div ></div>");
}
var headerFirstRowCells = $('#'+headerDivId+' table tr:first-child td');
for (k = 0; k < headerFirstRowCells.length; k++) {
$( headerFirstRowCells[k] ).wrapInner( "<div></div>");
}
/*End : Place header row cell and content table first row cell inside <DIV>*/
/*Start : Fix width for columns of header cells and content first ror cells*/
var headerColumns = $('#'+headerDivId+' table tr:first-child td div:first-child');
var contentColumns = $('#'+contentDivId+' table tr:first-child td div:first-child');
for (i = 0; i < contentColumns.length; i++) {
if (i == contentColumns.length - 1) {
contentCellWidth = contentColumns[i].offsetWidth;
}
else {
contentCellWidth = contentColumns[i].offsetWidth;
}
headerCellWidth = headerColumns[i].offsetWidth;
if(contentCellWidth>headerCellWidth){
$(headerColumns[i]).css('width', contentCellWidth+"px");
$(contentColumns[i]).css('width', contentCellWidth+"px");
}else{
$(headerColumns[i]).css('width', headerCellWidth+"px");
$(contentColumns[i]).css('width', headerCellWidth+"px");
}
}
/*End : Fix width for columns of header and columns of content table first row*/
}
function OnScrollDiv(Scrollablediv) {
document.getElementById('headerDiv').scrollLeft = Scrollablediv.scrollLeft;
}
function radioCount(){
alert(document.form.elements.length);
}
</script>
<style>
table,th,td
{
border:1px solid black;
border-collapse:collapse;
}
th,td
{
padding:5px;
}
</style>
</head>
<body onload="fixHeader();">
<form id="form" name="form">
<div id="contentDiv" style="width:500px;height:100px;overflow:auto;" onscroll="OnScrollDiv(this)">
<table>
<!--tr id="tableColumnHeadings" class="tableColumnHeadings">
<td><div>Firstname</div></td>
<td><div>Lastname</div></td>
<td><div>Points</div></td>
</tr>
<tr>
<td><div>Jillsddddddddddddddddddddddddddd</div></td>
<td><div>Smith</div></td>
<td><div>50</div></td>
</tr-->
<tr id="tableColumnHeadings" class="tableColumnHeadings">
<td> </td>
<td>Firstname</td>
<td>Lastname</td>
<td>Points</td>
</tr>
<tr style="height:0px">
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr >
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID" onclick="javascript:radioCount();"/></td>
<td>Jillsddddddddddddddddddddddddddd</td>
<td>Smith</td>
<td>50</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>Eve</td>
<td>Jackson</td>
<td>9400000000000000000000000000000</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td><div>Jillsddddddddddddddddddddddddddd</div></td>
<td><div>Smith</div></td>
<td><div>50</div></td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>Eve</td>
<td>Jackson</td>
<td>9400000000000000000000000000000</td>
</tr>
<tr>
<td><input type="radio" id="SELECTED_ID" name="SELECTED_ID"/></td>
<td>John</td>
<td>Doe</td>
<td>80</td>
</tr>
</table>
</div>
</form>
</body>
</html>
It is .shape
:
ndarray.shape
Tuple of array dimensions.
Thus:
>>> a.shape
(2, 2)
Change the PATH variable to include the bin directory of your PostgreSQL installation.
then add new path their....[for example]
C:\Program Files\PostgreSQL\12\bin
After that click OK
Open CMD/Command Prompt. Type this to open psql
psql -U username database_name
For Example psql -U postgres test
Now, you will be prompted to give Password for the User. (It will be hidden as a security measure).
Then you are good to go.
File modification:
ls -t
Inode change:
ls -tc
File access:
ls -tu
"Newest" one at the bottom:
ls -tr
None of this is a creation time. Most Unix filesystems don't support creation timestamps.
If the web service being invoked uses windows integrated security, creating a NetworkCredential
from the current WindowsIdentity
should be sufficient to allow the web service to use the current users windows login. However, if the web service uses a different security model, there isn't any way to extract a users password from the current identity ... that in and of itself would be insecure, allowing you, the developer, to steal your users passwords. You will likely need to provide some way for your user to provide their password, and keep it in some secure cache if you don't want them to have to repeatedly provide it.
Edit: To get the credentials for the current identity, use the following:
Uri uri = new Uri("http://tempuri.org/");
ICredentials credentials = CredentialCache.DefaultCredentials;
NetworkCredential credential = credentials.GetCredential(uri, "Basic");
As for 2018 there is still not a simple answer to the question of how to convert a PDF document to an image in C#; many libraries use Ghostscript licensed under AGPL and in most cases an expensive commercial license is required for production use.
A good alternative might be using the popular 'pdftoppm' utility which has a GPL license; it can be used from C# as command line tool executed with System.Diagnostics.Process. Popular tools are well known in the Linux world, but a windows build is also available.
If you don't want to integrate pdftoppm by yourself, you can use my PdfRenderer popular wrapper (supports both classic .NET Framework and .NET Core) - it is not free, but pricing is very affordable.
1) Go to C:\Program Files (x86)\Microsoft SDKs\Windows\v7.1A for VS2013
2) Copy the folders Include
and Lib
(you should check where are your folders in folder windows such as v7.1
, v8
, v6
, etc.)
3) Paste them into C:\Program Files (x86)\Microsoft Visual Studio 12.0\VC
I solved my problems like:
error lnk1104: cannot open file 'kernel32.lib'.
error c1083: Cannot open Windows.h
Thanks.
from flask import request
@app.route('/data')
def data():
# here we want to get the value of user (i.e. ?user=some-value)
user = request.args.get('user')
From here download this video so we have the same video file for the test. Make sure to have that mp4 file in the same directory of your python code. Then also make sure to run the python interpreter from the same directory.
Then modify the code, ditch waitKey
that's wasting time also without a window it cannot capture the keyboard events. Also we print the success
value to make sure it's reading the frames successfully.
import cv2
vidcap = cv2.VideoCapture('big_buck_bunny_720p_5mb.mp4')
success,image = vidcap.read()
count = 0
while success:
cv2.imwrite("frame%d.jpg" % count, image) # save frame as JPEG file
success,image = vidcap.read()
print('Read a new frame: ', success)
count += 1
How does that go?
If it's not a typed dataset, then you probably want to do something like this, using the Linq-to-DataSet extension methods:
var distinctValues = dsValues.AsEnumerable()
.Select(row => new {
attribute1_name = row.Field<string>("attribute1_name"),
attribute2_name = row.Field<string>("attribute2_name")
})
.Distinct();
Make sure you have a using System.Data;
statement at the beginning of your code in order to enable the Linq-to-Dataset extension methods.
Hope this helps!
A bit shorter answer since PHP >= 5.3.0:
$csvFile = file('../somefile.csv');
$data = [];
foreach ($csvFile as $line) {
$data[] = str_getcsv($line);
}
I'm not sure how you want to use the file names, but one of these should help:
If you just want to see the names, you can use something like gulp-debug
, which lists the details of the vinyl file. Insert this anywhere you want a list, like so:
var gulp = require('gulp'),
debug = require('gulp-debug');
gulp.task('examples', function() {
return gulp.src('./examples/*.html')
.pipe(debug())
.pipe(gulp.dest('./build'));
});
Another option is gulp-filelog
, which I haven't used, but sounds similar (it might be a bit cleaner).
Another options is gulp-filesize
, which outputs both the file and it's size.
If you want more control, you can use something like gulp-tap
, which lets you provide your own function and look at the files in the pipe.
Probably because you forgot to implement the solution in the accepted answer. That's the code that makes trim()
work.
update
This answer only applies to older browsers. Newer browsers apparently support trim()
natively.
<form>
<input type="hidden" name="selval">
<select onchange="this.form.selval.value=this.selectedIndex">
<option>val1</option>
<option>val2</option>
</select>
</form>
pure javascript from within a form
I believe the default color integer value is 16711935 (0x00FF00FF).
you need to parse your xml with jquery json parse...i.e
var parsed_json = $.parseJSON(xml);
Based on your comment, moddify this:
$( '.bgHeaderH2' ).html (); // will return whatever is inside the DIV
to:
$( '.bgHeaderH2', $( this ) ).html (); // will return whatever is inside the DIV
More about selectors: https://api.jquery.com/category/selectors/
private static String getPreviousMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.add(Calendar.DATE, -1);
Date preMonthDate = cal.getTime();
return format.format(preMonthDate);
}
private static String getPreToPreMonthDate(Date date){
final SimpleDateFormat format = new SimpleDateFormat("dd-MM-yyyy");
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.add(Calendar.MONTH, -1);
cal.set(Calendar.DAY_OF_MONTH,1);
cal.add(Calendar.DATE, -1);
Date preToPreMonthDate = cal.getTime();
return format.format(preToPreMonthDate);
}
I tried everything except this. After rigorous trials,Uninstalling java 8 update 25 helped me.
Here's another solution using a package solely dedicated to working with dates and times in R:
library(tidyverse)
library(lubridate)
(df <- tibble(ID = 1:3, Date = c("2004-02-06" , "2006-03-14", "2007-07-16")))
#> # A tibble: 3 x 2
#> ID Date
#> <int> <chr>
#> 1 1 2004-02-06
#> 2 2 2006-03-14
#> 3 3 2007-07-16
df %>%
mutate(
Date = ymd(Date),
Month_Yr = format_ISO8601(Date, precision = "ym")
)
#> # A tibble: 3 x 3
#> ID Date Month_Yr
#> <int> <date> <chr>
#> 1 1 2004-02-06 2004-02
#> 2 2 2006-03-14 2006-03
#> 3 3 2007-07-16 2007-07
Created on 2020-09-01 by the reprex package (v0.3.0)
Despite setting up dimensions for the columns, they still seem to shrink as the window shrinks.
An initial setting of a flex container is flex-shrink: 1
. That's why your columns are shrinking.
It doesn't matter what width you specify (it could be width: 10000px
), with flex-shrink
the specified width can be ignored and flex items are prevented from overflowing the container.
I'm trying to set up a flexbox with 3 columns where the left and right columns have a fixed width...
You will need to disable shrinking. Here are some options:
.left, .right {
width: 230px;
flex-shrink: 0;
}
OR
.left, .right {
flex-basis: 230px;
flex-shrink: 0;
}
OR, as recommended by the spec:
.left, .right {
flex: 0 0 230px; /* don't grow, don't shrink, stay fixed at 230px */
}
7.2. Components of Flexibility
Authors are encouraged to control flexibility using the
flex
shorthand rather than with its longhand properties directly, as the shorthand correctly resets any unspecified components to accommodate common uses.
More details here: What are the differences between flex-basis and width?
An additional thing I need to do is hide the right column based on user interaction, in which case the left column would still keep its fixed width, but the center column would fill the rest of the space.
Try this:
.center { flex: 1; }
This will allow the center column to consume available space, including the space of its siblings when they are removed.
I have a quick solution for finding Waldo using OpenCV.
I used the template matching function available in OpenCV to find Waldo.
To do this a template is needed. So I cropped Waldo from the original image and used it as a template.
Next I called the cv2.matchTemplate()
function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):
The position of the highest probable region was found using cv2.minMaxLoc()
function, which I then used to draw the rectangle to highlight Waldo:
Now Kibana 4 allows you to use aggregations. Apart from building a panel like the one that was explained in this answer for Kibana 3, now we can see the number of unique IPs in different periods, that was (IMO) what the OP wanted at the first place.
To build a dashboard like this you should go to Visualize -> Select your Index -> Select a Vertical Bar chart and then in the visualize panel:
Just take into account that the unique counts are approximate. For more information check also this answer.
You can also use array_column()
. It's available from PHP 5.5: php.net/manual/en/function.array-column.php
It returns the values from a single column of the array, identified by the column_key. Optionally, you may provide an index_key to index the values in the returned array by the values from the index_key column in the input array.
print_r(array_column($myarray, 'email'));
Yes you will have to escape all double quotes by a backslash.
Nothing worked for me until I finally found the answer here: http://ptspts.blogspot.co.il/2011/10/how-to-fix-adb-no-permissions-error-on.html
I'm copying the text here in case it disappears in the future.
Create a file named /tmp/android.rules with the following contents (hex vendor numbers were taken from the vendor list page):
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0e79", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0502", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0b05", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="413c", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0489", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="091e", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="18d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0bb4", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="12d1", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="24e3", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2116", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0482", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="17ef", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1004", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="22b8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0409", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2080", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0955", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="2257", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="10a9", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1d4d", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0471", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04da", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="05c6", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1f53", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04e8", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="04dd", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0fce", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="0930", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="19d2", MODE="0666"
SUBSYSTEM=="usb", ATTRS{idVendor}=="1bbb", MODE="0666"
Run the following commands:
sudo cp /tmp/android.rules /etc/udev/rules.d/51-android.rules
sudo chmod 644 /etc/udev/rules.d/51-android.rules
sudo chown root. /etc/udev/rules.d/51-android.rules
sudo service udev restart
sudo killall adb
Disconnect the USB cable between the phone and the computer.
Reconnect the phone.
Run adb devices
to confirm that now it has permission to access the phone.
Please note that it's possible to use , USER="$LOGINNAME"
instead of , MODE="0666"
in the .rules
file, substituting $LOGINNAME
for your login name, i.e. what id -nu
prints.
In some cases it can be necessary to give the udev rules file a name that sorts close to the end, such as z51-android.rules
.
sys.path
. See site
module.A larger list of additional Python file-extensions (mostly rare and unofficial) can be found at http://dcjtech.info/topic/python-file-extensions/
Hi you do it by using this approach, all fragments will remain in the container once added initially and then we are simply revealing the desired fragment and hiding the others within the container.
// Within an activity
private FragmentA fragmentA;
private FragmentB fragmentB;
private FragmentC fragmentC;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
fragmentA = FragmentA.newInstance("foo");
fragmentB = FragmentB.newInstance("bar");
fragmentC = FragmentC.newInstance("baz");
}
}
// Replace the switch method
protected void displayFragmentA() {
FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
if (fragmentA.isAdded()) { // if the fragment is already in container
ft.show(fragmentA);
} else { // fragment needs to be added to frame container
ft.add(R.id.flContainer, fragmentA, "A");
}
// Hide fragment B
if (fragmentB.isAdded()) { ft.hide(fragmentB); }
// Hide fragment C
if (fragmentC.isAdded()) { ft.hide(fragmentC); }
// Commit changes
ft.commit();
}
Please see https://github.com/codepath/android_guides/wiki/Creating-and-Using-Fragments for more info. I hope I get to help anyone. Even if it this is an old question.
Use a scalar-valued UDF, not a table-value one, then you can use it in a SELECT as you want.
SQL>
SELECT interview.qtrcode QTR, interview.companyname "Company Name", interview.division Division
FROM interview
JOIN jobsdev.employer
ON (interview.companyname = employer.companyname AND employer.zipcode like '100%')
GROUP BY interview.qtrcode, interview.companyname, interview.division
ORDER BY interview.qtrcode;
You have a couple of problems here.
First, the XSD has an issue where an element is both named or referenced; in your case should be referenced.
Change:
<xsd:element name="stock" ref="Stock" minOccurs="1" maxOccurs="unbounded"/>
To:
<xsd:element name="stock" type="Stock" minOccurs="1" maxOccurs="unbounded"/>
And:
Stock
Stock
So:
<xsd:element name="Stock">
<xsd:complexType>
To:
<xsd:complexType name="Stock">
Make sure you fix the xml closing tags.
The second problem is that the correct way to reference an external XSD is to use XSD schema with import/include within a wsdl:types element. wsdl:import is reserved to referencing other WSDL files. More information is available by going through the WS-I specification, section WSDL and Schema Import. Based on WS-I, your case would be:
INCORRECT: (the way you showed it)
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<import namespace="http://stock.com/schemas/services/stock" location="Stock.xsd" />
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
CORRECT:
<?xml version="1.0" encoding="UTF-8"?>
<definitions targetNamespace="http://stock.com/schemas/services/stock/wsdl"
.....xmlns:external="http://stock.com/schemas/services/stock"
<types>
<schema xmlns="http://www.w3.org/2001/XMLSchema">
<import namespace="http://stock.com/schemas/services/stock" schemaLocation="Stock.xsd" />
</schema>
</types>
<message name="getStockQuoteResp">
<part name="parameters" element="external:getStockQuoteResponse" />
</message>
</definitions>
SOME processors may support both syntaxes. The XSD you put out shows issues, make sure you first validate the XSD.
It would be better if you go the WS-I way when it comes to WSDL authoring.
Other issues may be related to the use of relative vs. absolute URIs in locating external content.
You can use below code to find out principal (user email who logged in)
org.opensaml.saml2.core.impl.NameIDImpl principal =
(NameIDImpl) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String email = principal.getValue();
This code is written on top of SAML.
Updated list December 2019, iOS13 One icon for iOS 180x180 px and one for android 192x192 px (declared in site.webmanifest).
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="manifest" href="/site.webmanifest">
#### site.webmanifest
{
"name": "",
"short_name": "",
"icons": [
{
"src": "/android-chrome-192x192.png",
"sizes": "192x192",
"type": "image/png"
}
],
"display": "standalone"
}
Deprecated list October 2017, iOS11
List for iPhone and iPad with and without retina
<!-- iPhone(first generation or 2G), iPhone 3G, iPhone 3GS -->
<link rel="apple-touch-icon" sizes="57x57" href="touch-icon-iphone.png">
<!-- iPad and iPad mini @1x -->
<link rel="apple-touch-icon" sizes="76x76" href="touch-icon-ipad.png">
<!-- iPhone 4, iPhone 4s, iPhone 5, iPhone 5c, iPhone 5s, iPhone 6, iPhone 6s, iPhone 7, iPhone 7s, iPhone8 -->
<link rel="apple-touch-icon" sizes="120x120" href="touch-icon-iphone-retina.png">
<!-- iPad and iPad mini @2x -->
<link rel="apple-touch-icon" sizes="152x152" href="touch-icon-ipad-retina.png">
<!-- iPad Pro -->
<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-pro.png">
<!-- iPhone X, iPhone 8 Plus, iPhone 7 Plus, iPhone 6s Plus, iPhone 6 Plus -->
<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-6-plus.png">
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="192x192" href="icon-hd.png">
<!-- Android Devices Normal Resolution -->
<link rel="icon" sizes="128x128" href="icon.png">
Update Oct 2017 iOS 11: iOS 11 checked, iPhone X and iPhone 8 introduced
Update Nov 2016 iOS 10: New iOS version iPhone 7 and iPhone 7plus introduced, they have the same display resolution, dpi, etc as iPhone 6s and iPhone 7plus, until now no changes found respecting the update 2015
Update Mid 2016 Android: Add Android Devices to the list as the apple-touch links are marked as deprecated by Google and will be not supported anytime for their devices
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="192x192" href="icon-hd.png">
<!-- Android Devices High Resolution -->
<link rel="icon" sizes="128x128" href="icon.png">
Update 2015 iOS 9: For iOS 9 and iPad pro
<link rel="apple-touch-icon" sizes="167x167" href="touch-icon-ipad-pro.png">
The new iPhones (6s and 6s Plus) are using the same sizes as the iPhone(6 and 6 Plus), the new iPad pro uses an image of size 167x167 px, the other resolutions are still the same.
Update 2014 iOS 8:
For iOS 8 and iPhone 6 plus
<link rel="apple-touch-icon" sizes="180x180" href="touch-icon-iphone-6-plus.png">
Iphone 6 uses the same 120 x 120 px image as iphone 4 and 5 the rest is the same as for iOS 7
Update 2013 iOS7:
For iOS 7 the recommended resolutions changed:
The other resolution are still the same
Source: https://developer.apple.com/ios/human-interface-guidelines/icons-and-images/app-icon/
I will show visually the problem, using the great example from James answer and adding the alternative solution.
When you do the follow query, without the FETCH
:
Select e from Employee e
join e.phones p
where p.areaCode = '613'
You will have the follow results from Employee
as you expected:
EmployeeId | EmployeeName | PhoneId | PhoneAreaCode |
---|---|---|---|
1 | James | 5 | 613 |
1 | James | 6 | 416 |
But when you add the FETCH
word on JOIN
, this is what happens:
EmployeeId | EmployeeName | PhoneId | PhoneAreaCode |
---|---|---|---|
1 | James | 5 | 613 |
The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416
register when you use WHERE
on the FETCH
join.
So, to bring all phones and apply the WHERE
correctly, you need to have two JOIN
s: one for the WHERE
and another for the FETCH
. Like:
Select e from Employee e
join e.phones p
join fetch e.phones //no alias, to not commit the mistake
where p.areaCode = '613'
In Kotlin:
recyclerView.viewTreeObserver.addOnGlobalLayoutListener { scrollToEnd() }
private fun scrollToEnd() =
(adapter.itemCount - 1).takeIf { it > 0 }?.let(recyclerView::smoothScrollToPosition)
One way to fix it is by modifying the assembly redirect in the web.config file.
Modify the following:
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.0.0" newVersion="4.0.0.0" />
</dependentAssembly>
to
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="4.0.0.0" />
</dependentAssembly>
So the oldVersion attribute should change from "...-4.0.0.0" to "...-5.2.3.0".
WAMP [ Windows, Apache, Mysql, Php]
XAMPP [X-os, Apache, Mysql, Php , Perl ] (x-os : it can be used on any OS )
Both can be used to easily run and test websites and web applications locally. WAMP cannot be run parallel with XAMPP because with default installation XAMPP gets priority and it takes up ports.
WAMP easy to setup configuration in. WAMPServer has a graphical user interface to switch on or off individual component softwares while it is running. WAMPServer provide an option to switch among many versions of Apache, many versions of PHP and many versions of MySQL all installed which provide more flexibility towards developing while XAMPPServer doesn't have such an option. If you want to use Perl with WAMP you can configure Perl with WAMPServer http://phpflow.com/perl/how-to-configure-perl-on-wamp/ but it is better to go with XAMPP.
XAMPP is easy to use than WAMP. XAMPP is more powerful. XAMPP has a control panel from that you can start and stop individual components (such as MySQL,Apache etc.). XAMPP is more resource consuming than WAMP because of heavy amount of internal component softwares like Tomcat , FileZilla FTP server, Webalizer, Mercury Mail etc.So if you donot need high features better to go with WAMP. XAMPP also has SSL feature which WAMP doesn't.(Secure Sockets Layer (SSL) is a networking protocol that manages server authentication, client authentication and encrypted communication between servers and clients. )
IIS acronym for Internet Information Server also an extensible web server initiated as a research project for for Microsoft NT.IIS can be used for making Web applications, search engines, and Web-based applications that access databases such as SQL Server within Microsoft OSs. . IIS supports HTTP, HTTPS, FTP, FTPS, SMTP and NNTP.
I got this when building a project via Visual Studio Online (VSTS) Build using Visual Studio Build
Steps.
The solution was:
<select name="selectedFacilityId" ng-model="selectedFacilityId">
<option ng-repeat="facility in facilities" value="{{facility.id}}">{{facility.name}}</option>
</select>
This is an example on how to use it.
Check this code to:
@Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// <uses-permission
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
// The directory is now empty so delete it
return dir.delete();
}
The best way I have found is to use the initComplete method as it fires after the data has been retrieved and renders the table. NOTE this only fires once though.
$("#tableOfData").DataTable({
"pageLength": 50,
"ajax":{
url: someurl,
dataType : "json",
type: "post",
"data": {data to be sent}
},
"initComplete":function( settings, json){
console.log(json);
// call your function here
}
});
It's also useful when you actually don't want to assign the value to anything, such as loading some class only once during runtime.
E.g.
static {
try {
Class.forName("com.example.jdbc.Driver");
} catch (ClassNotFoundException e) {
throw new ExceptionInInitializerError("Cannot load JDBC driver.", e);
}
}
Hey, there's another benefit, you can use it to handle exceptions. Imagine that getStuff()
here throws an Exception
which really belongs in a catch block:
private static Object stuff = getStuff(); // Won't compile: unhandled exception.
then a static
initializer is useful here. You can handle the exception there.
Another example is to do stuff afterwards which can't be done during assigning:
private static Properties config = new Properties();
static {
try {
config.load(Thread.currentThread().getClassLoader().getResourceAsStream("config.properties");
} catch (IOException e) {
throw new ExceptionInInitializerError("Cannot load properties file.", e);
}
}
To come back to the JDBC driver example, any decent JDBC driver itself also makes use of the static
initializer to register itself in the DriverManager
. Also see this and this answer.
Same problem, not sure why it occurred only after upgrading from Spring
v3.2.x
to v4.2.x
.
Solved it by doing the following:
Publish and Start the module in Tomcat
tab, it now starts properly.
Inspired by Tom's answer, I believe the idea here is:
onClickListener
during the creation of the dialog to null
onClickListener
after the dialog is shown. You can override the onShowListener
like Tom. Alternatively, you can
show()
onClickListener
as follows (slightly more readable I think). Code:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
// ...
final AlertDialog dialog = builder.create();
dialog.show();
// now you can override the default onClickListener
Button b = dialog.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Log.i(TAG, "ok button is clicked");
handleClick(dialog);
}
});
TableA LEFT OUTER JOIN TableB
is equivalent to TableB RIGHT OUTER JOIN Table A
.
In Oracle, (+)
denotes the "optional" table in the JOIN. So in your first query, it's a P LEFT OUTER JOIN S
. In your second query, it's S RIGHT OUTER JOIN P
. They're functionally equivalent.
In the terminology, RIGHT or LEFT specify which side of the join always has a record, and the other side might be null. So in a P LEFT OUTER JOIN S
, P
will always have a record because it's on the LEFT
, but S
could be null.
See this example from java2s.com for additional explanation.
To clarify, I guess I'm saying that terminology doesn't matter, as it's only there to help visualize. What matters is that you understand the concept of how it works.
I've seen some confusion about what matters in determining RIGHT vs LEFT in implicit join syntax.
LEFT OUTER JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
RIGHT OUTER JOIN
SELECT *
FROM A, B
WHERE B.column(+) = A.column
All I did is swap sides of the terms in the WHERE clause, but they're still functionally equivalent. (See higher up in my answer for more info about that.) The placement of the (+)
determines RIGHT or LEFT. (Specifically, if the (+)
is on the right, it's a LEFT JOIN. If (+)
is on the left, it's a RIGHT JOIN.)
The two styles of JOIN are implicit JOINs and explicit JOINs. They are different styles of writing JOINs, but they are functionally equivalent.
See this SO question.
Implicit JOINs simply list all tables together. The join conditions are specified in a WHERE clause.
Implicit JOIN
SELECT *
FROM A, B
WHERE A.column = B.column(+)
Explicit JOINs associate join conditions with a specific table's inclusion instead of in a WHERE clause.
Explicit JOIN
SELECT *
FROM A
LEFT OUTER JOIN B ON A.column = B.column
These Implicit JOINs can be more difficult to read and comprehend, and they also have a few limitations since the join conditions are mixed in other WHERE conditions. As such, implicit JOINs are generally recommended against in favor of explicit syntax.
npm i -D @angular/material @angular/cdk @angular/animations
The best way is to import the image first and then use it.
import React, { Component } from 'react';
import logo from '../logo.svg';
export default class Header extends Component {
render() {
return (
<div className="row">
<div className="logo">
<img src={logo} width="100" height="50" />
</div>
</div>
);
}
}
I think you want to cast your dt
to a date
and fix the format of your date literal:
SELECT *
FROM table
WHERE dt::date = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
Or the standard version:
SELECT *
FROM table
WHERE CAST(dt AS DATE) = '2011-01-01' -- This should be ISO-8601 format, YYYY-MM-DD
The extract
function doesn't understand "date" and it returns a number.
QT can be as simple as that of Windows. The equivalent code is
if (QMessageBox::Yes == QMessageBox(QMessageBox::Information, "title", "Question", QMessageBox::Yes|QMessageBox::No).exec())
{
}
Did you know that JavaScript has it's built-in methods and libs to create forms and submit them?
I am seeing a lot of replies here all asking to use a 3rd party library which I think is an overkill.
I would do the following in pure Javascript:
<script>
function launchMyForm()
{
var myForm = document.createElement("FORM");
myForm.setAttribute("id","TestForm");
document.body.appendChild(myForm);
// this will create a new FORM which is mapped to the Java Object of myForm, with an id of TestForm. Equivalent to: <form id="TestForm"></form>
var myInput = document.createElement("INPUT");
myInput.setAttribute("id","MyInput");
myInput.setAttribute("type","text");
myInput.setAttribute("value","Heider");
document.getElementById("TestForm").appendChild(myInput);
// This will create an INPUT equivalent to: <INPUT id="MyInput" type="text" value="Heider" /> and then assign it to be inside the TestForm tags.
}
</script>
This way (A) you don't need to rely on 3rd parties to do the job. (B) It's all built-in to all browsers, (C) faster, (D) it works, feel free to try it out.
I hope this helps. H
git rev-parse --show-toplevel
could be enough if executed within a git repo.
From git rev-parse
man page:
--show-toplevel
Show the absolute path of the top-level directory.
For older versions (before 1.7.x), the other options are listed in "Is there a way to get the git root directory in one command?":
git rev-parse --git-dir
That would give the path of the .git
directory.
The OP mentions:
git rev-parse --show-prefix
which returns the local path under the git repo root. (empty if you are at the git repo root)
Note: for simply checking if one is in a git repo, I find the following command quite expressive:
git rev-parse --is-inside-work-tree
And yes, if you need to check if you are in a .git
git-dir folder:
git rev-parse --is-inside-git-dir
Try with:
$row = mysqli_fetch_assoc($result);
echo "my result <a href='data/" . htmlentities($row['classtype'], ENT_QUOTES, 'UTF-8') . ".php'>My account</a>";
Seems like kind of a homely way of doing things, but if you must... you could restructure it as such to fit your needs:
boolean found = false;
case 1:
for (Element arrayItem : array) {
if (arrayItem == whateverValue) {
found = true;
} // else if ...
}
if (found) {
break;
}
case 2:
I think we need to write more specific media query. Make sure if you write one media query it should be not effect to other view (Mob,Tab,Desk) otherwise it can be trouble. I would like suggest to write one basic media query for respective device which cover both view and one orientation media query that you can specific code more about orientation view its for good practice. we Don't need to write both media orientation query at same time. You can refer My below example. I am sorry if my English writing is not much good. Ex:
For Mobile
@media screen and (max-width:767px) {
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:320px) and (max-width:767px) and (orientation:landscape) {
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
For Tablet
@media screen and (max-width:1024px){
..This is basic media query for respective device.In to this media query CSS code cover the both view landscape and portrait view.
}
@media screen and (min-width:768px) and (max-width:1024px) and (orientation:landscape){
..This orientation media query. In to this orientation media query you can specify more about CSS code for landscape view.
}
Desktop
make as per your design requirement enjoy...(:
Thanks, Jitu
Another short oneliner:
mydict = {'c': 1, 'b': 2, 'a': 3}
print(*sorted(mydict.items()), sep='\n')
Go to Start --> Run--> type " services.msc"
Select the OracleService name, Right Click, Start.
Wait for a while and then your service will start. Then go to your sql command line window and try to connect to your user. I hope you can do that now.
Try this, I used it in many websites, it works perfectly
Options +FollowSymLinks
RewriteEngine On
RewriteCond %{HTTP_HOST} ^bewebdeveloper.com$
RewriteRule ^(.*) http://www.bewebdeveloper.com/$1 [QSA,L,R=301]
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
Just press Ctrl + Shift + R and see...
In SQL Server Management Studio, Ctrl+Shift+R refreshes the local cache.
Here's a more recent and in depth analysis of Appcelerator and PhoneGap: http://savagelook.com/blog/portfolio/a-deeper-look-at-appcelerator-and-phonegap
And here's even more detail on how they differ programmatically: http://savagelook.com/blog/portfolio/phonegap-is-web-based-appcelerator-is-pure-javascript
That's probably as fast as you can do it in pure python for reasonably large inputs:
def choose(n, k):
if k == n: return 1
if k > n: return 0
d, q = max(k, n-k), min(k, n-k)
num = 1
for n in xrange(d+1, n+1): num *= n
denom = 1
for d in xrange(1, q+1): denom *= d
return num / denom
The negation pseudo-class seems to be what you are looking for.
table:not(.dojoxGrid) {color:red;}
For Ubuntu 14.04 and Android try:
hcitool scan #get hardware address
sudo bluetooth-agent PIN HARDWARE-ADDRESS
PIN dialog pops up on Android device. Enter same PIN.
Note: sudo apt-get install bluez-utils
might be necessary.
Note2: If PIN dialog does not appear, try pairing from Android first (will fail because of wrong PIN). Then try again as described above.
Try this: The data returned from SQL has to converted into a Dict.
or could it be "Pollutant Levels"
is now Pollutants'
StationID Pollutants
0 8809 {"a":"46","b":"3","c":"12"}
1 8810 {"a":"36","b":"5","c":"8"}
2 8811 {"b":"2","c":"7"}
3 8812 {"c":"11"}
4 8813 {"a":"82","c":"15"}
df2["Pollutants"] = df2["Pollutants"].apply(lambda x : dict(eval(x)) )
df3 = df2["Pollutants"].apply(pd.Series )
a b c
0 46 3 12
1 36 5 8
2 NaN 2 7
3 NaN NaN 11
4 82 NaN 15
result = pd.concat([df, df3], axis=1).drop('Pollutants', axis=1)
result
StationID a b c
0 8809 46 3 12
1 8810 36 5 8
2 8811 NaN 2 7
3 8812 NaN NaN 11
4 8813 82 NaN 15
Just wondering why you are using 2 directives?
It seems like, in this case it would be more straightforward to have a controller as the parent - handle adding the data from your service to its $scope, and pass the model you need from there into your warrantyDirective.
Or for that matter, you could use 0 directives to achieve the same result. (ie. move all functionality out of the separate directives and into a single controller).
It doesn't look like you're doing any explicit DOM transformation here, so in this case, perhaps using 2 directives is overcomplicating things.
Alternatively, have a look at the Angular documentation for directives: http://docs.angularjs.org/guide/directive The very last example at the bottom of the page explains how to wire up dependent directives.
I have found the metadata plugin to be an excellent solution to the problem of storing arbitrary data with the html tag in a way that makes it easy to retrieve and use with jQuery.
Important: The actual file you include is is only 5 kb and not 37 kb (which is the size of the complete download package)
Here is an example of it being used to store values I use when generating a google analytics tracking event (note: data.label and data.value happen to be optional params)
$(function () {
$.each($(".ga-event"), function (index, value) {
$(value).click(function () {
var data = $(value).metadata();
if (data.label && data.value) {
_gaq.push(['_trackEvent', data.category, data.action, data.label, data.value]);
} else if (data.label) {
_gaq.push(['_trackEvent', data.category, data.action, data.label]);
} else {
_gaq.push(['_trackEvent', data.category, data.action]);
}
});
});
});
<input class="ga-event {category:'button', action:'click', label:'test', value:99}" type="button" value="Test"/>
You can use VT100 escape codes. Most terminals, including xterm, are VT100 aware. For erasing a line, this is ^[[2K
. In C this gives:
printf("%c[2K", 27);
Bash 3 solution:
In reading some of the answers I put together a quick little function I would like to contribute back that might help others.
# Define a hash like this
MYHASH=("firstName:Milan"
"lastName:Adamovsky")
# Function to get value by key
getHashKey()
{
declare -a hash=("${!1}")
local key
local lookup=$2
for key in "${hash[@]}" ; do
KEY=${key%%:*}
VALUE=${key#*:}
if [[ $KEY == $lookup ]]
then
echo $VALUE
fi
done
}
# Function to get a list of all keys
getHashKeys()
{
declare -a hash=("${!1}")
local KEY
local VALUE
local key
local lookup=$2
for key in "${hash[@]}" ; do
KEY=${key%%:*}
VALUE=${key#*:}
keys+="${KEY} "
done
echo $keys
}
# Here we want to get the value of 'lastName'
echo $(getHashKey MYHASH[@] "lastName")
# Here we want to get all keys
echo $(getHashKeys MYHASH[@])
With ObsoleteAttribute
you can to show the deprecated method.
Obsolete attribute has three constructor:
[Obsolete]:
is a no parameter constructor and is a default using this attribute.[Obsolete(string message)]:
in this format you can getmessage
of why this method is deprecated.[Obsolete(string message, bool error)]:
in this format message is very explicit buterror
means, in compilation time, compiler must be showing error and cause to fail compiling or not.
For Sticky Footer we use two DIV's
in the HTML for basic sticky footer effect. Write like this:
HTML
<div class="container"></div>
<div class="footer"></div>
CSS
body,html {
height:100%;
}
.container {
min-height:100%;
}
.footer {
height:40px;
margin-top:-40px;
}
A slightly more generic powershell example. In powershell 7, the match is highlighted including the last space (can you highlight in stack?).
'a b c d e f ' | select-string '([a-f] ){6,}'
a b c d e f
They've bundled all the target/build configuration/debugging options stuff into "schemes". The transition guide has a good explanation.
Odeds answer is almost complete. Just one thing to add.
having this password="'; this sould be a valid connection string:
connectionString='Server=dbsrv;User ID=myDbUser;Password='"&&;'
I used an extension to UIViewController and a struct to make sure that my current view is presented from the favourites
1.Struct for a global Bool
struct PresentedFromFavourites {
static var comingFromFav = false}
2.UIVeiwController extension: presented modally as in the second option by "stefandouganhyde - Option 2 " and solving the back
extension UIViewController {
func returnToFavourites()
{
// you return to the storyboard wanted by changing the name
let storyBoard : UIStoryboard = UIStoryboard(name: "Main", bundle:nil)
let mainNavigationController = storyBoard.instantiateViewController(withIdentifier: "HomeNav") as! UINavigationController
// Set animated to false
let favViewController = storyBoard.instantiateViewController(withIdentifier: "Favourites")
self.present(mainNavigationController, animated: false, completion: {
mainNavigationController.pushViewController(favViewController, animated: false)
})
}
// call this function in viewDidLoad()
//
func addBackToFavouritesButton()
{
if PresentedFromFavourites.comingFromFav
{
//Create a button
// I found this good for most size classes
let buttonHeight = (self.navigationController?.navigationBar.frame.size.height)! - 15
let rect = CGRect(x: 2, y: 8, width: buttonHeight, height: buttonHeight)
let aButton = UIButton(frame: rect)
// Down a back arrow image from icon8 for free and add it to your image assets
aButton.setImage(#imageLiteral(resourceName: "backArrow"), for: .normal)
aButton.backgroundColor = UIColor.clear
aButton.addTarget(self, action:#selector(self.returnToFavourites), for: .touchUpInside)
self.navigationController?.navigationBar.addSubview(aButton)
PresentedFromFavourites.comingFromFav = false
}
}}
You can get a View's coordinates using getLocationOnScreen()
or getLocationInWindow()
Afterwards, x
and y
should be the top-left corner of the view. If your root layout is smaller than the screen (like in a Dialog), using getLocationInWindow
will be relative to its container, not the entire screen.
int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];
NOTE: If value is always 0, you are likely changing the view immediately before requesting location.
To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post
:
view.post(() -> {
// Values should no longer be 0
int[] point = new int[2];
view.getLocationOnScreen(point); // or getLocationInWindow(point)
int x = point[0];
int y = point[1];
});
~~
val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point
NOTE: If value is always 0, you are likely changing the view immediately before requesting location.
To ensure view has had a chance to update, run your location request after the View's new layout has been calculated by using view.post
:
view.post {
// Values should no longer be 0
val point = IntArray(2)
view.getLocationOnScreen(point) // or getLocationInWindow(point)
val (x, y) = point
}
I recommend creating an extension function for handling this:
// To use, call:
val (x, y) = view.screenLocation
val View.screenLocation get(): IntArray {
val point = IntArray(2)
getLocationOnScreen(point)
return point
}
And if you require reliability, also add:
view.screenLocationSafe { x, y -> Log.d("", "Use $x and $y here") }
fun View.screenLocationSafe(callback: (Int, Int) -> Unit) {
post {
val (x, y) = screenLocation
callback(x, y)
}
}
Completely removed from java 8 +
Partially removed from java 7 (interned Strings for example)
source
You can specify '-m32' or '-m64' to select the compilation mode.
When dealing with autoconf (configure) scripts, I usually set CC="gcc -m64" (or CC="gcc -m32") in the environment so that everything is compiled with the correct bittiness. At least, usually...people find endless ways to make that not quite work, but my batting average is very high (way over 95%) with it.
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
The window object represents an open window in a browser. Since you are not running your code within a browser, but via Windows Script Host, the interpreter won't be able to find the window object, since it does not exist, since you're not within a web browser.
You need to make sure that node
is in your PATH
. To set up your path, this out.
Make sure that the directory that has node.exe
is in your PATH
. Then you should be able to
run node path_to_js_file.js
.
For a good "Hello World" example, check out: http://howtonode.org/hello-node
Just want to let you guys know, the accepted answer doesn't always work.
Here's an example it will fail.
if <href='/list'>
href = $('css_selector').attr('href')
"/list"
href = document.querySelector('css_selector').href
"http://localhost/list"
or you could append the href you got from jQuery to this
href = document.URL +$('css_selector').attr('href');
or jQuery way
href = $('css_selector').prop('href')
Finally, invoke it to change the browser current page's url
window.location.href = href
or pop it out using window.open(url)
Here's an example in JSFiddle.
local_action
runs the command on the local server, not on the servers you specify in hosts
parameter.
Change your "Execute the script" task to
- name: Execute the script
command: sh /home/test_user/test.sh
and it should do it.
You don't need to repeat sudo in the command line because you have defined it already in the playbook.
According to Ansible Intro to Playbooks user
parameter was renamed to remote_user
in Ansible 1.4 so you should change it, too
remote_user: test_user
So, the playbook will become:
---
- name: Transfer and execute a script.
hosts: server
remote_user: test_user
sudo: yes
tasks:
- name: Transfer the script
copy: src=test.sh dest=/home/test_user mode=0777
- name: Execute the script
command: sh /home/test_user/test.sh
I've found the liquibase.database.typeconversion.core.AbstractTypeConverter
class.
It lists all types that can be used:
protected DataType getDataType(String columnTypeString, Boolean autoIncrement, String dataTypeName, String precision, String additionalInformation) {
// Translate type to database-specific type, if possible
DataType returnTypeName = null;
if (dataTypeName.equalsIgnoreCase("BIGINT")) {
returnTypeName = getBigIntType();
} else if (dataTypeName.equalsIgnoreCase("NUMBER") || dataTypeName.equalsIgnoreCase("NUMERIC")) {
returnTypeName = getNumberType();
} else if (dataTypeName.equalsIgnoreCase("BLOB")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("BOOLEAN")) {
returnTypeName = getBooleanType();
} else if (dataTypeName.equalsIgnoreCase("CHAR")) {
returnTypeName = getCharType();
} else if (dataTypeName.equalsIgnoreCase("CLOB")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("CURRENCY")) {
returnTypeName = getCurrencyType();
} else if (dataTypeName.equalsIgnoreCase("DATE") || dataTypeName.equalsIgnoreCase(getDateType().getDataTypeName())) {
returnTypeName = getDateType();
} else if (dataTypeName.equalsIgnoreCase("DATETIME") || dataTypeName.equalsIgnoreCase(getDateTimeType().getDataTypeName())) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("DOUBLE")) {
returnTypeName = getDoubleType();
} else if (dataTypeName.equalsIgnoreCase("FLOAT")) {
returnTypeName = getFloatType();
} else if (dataTypeName.equalsIgnoreCase("INT")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("INTEGER")) {
returnTypeName = getIntType();
} else if (dataTypeName.equalsIgnoreCase("LONGBLOB")) {
returnTypeName = getLongBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARBINARY")) {
returnTypeName = getBlobType();
} else if (dataTypeName.equalsIgnoreCase("LONGVARCHAR")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("SMALLINT")) {
returnTypeName = getSmallIntType();
} else if (dataTypeName.equalsIgnoreCase("TEXT")) {
returnTypeName = getClobType();
} else if (dataTypeName.equalsIgnoreCase("TIME") || dataTypeName.equalsIgnoreCase(getTimeType().getDataTypeName())) {
returnTypeName = getTimeType();
} else if (dataTypeName.toUpperCase().contains("TIMESTAMP")) {
returnTypeName = getDateTimeType();
} else if (dataTypeName.equalsIgnoreCase("TINYINT")) {
returnTypeName = getTinyIntType();
} else if (dataTypeName.equalsIgnoreCase("UUID")) {
returnTypeName = getUUIDType();
} else if (dataTypeName.equalsIgnoreCase("VARCHAR")) {
returnTypeName = getVarcharType();
} else if (dataTypeName.equalsIgnoreCase("NVARCHAR")) {
returnTypeName = getNVarcharType();
} else {
return new CustomType(columnTypeString,0,2);
}
Sending a POST request is easy in vanilla Java. Starting with a URL
, we need t convert it to a URLConnection
using url.openConnection();
. After that, we need to cast it to a HttpURLConnection
, so we can access its setRequestMethod()
method to set our method. We finally say that we are going to send data over the connection.
URL url = new URL("https://www.example.com/login");
URLConnection con = url.openConnection();
HttpURLConnection http = (HttpURLConnection)con;
http.setRequestMethod("POST"); // PUT is another valid option
http.setDoOutput(true);
We then need to state what we are going to send:
A normal POST coming from a http form has a well defined format. We need to convert our input to this format:
Map<String,String> arguments = new HashMap<>();
arguments.put("username", "root");
arguments.put("password", "sjh76HSn!"); // This is a fake password obviously
StringJoiner sj = new StringJoiner("&");
for(Map.Entry<String,String> entry : arguments.entrySet())
sj.add(URLEncoder.encode(entry.getKey(), "UTF-8") + "="
+ URLEncoder.encode(entry.getValue(), "UTF-8"));
byte[] out = sj.toString().getBytes(StandardCharsets.UTF_8);
int length = out.length;
We can then attach our form contents to the http request with proper headers and send it.
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
// Do something with http.getInputStream()
We can also send json using java, this is also easy:
byte[] out = "{\"username\":\"root\",\"password\":\"password\"}" .getBytes(StandardCharsets.UTF_8);
int length = out.length;
http.setFixedLengthStreamingMode(length);
http.setRequestProperty("Content-Type", "application/json; charset=UTF-8");
http.connect();
try(OutputStream os = http.getOutputStream()) {
os.write(out);
}
// Do something with http.getInputStream()
Remember that different servers accept different content-types for json, see this question.
Sending files can be considered more challenging to handle as the format is more complex. We are also going to add support for sending the files as a string, since we don't want to buffer the file fully into the memory.
For this, we define some helper methods:
private void sendFile(OutputStream out, String name, InputStream in, String fileName) {
String o = "Content-Disposition: form-data; name=\"" + URLEncoder.encode(name,"UTF-8")
+ "\"; filename=\"" + URLEncoder.encode(filename,"UTF-8") + "\"\r\n\r\n";
out.write(o.getBytes(StandardCharsets.UTF_8));
byte[] buffer = new byte[2048];
for (int n = 0; n >= 0; n = in.read(buffer))
out.write(buffer, 0, n);
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
private void sendField(OutputStream out, String name, String field) {
String o = "Content-Disposition: form-data; name=\""
+ URLEncoder.encode(name,"UTF-8") + "\"\r\n\r\n";
out.write(o.getBytes(StandardCharsets.UTF_8));
out.write(URLEncoder.encode(field,"UTF-8").getBytes(StandardCharsets.UTF_8));
out.write("\r\n".getBytes(StandardCharsets.UTF_8));
}
We can then use these methods to create a multipart post request as follows:
String boundary = UUID.randomUUID().toString();
byte[] boundaryBytes =
("--" + boundary + "\r\n").getBytes(StandardCharsets.UTF_8);
byte[] finishBoundaryBytes =
("--" + boundary + "--").getBytes(StandardCharsets.UTF_8);
http.setRequestProperty("Content-Type",
"multipart/form-data; charset=UTF-8; boundary=" + boundary);
// Enable streaming mode with default settings
http.setChunkedStreamingMode(0);
// Send our fields:
try(OutputStream out = http.getOutputStream()) {
// Send our header (thx Algoman)
out.write(boundaryBytes);
// Send our first field
sendField(out, "username", "root");
// Send a seperator
out.write(boundaryBytes);
// Send our second field
sendField(out, "password", "toor");
// Send another seperator
out.write(boundaryBytes);
// Send our file
try(InputStream file = new FileInputStream("test.txt")) {
sendFile(out, "identification", file, "text.txt");
}
// Finish the request
out.write(finishBoundaryBytes);
}
// Do something with http.getInputStream()
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
Basically what others have already posted but IMHO a bit cleaner:
$('<iframe/>', {
src: 'https://example.com/',
load: function() {
alert("loaded")
}
}).appendTo('body');
It looks that even if the driver 10.2 is compatible with the JDBC3 it may not work with JRE6 as I've found here:
http://www.oracle.com/technology/tech/java/sqlj_jdbc/htdocs/jdbc_faq.html#02_03
Which JDBC drivers support which versions of Javasoft's JDK?
pre-8i OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x
8.1.5 OCI and THIN Drivers - JDK 1.0.x and JDK 1.1.x
8.1.6SDK THIN Driver - JDK 1.1.x and JDK 1.2.x (aka Java2)
8.1.6SDK OCI Driver - Only JDK 1.1.x
8.1.6 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x
8.1.7 OCI and THIN Driver - JDK 1.1.x and JDK 1.2.x
9.0.1 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x and JDK 1.3.x
9.2.0 OCI and THIN Driver - JDK 1.1.x, JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x
10.1.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, and JDK 1.4.x
10.2.0 OCI and THIN Driver - JDK 1.2.x, JDK 1.3.x, JDK 1.4.x, and JDK 5.0.x
11.1.0 OCI and THIN Driver - JDK 1.5.x and JDK 1.6.x
Oracle 10.2.0 supports:
Full support for JDBC 3.0
Note that there is no real change in the support for the following in the database. Allthat has changed is that some methods that previously threw SQLException now do something more reasonable instead.
result-set holdability
returning multiple result-sets.
What you can try is to remove the map before initialising it or when you leave the page:
if(this.map) {
this.map.remove();
}
To draw Horizontal
************************
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4"/>
To draw vertical
*******************
<Rectangle HorizontalAlignment="Stretch" VerticalAlignment="Center" Fill="DarkCyan" Height="4" Width="Auto" >
<Rectangle.RenderTransform>
<TransformGroup>
<ScaleTransform/>
<SkewTransform/>
<RotateTransform Angle="90"/>
<TranslateTransform/>
</TransformGroup>
</Rectangle.RenderTransform>
</Rectangle>
I had the same problem, and all the solutions from SO or Google didn't work for me. Usually, setNeedsDisplay
does work, but when it doesn't...
I've tried calling setNeedsDisplay
of the view just every possible way from every possible threads and stuff - still no success. We know, as Rob said, that
"this needs to be drawn in the next draw cycle."
But for some reason it wouldn't draw this time. And the only solution I've found is calling it manually after some time, to let anything that blocks the draw pass away, like this:
dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW,
(int64_t)(0.005 * NSEC_PER_SEC));
dispatch_after(popTime, dispatch_get_main_queue(), ^(void) {
[viewToRefresh setNeedsDisplay];
});
It's a good solution if you don't need the view to redraw really often. Otherwise, if you're doing some moving (action) stuff, there is usually no problems with just calling setNeedsDisplay
.
I hope it will help someone who is lost there, like I was.
Now you can also use Talentsoft.Moq.SetupAsync package https://github.com/TalentSoft/Moq.SetupAsync
Which on the base on the answers found here and ideas proposed to Moq but still not yet implemented here: https://github.com/moq/moq4/issues/384, greatly simplify setup of async methods
Few examples found in previous responses done with SetupAsync extension:
mock.SetupAsync(arg=>arg.DoSomethingAsync());
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Callback(() => { <my code here> });
mock.SetupAsync(arg=>arg.DoSomethingAsync()).Throws(new InvalidOperationException());
If you need to just empty the style
of an element then:
element.style.cssText = null;
This should do good. Hope it helps!
I have written this article about the ICommand interface.
The idea - creating a universal command that takes two delegates: one is called when ICommand.Execute (object param)
is invoked, the second checks the status of whether you can execute the command (ICommand.CanExecute (object param))
.
Requires the method to switching event CanExecuteChanged
. It is called from the user interface elements for switching the state CanExecute()
command.
public class ModelCommand : ICommand
{
#region Constructors
public ModelCommand(Action<object> execute)
: this(execute, null) { }
public ModelCommand(Action<object> execute, Predicate<object> canExecute)
{
_execute = execute;
_canExecute = canExecute;
}
#endregion
#region ICommand Members
public event EventHandler CanExecuteChanged;
public bool CanExecute(object parameter)
{
return _canExecute != null ? _canExecute(parameter) : true;
}
public void Execute(object parameter)
{
if (_execute != null)
_execute(parameter);
}
public void OnCanExecuteChanged()
{
CanExecuteChanged(this, EventArgs.Empty);
}
#endregion
private readonly Action<object> _execute = null;
private readonly Predicate<object> _canExecute = null;
}
use this Reload page
success: function(data){
if(data.success == true){ // if true (1)
setTimeout(function(){// wait for 5 secs(2)
location.reload(); // then reload the page.(3)
}, 5000);
}
}
Your "listen" directives are wrong. See this page: http://nginx.org/en/docs/http/server_names.html.
They should be
server {
listen 80;
server_name www.domain1.com;
root /var/www/domain1;
}
server {
listen 80;
server_name www.domain2.com;
root /var/www/domain2;
}
Note, I have only included the relevant lines. Everything else looked okay but I just deleted it for clarity. To test it you might want to try serving a text file from each server first before actually serving php. That's why I left the 'root' directive in there.
Here is a more concise way to achieve the "less insecure" method proposed by CoolAJ86
request({
url: url,
agentOptions: {
rejectUnauthorized: false
}
}, function (err, resp, body) {
// ...
});
Sample Usage:
import paramiko
paramiko.util.log_to_file("paramiko.log")
# Open a transport
host,port = "example.com",22
transport = paramiko.Transport((host,port))
# Auth
username,password = "bar","foo"
transport.connect(None,username,password)
# Go!
sftp = paramiko.SFTPClient.from_transport(transport)
# Download
filepath = "/etc/passwd"
localpath = "/home/remotepasswd"
sftp.get(filepath,localpath)
# Upload
filepath = "/home/foo.jpg"
localpath = "/home/pony.jpg"
sftp.put(localpath,filepath)
# Close
if sftp: sftp.close()
if transport: transport.close()
If you have two or more field to order try this:
var soterdList = initialList.OrderBy(x => x.Priority).
ThenBy(x => x.ArrivalDate).
ThenBy(x => x.ShipDate);
You can add other fields with clasole "ThenBy"
No, not in the current one. But you can take a look at the next version by downloading it from github. It has vertical pills and tabs. Maybe that will help? (be aware, it's under construction tho)
For Spring 5.2+ this works for me:
@PostMapping("/foo")
ResponseEntity<Void> foo(@PathVariable UUID fooId) {
return fooService.findExam(fooId)
.map(uri -> ResponseEntity.noContent().<Void>build())
.orElse(ResponseEntity.notFound().build());
}
try to disable the rewrite module in ubuntu using sudo a2dismod rewrite
. This will perhaps stop your apache server to crash.
REM kill all existing instance of chrome
taskkill /F /IM chrome.exe /T
REM directory path where chrome.exe is located
set chromeLocation="C:\Program Files (x86)\Google\Chrome\Application"
cd %chromeLocation%
cd c:
start chrome.exe --allow-file-access-from-files
change chromeLocation path with yours.
save above as .bat file.
drag drop you file on the batch file you created. (chrome does give restore pages option though so if you have pages open just hit restore and it will work).
I love @bill-hoenig 's answer; however, I was using a subquery and I got caught up because the REVERSE function needed two sets of parentheses. Took me a while to figure that one out!
SELECT
-- Return comma delimited list of all payment reasons for this Visit
REVERSE(STUFF(REVERSE((
SELECT DISTINCT
CAST(CONVERT(varchar, r1.CodeID) + ' - ' + c.Name + ', ' AS VARCHAR(MAX))
FROM VisitReason r1
LEFT JOIN ReasonCode c ON c.ID = r1.ReasonCodeID
WHERE p.ID = r1.PaymentID
FOR XML PATH('')
)), 1, 2, '')) ReasonCode
FROM Payments p
Not sure how you want to represent the tree? Anyway here's an example which scans the entire subtree using recursion. Files and directories are treated alike. Note that File.listFiles() returns null for non-directories.
public static void main(String[] args) {
Collection<File> all = new ArrayList<File>();
addTree(new File("."), all);
System.out.println(all);
}
static void addTree(File file, Collection<File> all) {
File[] children = file.listFiles();
if (children != null) {
for (File child : children) {
all.add(child);
addTree(child, all);
}
}
}
Java 7 offers a couple of improvements. For example, DirectoryStream provides one result at a time - the caller no longer has to wait for all I/O operations to complete before acting. This allows incremental GUI updates, early cancellation, etc.
static void addTree(Path directory, Collection<Path> all)
throws IOException {
try (DirectoryStream<Path> ds = Files.newDirectoryStream(directory)) {
for (Path child : ds) {
all.add(child);
if (Files.isDirectory(child)) {
addTree(child, all);
}
}
}
}
Note that the dreaded null return value has been replaced by IOException.
Java 7 also offers a tree walker:
static void addTree(Path directory, final Collection<Path> all)
throws IOException {
Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs)
throws IOException {
all.add(file);
return FileVisitResult.CONTINUE;
}
});
}
For Windows 8 and Windows Server 2012 use dism /online /enable-feature /featurename:IIS-ASPNET45
As administrative command prompt.
You can generate easily with livegap charts
Select Mulicolors from Bar menu
(source: livegap.com)
** chart library used is chartnew.js modified version of chart.js library
with chartnew.js code will be something like this
var barChartData = {
labels: ["001", "002", "003", "004", "005", "006", "007"],
datasets: [
{
label: "My First dataset",
fillColor: ["rgba(0,10,220,0.5)","rgba(220,0,10,0.5)","rgba(220,0,0,0.5)","rgba(120,250,120,0.5)" ],
strokeColor: "rgba(220,220,220,0.8)",
highlightFill: "rgba(220,220,220,0.75)",
highlightStroke: "rgba(220,220,220,1)",
data: [20, 59, 80, 81, 56, 55, 40]
}
]
};
Adding to Jacks solution. I need to Deserialize using the JsonProperty and Serialize while ignoring the JsonProperty (or vice versa). ReflectionHelper and Attribute Helper are just helper classes that get a list of properties or attributes for a property. I can include if anyone actually cares. Using the example below you can serialize the viewmodel and get "Amount" even though the JsonProperty is "RecurringPrice".
/// <summary>
/// Ignore the Json Property attribute. This is usefule when you want to serialize or deserialize differently and not
/// let the JsonProperty control everything.
/// </summary>
/// <typeparam name="T"></typeparam>
public class IgnoreJsonPropertyResolver<T> : DefaultContractResolver
{
private Dictionary<string, string> PropertyMappings { get; set; }
public IgnoreJsonPropertyResolver()
{
this.PropertyMappings = new Dictionary<string, string>();
var properties = ReflectionHelper<T>.GetGetProperties(false)();
foreach (var propertyInfo in properties)
{
var jsonProperty = AttributeHelper.GetAttribute<JsonPropertyAttribute>(propertyInfo);
if (jsonProperty != null)
{
PropertyMappings.Add(jsonProperty.PropertyName, propertyInfo.Name);
}
}
}
protected override string ResolvePropertyName(string propertyName)
{
string resolvedName = null;
var resolved = this.PropertyMappings.TryGetValue(propertyName, out resolvedName);
return (resolved) ? resolvedName : base.ResolvePropertyName(propertyName);
}
}
Usage:
var settings = new JsonSerializerSettings();
settings.DateFormatString = "YYYY-MM-DD";
settings.ContractResolver = new IgnoreJsonPropertyResolver<PlanViewModel>();
var model = new PlanViewModel() {Amount = 100};
var strModel = JsonConvert.SerializeObject(model,settings);
Model:
public class PlanViewModel
{
/// <summary>
/// The customer is charged an amount over an interval for the subscription.
/// </summary>
[JsonProperty(PropertyName = "RecurringPrice")]
public double Amount { get; set; }
/// <summary>
/// Indicates the number of intervals between each billing. If interval=2, the customer would be billed every two
/// months or years depending on the value for interval_unit.
/// </summary>
public int Interval { get; set; } = 1;
/// <summary>
/// Number of free trial days that can be granted when a customer is subscribed to this plan.
/// </summary>
public int TrialPeriod { get; set; } = 30;
/// <summary>
/// This indicates a one-time fee charged upfront while creating a subscription for this plan.
/// </summary>
[JsonProperty(PropertyName = "SetupFee")]
public double SetupAmount { get; set; } = 0;
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "TypeId")]
public string Type { get; set; }
/// <summary>
/// Billing Frequency
/// </summary>
[JsonProperty(PropertyName = "BillingFrequency")]
public string Period { get; set; }
/// <summary>
/// String representing the type id, usually a lookup value, for the record.
/// </summary>
[JsonProperty(PropertyName = "PlanUseType")]
public string Purpose { get; set; }
}
If you are a Windows user, this is a common error when you use XAMPP
since LDAP
is not enabled by default.
You can follow this steps to make sure LDAP
works in your XAMPP
:
[Your Drive]:\xampp\php\php.ini
: In this file uncomment the following line:
extension=php_ldap.dll
Move the file: libsasl.dll
, from [Your Drive]:\xampp\php
to [Your Drive]:\xampp\apache\bin
(Note: moving the file is needed only for XAMPP prior to version: 5.6.28
)
Restart Apache.
You can now use functions of the LDAP Module!
If you use Linux:
For php5:
sudo apt-get install php5-ldap
For php7:
sudo apt-get install php7.0-ldap
If you are using the latest version of PHP you can do
sudo apt-get install php-ldap
running the above command should do the trick.
if for any reason it doesn't work check your php.ini configuration to enable ldap, remove the semicolon before extension=ldap
to uncomment, save and restart Apache
Required arguments (the ones without defaults), must be at the start to allow client code to only supply two. If the optional arguments were at the start, it would be confusing:
fun1("who is who", 3, "jack")
What would that do in your first example? In the last, x is "who is who", y is 3 and a = "jack".
function doParseCSVFile($filesArray)
{
if ((file_exists($filesArray['frmUpload']['name'])) && (is_readable($filesArray['frmUpload']['name']))) {
$strFilePath = $filesArray['frmUpload']['tmp_name'];
$strFileHandle = fopen($strFilePath,"r");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
$line_of_text = fgetcsv($strFileHandle,1024,",","'");
do {
if ($line_of_text[0]) {
$strInsertSql = "INSERT INTO tbl_employee(employee_name, employee_code, employee_email, employee_designation, employee_number)VALUES('".addslashes($line_of_text[0])."', '".$line_of_text[1]."', '".addslashes($line_of_text[2])."', '".$line_of_text[3]."', '".$line_of_text[4]."')";
ExecuteQry($strInsertSql);
}
} while (($line_of_text = fgetcsv($strFileHandle,1024,",","'"))!== FALSE);
} else {
return FALSE;
}
}
You can use MySQL Table Data Import Wizard
Yes You can have more than one Class in one .Java file . But You have make one of them Public . and save .java file with same name as name of public class. when you will compile that .java file than you will get Separate .class files for each class defined in .java file .
Apart from this there are too many method for defining more than one class in one .java file .
There is not an equivalent statement for export in Windows Command Prompt. In Windows the environment is copied so when you exit from the session (from a called command prompt or from an executable that set a variable) the variable in Windows get lost. You can set it in user registry or in machine registry via setx but you won't see it if you not start a new command prompt.
Is your logic not round the wrong way in that example, you have it hiding when the screen is bigger than 1024. Reverse the cases, make the none
in to a block
and vice versa.
For Python Run This Command
apt-get install -y python-setuptools
For Python 3.
apt-get install -y python3-setuptools
I wanted to put cursor at the end of a "div" element where contenteditable = true, and I got a solution with Xeoncross code:
<input type="button" value="Paste HTML" onclick="document.getElementById('test').focus(); pasteHtmlAtCaret('<b>INSERTED</b>'); ">
<div id="test" contenteditable="true">
Here is some nice text
</div>
And this function do magic:
function pasteHtmlAtCaret(html) {
var sel, range;
if (window.getSelection) {
// IE9 and non-IE
sel = window.getSelection();
if (sel.getRangeAt && sel.rangeCount) {
range = sel.getRangeAt(0);
range.deleteContents();
// Range.createContextualFragment() would be useful here but is
// non-standard and not supported in all browsers (IE9, for one)
var el = document.createElement("div");
el.innerHTML = html;
var frag = document.createDocumentFragment(), node, lastNode;
while ( (node = el.firstChild) ) {
lastNode = frag.appendChild(node);
}
range.insertNode(frag);
// Preserve the selection
if (lastNode) {
range = range.cloneRange();
range.setStartAfter(lastNode);
range.collapse(true);
sel.removeAllRanges();
sel.addRange(range);
}
}
} else if (document.selection && document.selection.type != "Control") {
// IE < 9
document.selection.createRange().pasteHTML(html);
}
}
Works fine for most browsers, please check it, this code puts text and put focus at the end of the text in div element (not input element)
https://jsfiddle.net/Xeoncross/4tUDk/
Thanks, Xeoncross
Select-Object creates a new psobject and copies the properties you requested to it. You can verify this with GetType():
PS > $a.GetType().fullname
System.DayOfWeek
PS > $b.GetType().fullname
System.Management.Automation.PSCustomObject
Expanding on scrappedocola/renergy's idea, you can turn the JavaScript into a bookmarklet that executes against the javascript:
uri so the code can be re-used easily across multiple pages without having to open up the dev tools or keep anything on your clipboard.
Just run the following snippet and drag the link to your bookmarks/favorites bar:
<a href="javascript: var el = document.querySelectorAll('style,link');_x000D_
for (var i=0; i<el.length; i++) {_x000D_
el[i].parentNode.removeChild(el[i]); _x000D_
};">_x000D_
Remove Styles _x000D_
</a>
_x000D_
getElementsByTagName('*')
and have to check and act on each individually.$('style,link[rel="stylesheet"]').remove()
when the extra javascript is not overwhelmingly cumbersome.CASE might help you out:
SELECT t.first_name,
t.last_name,
t.employid,
t.status
FROM employeetable t
WHERE t.status = (CASE WHEN status_flag = STATUS_ACTIVE THEN 'A'
WHEN status_flag = STATUS_INACTIVE THEN 'T'
ELSE null END)
AND t.business_unit = (CASE WHEN source_flag = SOURCE_FUNCTION THEN 'production'
WHEN source_flag = SOURCE_USER THEN 'users'
ELSE null END)
AND t.first_name LIKE firstname
AND t.last_name LIKE lastname
AND t.employid LIKE employeeid;
The CASE statement evaluates multiple conditions to produce a single value. So, in the first usage, I check the value of status_flag, returning 'A', 'T' or null depending on what it's value is, and compare that to t.status. I do the same for the business_unit column with a second CASE statement.
Note that when using "git log -n 1 [branch_name]" option. -n returns only one line of log but order in which this is returned is not guaranteed. Following is extract from git-log man page
.....
.....
Commit Limiting
Besides specifying a range of commits that should be listed using the special notations explained in the description, additional commit limiting may be applied.
Using more options generally further limits the output (e.g. --since=<date1> limits to commits newer than <date1>, and using it with --grep=<pattern> further limits to commits whose log message has a line that matches <pattern>), unless otherwise noted.
Note that these are applied before commit ordering and formatting options, such as --reverse.
-<number>
-n <number>
.....
.....
I made a sketchy benchmark on the three methods described in other responses.
Obviously pre-allocating the slice before pulling the keys is faster than append
ing, but surprisingly, the reflect.ValueOf(m).MapKeys()
method is significantly slower than the latter:
? go run scratch.go
populating
filling 100000000 slots
done in 56.630774791s
running prealloc
took: 9.989049786s
running append
took: 18.948676741s
running reflect
took: 25.50070649s
Here's the code: https://play.golang.org/p/Z8O6a2jyfTH (running it in the playground aborts claiming that it takes too long, so, well, run it locally.)
ExecuteScalar()
is what you need here
pandas
uses matplotlib
for basic dataframe plots. So, if you are using pandas
for basic plot you can use matplotlib for plot customization. However, I propose an alternative method here using seaborn
which allows more customization of the plot while not going into the basic level of matplotlib
.
Working Code:
import pandas as pd
import seaborn as sns
values = [[1, 2], [2, 5]]
df2 = pd.DataFrame(values, columns=['Type A', 'Type B'],
index=['Index 1', 'Index 2'])
ax= sns.lineplot(data=df2, markers= True)
ax.set(xlabel='xlabel', ylabel='ylabel', title='Video streaming dropout by category')
Use Array.CreateInstance
to create an array dynamically.
private Update BuildMetaData(MetaData[] nvPairs)
{
Update update = new Update();
InputProperty[] ip = Array.CreateInstance(typeof(InputProperty), nvPairs.Count()) as InputProperty[];
int i;
for (i = 0; i < nvPairs.Length; i++)
{
if (nvPairs[i] == null) break;
ip[i] = new InputProperty();
ip[i].Name = "udf:" + nvPairs[i].Name;
ip[i].Val = nvPairs[i].Value;
}
update.Items = ip;
return update;
}
Renders a view and sends the rendered HTML string to the client.
res.render('index');
Or
res.render('index', function(err, html) {
if(err) {...}
res.send(html);
});
DOCS HERE: https://expressjs.com/en/api.html#res.render
We can use replace
to change the values in 'mpg' to NA
that corresponds to cyl==4
.
mtcars %>%
mutate(mpg=replace(mpg, cyl==4, NA)) %>%
as.data.frame()
You can also use CopyTo:
var ms = new MemoryStream();
yourStreamReader.BaseStream.CopyTo(ms); // blocking call till the end of the stream
ms.GetBuffer().CopyTo(yourArray, ms.Length);
or
var ms = new MemoryStream();
var ct = yourStreamReader.BaseStream.CopyToAsync(ms);
await ct;
ms.GetBuffer().CopyTo(yourArray, ms.Length);
I ended up recording a Macro to save and compile in one step, and keymap Ctrl+s
to it.
By default git push
updates all the remote branches. But you can configure git to update only the current branch to it's upstream.
git config push.default upstream
It means git will update only the current (checked out) branch when you do git push.
Other valid options are:
nothing
: Do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.matching
: Push all branches having the same name on both ends. (default option prior to Ver 1.7.11) upstream
: Push the current branch to its upstream
branch. This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow). No need to have the same name for local and remote branch.tracking
: Deprecated, use upstream
instead.current
: Push the current branch to the remote branch of the same name on the receiving end. Works in both central and non-central workflows.simple
: [available since Ver 1.7.11] in centralized workflow, work like upstream
with an added safety to refuse to push if the upstream branch’s name is different from the local one. When pushing to a remote that is different from the remote you normally pull from, work as current
. This is the safest option and is suited for beginners. This mode has become the default in Git 2.0.(Let's just all agree that TreeView is obviously busted in respect to this problem. Binding to SelectedItem would have been obvious. Sigh)
I needed the solution to interact properly with the IsSelected property of TreeViewItem, so here's how I did it:
// the Type CustomThing needs to implement IsSelected with notification
// for this to work.
public class CustomTreeView : TreeView
{
public CustomThing SelectedCustomThing
{
get
{
return (CustomThing)GetValue(SelectedNode_Property);
}
set
{
SetValue(SelectedNode_Property, value);
if(value != null) value.IsSelected = true;
}
}
public static DependencyProperty SelectedNode_Property =
DependencyProperty.Register(
"SelectedCustomThing",
typeof(CustomThing),
typeof(CustomTreeView),
new FrameworkPropertyMetadata(
null,
FrameworkPropertyMetadataOptions.None,
SelectedNodeChanged));
public CustomTreeView(): base()
{
this.SelectedItemChanged += new RoutedPropertyChangedEventHandler<object>(SelectedItemChanged_CustomHandler);
}
void SelectedItemChanged_CustomHandler(object sender, RoutedPropertyChangedEventArgs<object> e)
{
SetValue(SelectedNode_Property, SelectedItem);
}
private static void SelectedNodeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
var treeView = d as CustomTreeView;
var newNode = e.NewValue as CustomThing;
treeView.SelectedCustomThing = (CustomThing)e.NewValue;
}
}
With this XAML:
<local:CustonTreeView ItemsSource="{Binding TreeRoot}"
SelectedCustomThing="{Binding SelectedNode,Mode=TwoWay}">
<TreeView.ItemContainerStyle>
<Style TargetType="TreeViewItem">
<Setter Property="IsSelected" Value="{Binding IsSelected, Mode=TwoWay}" />
</Style>
</TreeView.ItemContainerStyle>
</local:CustonTreeView>
You should be using datetime.datetime.strptime
. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime
; use time.strptime
in that case.
http://wiki.answers.com/Q/Does_Google_Chrome_support_ActiveX
Google Chrome comes with an ActiveX shim, as part of its default plugin array. So Google Chrome features at least partial support for ActiveX controls (as do many non-Internet Explorer browsers). I can't find information as to whether or not this includes support for ActiveX security certificates or the like, nor if/where such plugins can be controlled, within the browser.
..... Note that to enable the plug-in you must run Chrome with the following switch " --allow-all-activex" So in shortcut that is used to start up Chrome, add this after "Chrome.exe"
You may use the padding and margin shorthand Bootstrap 4 classes as follows:
For extra small devices i.e. xs
{property}{sides}-{size}
For other devices/viewports (small, medium, large and extra large)
{property}{sides}-{breakpoint}-{size}
Where:
property = m for margin and p for padding
Following are sides shorthand meanings:
l = defines the left-margin or left-padding
r = defines the right-margin or right-padding
t = defines the top-margin or top-padding
b = defines the bottom-margin or right-padding
x = For setting left and right padding and margins by the single call
y = For setting top and bottom margins
blank = margin and padding for all sides
The breakpoint = sm, md, lg, and xl.
Combining all the above, the left padding complete code can be (for example):
For left padding in extra small devices
pl-2
or for medium to extra large
pl-md-2
A stateful server keeps state between connections. A stateless server does not.
So, when you send a request to a stateful server, it may create some kind of connection object that tracks what information you request. When you send another request, that request operates on the state from the previous request. So you can send a request to "open" something. And then you can send a request to "close" it later. In-between the two requests, that thing is "open" on the server.
When you send a request to a stateless server, it does not create any objects that track information regarding your requests. If you "open" something on the server, the server retains no information at all that you have something open. A "close" operation would make no sense, since there would be nothing to close.
HTTP and NFS are stateless protocols. Each request stands on its own.
Sometimes cookies are used to add some state to a stateless protocol. In HTTP (web pages), the server sends you a cookie and then the browser holds the state, only to send it back to the server on a subsequent request.
SMB is a stateful protocol. A client can open a file on the server, and the server may deny other clients access to that file until the client closes it.
Prepare the byte array to send:
ByteArrayOutputStream bos = new ByteArrayOutputStream();
ObjectOutputStream out = null;
try {
out = new ObjectOutputStream(bos);
out.writeObject(yourObject);
out.flush();
byte[] yourBytes = bos.toByteArray();
...
} finally {
try {
bos.close();
} catch (IOException ex) {
// ignore close exception
}
}
Create an object from a byte array:
ByteArrayInputStream bis = new ByteArrayInputStream(yourBytes);
ObjectInput in = null;
try {
in = new ObjectInputStream(bis);
Object o = in.readObject();
...
} finally {
try {
if (in != null) {
in.close();
}
} catch (IOException ex) {
// ignore close exception
}
}
If you have the .a file of your shared library (.so) you can simply include it with its full path as if it was an object file, like this:
This generates main.o by just compiling:
gcc -c main.c
This links that object file with the corresponding static library and creates the executable (named "main"):
gcc main.o mylibrary.a -o main
Or in a single command:
gcc main.c mylibrary.a -o main
It could also be an absolute or relative path:
gcc main.c /usr/local/mylibs/mylibrary.a -o main
Seems most logical to use a filter/index combo:
names=[{}, {'name': 'Tom'},{'name': 'Tony'}]
names.index(filter(lambda n: n.get('name') == 'Tom', names)[0])
1
And if you think there could be multiple matches:
[names.index(n) for item in filter(lambda n: n.get('name') == 'Tom', names)]
[1]
A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.
from contextlib import contextmanager
import pandas as pd
@contextmanager
def open_file(path, mode):
file_to=open(path,mode)
yield file_to
file_to.close()
##later
saved_df=pd.DataFrame(data)
with open_file('yourcsv.csv','r') as infile:
saved_df.to_csv('yourcsv.csv',mode='a',header=False)`
//Set fixed border
yourForm.FormBorderStyle = System.Windows.Forms.FormBorderStyle.Fixed3D
//Set the state of your form to maximized
yourForm.WindowState = FormWindowState.Maximized
//Disable the minimize box and the maximize box
yourForm.MinimizeBox = False
yourForm.MaximizeBox = False
I was faced with the same challenge, especially when importing multiple files, this is how I managed to overcome it.
import os, sys
from os.path import dirname, join, abspath
sys.path.insert(0, abspath(join(dirname(__file__), '..')))
from root_folder import file_name
A CTE worked for me:
with cte as (
select 1 col1
from temptable
group by column_1
)
select COUNT(col1)
from cte;
Try the change event and selected selector
$('#jobSel').change(function(){
var optId = $(this).find('option:selected').attr('id')
})
You need to build a custom class-loader to do this or a third-party library that supports this. Your best bet is to extract the jar from the runtime and add them to the classpath (or have them already added to the classpath).
As mentioned before, the use of x(end+1) = newElem
has the advantage that it allows you to concatenate your vector with a scalar, regardless of whether your vector is transposed or not. Therefore it is more robust for adding scalars.
However, what should not be forgotten is that x = [x newElem]
will also work when you try to add multiple elements at once. Furthermore, this generalizes a bit more naturally to the case where you want to concatenate matrices. M = [M M1 M2 M3]
All in all, if you want a solution that allows you to concatenate your existing vector x
with newElem
that may or may not be a scalar, this should do the trick:
x(end+(1:numel(newElem)))=newElem
Whatever approach you take, make sure in the end that you have an updated version of curl and libcurl. You can do curl --version
and see the versions.
Here's what I did to get the latest curl version installed in Ubuntu:
sudo add-apt-repository "deb http://mirrors.kernel.org/ubuntu wily main"
sudo apt-get update
sudo apt-get install curl
You can access your session variable like '<%= Session["VariableName"]%>'
the text in single quotes will give session value. 1)
<script>
var session ='<%= Session["VariableName"]%>'
</script>
2) you can take a hidden field and assign value at server;
hiddenfield.value= session["xyz"].tostring();
//and in script you access the hiddenfield like
alert(document.getElementbyId("hiddenfield").value);
Try to use "#" before and after of the date and be sure of your system date format. maybe "YYYYMMDD O YYYY-MM-DD O MM-DD-YYYY O USING '/ O \' "
Ex:
select id,numbers_from,created_date,amount_numbers,SMS_text
from Test_Table
where
created_date <= #2013-04-12#
Use TimeSpan.Parse
to convert the string
http://msdn.microsoft.com/en-us/library/system.timespan.parse(v=vs.110).aspx
I always write it like this:
var foo:string;
if(!foo){
foo="something";
}
This will work fine and I think it's very readable.
If you are running the container as a service
using docker swarm
, you can do:
docker service update --env-add <you environment variable> <service_name>
Also remove using --env-rm
To make sure it's addedd as you wanted, just run:
docker exec -it <container id> env
It is not htop-like, but you could use atop. However, to display disk activity per process, it needs a kernel patch (available from the site). These kernel patches are now obsoleted, only to show per-process network activity an optional module is provided.
Try:
java -cp . Echo "hello"
Assuming that you compiled with:
javac Echo.java
Then there is a chance that the "current" directory is not in your classpath ( where java looks for .class definitions )
If that's the case and listing the contents of your dir displays:
Echo.java
Echo.class
Then any of this may work:
java -cp . Echo "hello"
or
SET CLASSPATH=%CLASSPATH;.
java Echo "hello"
And later as Fredrik points out you'll get another error message like.
Exception in thread "main" java.lang.NoSuchMethodError: main
When that happens, go and read his answer :)
break
will stop the current loop (or pass an integer to tell it how many loops to break from).
continue
will stop the current iteration and start the next one.
```javascript
{ "some": "json" }
```
I tried using json
but didn't like the way it looked. javascript
looks a bit more pleasing to my eye.
Ive come across this many times in my work, an easy work around that I found is to ask if the array element is a Hash by class.
if i.class == Hash
notation like i[:label] will work in this block and not throw that error
end
If your div rule is just div {...}
, then #a {...}
will be sufficient. If it is more complicated, you need a "more specific" selector, as defined by the CSS specification on specificity. (#a being more specific than div is just single aspect in the algorithm.)
I have an intelligent function-call-backing button code:
<br>
<p id="demo"></p><h2>Intelligent Button:</h2><i>Note: Try pressing a key after clicking.</i><br>
<button id="button" shiftKey="getElementById('button').innerHTML=('You're pressing shift, aren't you?')" onscroll="getElementById('button').innerHTML=('Don't Leave me!')" onkeydown="getElementById('button').innerHTML=('Why are you pressing keys?')" onmouseout="getElementById('button').innerHTML=('Whatever, it is gone.. maybe')" onmouseover="getElementById('button').innerHTML=('Something Is Hovering Over Me.. again')" onclick="getElementById('button').innerHTML=('I was clicked, I think')">Ahhhh</button>
For a production system, you can use this configuration :
--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT CONNECT ON DATABASE nova TO user;
--ACCESS SCHEMA
REVOKE ALL ON SCHEMA public FROM PUBLIC;
GRANT USAGE ON SCHEMA public TO user;
--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL ON ALL TABLES IN SCHEMA public TO admin ;
You can select every column from that sub-query by aliasing it and adding the alias before the *
:
SELECT t.*, a+b AS total_sum
FROM
(
SELECT SUM(column1) AS a, SUM(column2) AS b
FROM table
) t
PHP runs on the server-side thus you have to use a client-side technology which is capable of showing popup windows: JavaScript.
So you should output a specific JS block via PHP if your form contains errors and you want to show that popup.
I know I'm uprising a very old topic, but after a couple of hours struggling with this very problem and not finding a solution anywhere else, I think this is a good place to put an answer.
We have some Build Servers WindowsXP based and found this very problem: svn command line client is not caching auth credentials.
We finally found out that we are using Cygwin's svn client! not a "native" Windows. So... this client stores all the auth credentials in /home/<user>/.subversion/auth
This /home directory in Cygwin, in our installation is in c:\cygwin\home. AND: the problem was that the Windows user that is running svn did never ever "logged in" in Cygwin, and so there was no /home/<user> directory.
A simple "bash -ls" from a Windows command terminal created the directory, and after the first access to our SVN server with interactive prompting for access credentials, alás, they got cached.
So if you are using Cygwin's svn client, be sure to have a "home" directory created for the local Windows user.
You've got a couple of issues here.
Firstly, you're defining your code within an anonymous function. This construct:
(function() {
...
)();
does two things. It defines an anonymous function and calls it. There are scope reasons to do this but I'm not sure it's what you actually want.
You're passing in a code block to setTimeout()
. The problem is that update()
is not within scope when executed like that. It however if you pass in a function pointer instead so this works:
(function() {
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
)();
because the function pointer update
is within scope of that block.
But like I said, there is no need for the anonymous function so you can rewrite it like this:
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout(update, 1000); }
}
or
$(document).ready(function() {update();});
function update() {
$("#board").append(".");
setTimeout('update()', 1000); }
}
and both of these work. The second works because the update()
within the code block is within scope now.
I also prefer the $(function() { ... }
shortened block form and rather than calling setTimeout()
within update()
you can just use setInterval()
instead:
$(function() {
setInterval(update, 1000);
});
function update() {
$("#board").append(".");
}
Hope that clears that up.
Since the original solution is:
temp = x; y = x; x = temp;
You can make it a two liner by using:
temp = x; y = y + temp -(x=y);
Then make it a one liner by using:
x = x + y -(y=x);
According to the Android developers guide for android.hardware.Camera
, they state:
We recommend using the new android.hardware.camera2 API for new applications.
On the information page about android.hardware.camera2
, (linked above), it is stated:
The android.hardware.camera2 package provides an interface to individual camera devices connected to an Android device. It replaces the deprecated Camera class.
When you check that documentation you'll find that the implementation of these 2 Camera API's are very different.
For example getting camera orientation on android.hardware.camera
@Override
public int getOrientation(final int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
Versus android.hardware.camera2
@Override
public int getOrientation(final int cameraId) {
try {
CameraManager manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
// TODO handle error properly or pass it on
return 0;
}
}
This makes it hard to switch from one to another and write code that can handle both implementations.
Note that in this single code example I already had to work around the fact that the olde camera API works with int
primitives for camera IDs while the new one works with String
objects. For this example I quickly fixed that by using the int as an index in the new API. If the camera's returned aren't always in the same order this will already cause issues. Alternative approach is to work with String objects and String representation of the old int cameraIDs which is probably safer.
Now to work around this huge difference you can implement an interface first and reference that interface in your code.
Here I'll list some code for that interface and the 2 implementations. You can limit the implementation to what you actually use of the camera API to limit the amount of work.
In the next section I'll quickly explain how to load one or another.
The interface wrapping all you need, to limit this example I only have 2 methods here.
public interface CameraSupport {
CameraSupport open(int cameraId);
int getOrientation(int cameraId);
}
Now have a class for the old camera hardware api:
@SuppressWarnings("deprecation")
public class CameraOld implements CameraSupport {
private Camera camera;
@Override
public CameraSupport open(final int cameraId) {
this.camera = Camera.open(cameraId);
return this;
}
@Override
public int getOrientation(final int cameraId) {
Camera.CameraInfo info = new Camera.CameraInfo();
Camera.getCameraInfo(cameraId, info);
return info.orientation;
}
}
And another one for the new hardware api:
public class CameraNew implements CameraSupport {
private CameraDevice camera;
private CameraManager manager;
public CameraNew(final Context context) {
this.manager = (CameraManager) context.getSystemService(Context.CAMERA_SERVICE);
}
@Override
public CameraSupport open(final int cameraId) {
try {
String[] cameraIds = manager.getCameraIdList();
manager.openCamera(cameraIds[cameraId], new CameraDevice.StateCallback() {
@Override
public void onOpened(CameraDevice camera) {
CameraNew.this.camera = camera;
}
@Override
public void onDisconnected(CameraDevice camera) {
CameraNew.this.camera = camera;
// TODO handle
}
@Override
public void onError(CameraDevice camera, int error) {
CameraNew.this.camera = camera;
// TODO handle
}
}, null);
} catch (Exception e) {
// TODO handle
}
return this;
}
@Override
public int getOrientation(final int cameraId) {
try {
String[] cameraIds = manager.getCameraIdList();
CameraCharacteristics characteristics = manager.getCameraCharacteristics(cameraIds[cameraId]);
return characteristics.get(CameraCharacteristics.SENSOR_ORIENTATION);
} catch (CameraAccessException e) {
// TODO handle
return 0;
}
}
}
Now to load either your CameraOld
or CameraNew
class you'll have to check the API level since CameraNew
is only available from api level 21.
If you have dependency injection set up already you can do so in your module when providing the CameraSupport
implementation. Example:
@Module public class CameraModule {
@Provides
CameraSupport provideCameraSupport(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
return new CameraNew(context);
} else {
return new CameraOld();
}
}
}
If you don't use DI you can just make a utility or use Factory pattern to create the proper one. Important part is that the API level is checked.
The best solution is to create a new branch with --orphan
option as shown below
git checkout --orphan <branch name>
By this you will be able to create a new branch and directly checkout to the new branch. It will be a parentless branch.
By default the --orphan
option doesn't remove the files in the working directory, so you can delete the working directory files by this:
git rm --cached -r
--orphan
does:
--orphan <new_branch>
Create a new orphan branch, named<new_branch>
, started from<start_point>
and switch to it. The first commit made on this new branch will have no parents and it will be the root of a new history totally disconnected from all the other branches and commits.
The index and the working tree are adjusted as if you had previously run git checkout <start_point>. This allows you to start a new history that records a set of paths similar to <start_point> by easily running git commit -a to make the root commit.
This can be useful when you want to publish the tree from a commit without exposing its full history. You might want to do this to publish an open source branch of a project whose current tree is "clean", but whose full history contains proprietary or otherwise encumbered bits of code.
If you want to start a disconnected history that records a set of paths that is totally different from the one of <start_point>, then you should clear the index and the working tree right after creating the orphan branch by running git rm -rf . from the top level of the working tree. Afterwards you will be ready to prepare your new files, repopulating the working tree, by copying them from elsewhere, extracting a tarball, etc.
I just installed Sublime 3, the 64 bit version, on Ubuntu 14.04. I can't tell the difference between this version and Sublime 2 as far as user interface. The reason I didn't go with Sublime 2 is that it gives an annoying "GLib critical" error messages.
Anyways - previous posts mentioned the file
/sublime_text_3/Packages/Color\ Scheme\ -\ Default.sublime-package
I wanted to give two tips here with respect to this file in Sublime 3:
^W
to search the theme name. The first search
result will bring you to an XML style entry where you can change the values. Make a copy
before you experiment.~/.config/sublime-text-3/Cache/Color Scheme - Default/
Small addition to @user995502's answer on how to run the program.
g++ player.cpp main.cpp -o main.out && ./main.out
there are many ways. as awk
solutions shows, it's the clean solution
sed solution is to delete anything till the last space. So if there is no space at the end, it should work
sed 's/.* //g' <file>
you can avoid sed
also and go for a while
loop.
while read line
do [ -z "$line" ] && continue ;
echo $line|rev|cut -f1 -d' '|rev
done < file
it reads a line, reveres it, cuts the first (i.e. last in the original) and restores back
the same can be done in a pure bash way
while read line
do [ -z "$line" ] && continue ;
echo ${line##* }
done < file
it is called parameter expansion
You can use ~
like {{ foo ~ 'inline string' ~ bar.fieldName }}
But you can also create your own concat
function to use it like in your question:
{{ concat('http://', app.request.host) }}
:
In src/AppBundle/Twig/AppExtension.php
<?php
namespace AppBundle\Twig;
class AppExtension extends \Twig_Extension
{
/**
* {@inheritdoc}
*/
public function getFunctions()
{
return [
new \Twig_SimpleFunction('concat', [$this, 'concat'], ['is_safe' => ['html']]),
];
}
public function concat()
{
return implode('', func_get_args())
}
/**
* {@inheritdoc}
*/
public function getName()
{
return 'app_extension';
}
}
In app/config/services.yml
:
services:
app.twig_extension:
class: AppBundle\Twig\AppExtension
public: false
tags:
- { name: twig.extension }
write old function on your fields value for example
<input type="text" name="username" value="{{ old('username') }}">
If you want to manage key misses you should use TryGetValue
https://msdn.microsoft.com/en-gb/library/bb347013(v=vs.110).aspx
string value = "";
if (openWith.TryGetValue("tif", out value))
{
Console.WriteLine("For key = \"tif\", value = {0}.", value);
}
else
{
Console.WriteLine("Key = \"tif\" is not found.");
}
Basically, you're trying to use int
as if it was an Object
, which it isn't (well...it's complicated)
id.equals(list[pos].getItemNumber())
Should be...
id == list[pos].getItemNumber()
I just found a solution to the problem here:
http://willcodeforcoffee.com/2007/01/31/cakephp-error-500-too-many-redirects/
The .htaccess file in webroot should look like:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
instead of this:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /projectname
RewriteCond %{REQUEST_FILENAME} !-d
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ index.php?url=$1 [QSA,L]
</IfModule>
You can do it like this by iterating through the array in a loop, accumulating the new HTML into it's own array and then joining the HTML all together and inserting it into the DOM at the end:
var array = [...];
var newHTML = [];
for (var i = 0; i < array.length; i++) {
newHTML.push('<span>' + array[i] + '</span>');
}
$(".element").html(newHTML.join(""));
Some people prefer to use jQuery's .each()
method instead of the for
loop which would work like this:
var array = [...];
var newHTML = [];
$.each(array, function(index, value) {
newHTML.push('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));
Or because the output of the array iteration is itself an array with one item derived from each item in the original array, jQuery's .map
can be used like this:
var array = [...];
var newHTML = $.map(array, function(value) {
return('<span>' + value + '</span>');
});
$(".element").html(newHTML.join(""));
Which you should use is a personal choice depending upon your preferred coding style, sensitivity to performance and familiarity with .map()
. My guess is that the for
loop would be the fastest since it has fewer function calls, but if performance was the main criteria, then you would have to benchmark the options to actually measure.
FYI, in all three of these options, the HTML is accumulated into an array, then joined together at the end and the inserted into the DOM all at once. This is because DOM operations are usually the slowest part of an operation like this so it's best to minimize the number of separate DOM operations. The results are accumulated into an array because adding items to an array and then joining them at the end is usually faster than adding strings as you go.
And, if you can live with IE9 or above (or install an ES5 polyfill for .map()
), you can use the array version of .map
like this:
var array = [...];
$(".element").html(array.map(function(value) {
return('<span>' + value + '</span>');
}).join(""));
Note: this version also gets rid of the newHTML
intermediate variable in the interest of compactness.
I prefer the Boost Timer library for its simplicity, but if you don't want to use third-parrty libraries, using clock() seems reasonable.
For things like numbers (decimal points, commas in amounts), they are usually preferred in the specific culture.
A appropriate way to do this would be set it at the culture level (for German) like this:
Thread.CurrentThread.CurrentCulture.NumberFormat = new CultureInfo("de").NumberFormat;
Good news! A pull request adding System.Globalization.ISOWeek
to .NET Core was just merged and is currently slated for the 3.0 release. Hopefully it will propagate to the other .NET platforms in a not-too-distant future.
The type has the following signature, which should cover most ISO week needs:
namespace System.Globalization
{
public static class ISOWeek
{
public static int GetWeekOfYear(DateTime date);
public static int GetWeeksInYear(int year);
public static int GetYear(DateTime date);
public static DateTime GetYearEnd(int year);
public static DateTime GetYearStart(int year);
public static DateTime ToDateTime(int year, int week, DayOfWeek dayOfWeek);
}
}
You can find the source code here.
UPDATE: These APIs have also been included in the 2.1 version of .NET Standard.
It basically occours when you return from a loop you can only return from function
This code works:
let str = "governance[string_i_want]";
let res = str.match(/[^governance\[](.*)[^\]]/g);
res will equal "string_i_want". However, in this example res is still an array, so do not treat res like a string.
By grouping the characters I do not want, using [^string], and matching on what is between the brackets, the code extracts the string I want!
You can try it out here: https://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_match_regexp
Good luck.
just install the database driver:
apt-get install php5-pgsql php5-mysql php5-sqlite ... and so on ...
and be happy!
for..in
and for..of
:Both for..in
and for..of
are looping constructs which are used to iterate over data structures. The only difference between them is the entities
they iterate over:
for..in
iterates over all enumerable property keys of an objectfor..of
iterates over the values of an iterable object. Examples of iterable objects are arrays, strings, and NodeLists.let arr = ['el1', 'el2', 'el3'];
arr.addedProp = 'arrProp';
// elKey are the property keys
for (let elKey in arr) {
console.log(elKey);
}
// elValue are the property values
for (let elValue of arr) {
console.log(elValue)
}
_x000D_
In this example we can observe that the for..in
loop iterates over the keys of the object, which is an array object in this example. The keys are 0, 1, 2 (which correspond to the array elements) and addedProp
. This is how the arr
array object looks in chrome devtools:
You see that our for..in
loop does nothing more than simply iterating over these keys.
The for..of
loop in our example iterates over the values of a data structure. The values in this specific example are 'el1', 'el2', 'el3'
. The values which an iterable data structure will return using for..of
is dependent on the type of iterable object. For example an array will return the values of all the array elements whereas a string returns every individual character of the string.
A three line solution, but works quite well:
int[] source_array = {0,1,2,3,4,5,6,7,8,9,10,11};
ArrayList<Integer> target_list = new ArrayList<Integer>();
for(int i = 0; i < source_array.length; i++){
target_list.add(random_array[i]);
}
There are a few existing resources you might check:
For what it's worth, my own personal guidelines that I tend to use are as follows:
A couple of other points:
The latter is preferred, because it will handle subclasses properly. In fact, your example can be written even more easily because isinstance()
's second parameter may be a tuple:
if isinstance(b, (str, unicode)):
do_something_else()
or, using the basestring
abstract class:
if isinstance(b, basestring):
do_something_else()
Check out jQuery UI Dialog. You would use it like this:
The jQuery:
$(document).ready(function() {
$("#dialog").dialog();
});
The markup:
<div id="dialog" title="Dialog Title">I'm in a dialog</div>
Done!
Bear in mind that's about the simplest use-case there is, I would suggest reading the documentation to get a better idea of just what can be done with it.
@RobinL as mentioned in previous comments, you can use chart.series[n].setData(). First you need to make sure you’ve assigned a chart instance to the chart variable, that way it adopts all the properties and methods you need to access and manipulate the chart.
I’ve also used the second parameter of setData() and had it false, to prevent automatic rendering of the chart. This was because I have multiple data series, so I’ll rather update each of them, with render=false, and then running chart.redraw(). This multiplied performance (I’m having 10,000-100,000 data points and refreshing the data set every 50 milliseconds).
localeCompare()
is slow, so if you don't care about the "correct" ordering of non-English-character strings, try your original method or the cleaner-looking:
str1 < str2 ? -1 : +(str1 > str2)
This is an order of magnitude faster than localeCompare()
on my machine.
The +
ensures that the answer is always numeric rather than boolean.
I figured out myself.
cmp
calls ComputeBetasAndNuHat
which returns a list which has objective
as minusloglik
So I can change the function cmp
to get this value.
You can join a table to itself as many times as you require, it is called a self join.
An alias is assigned to each instance of the table (as in the example below) to differentiate one from another.
SELECT a.SelfJoinTableID
FROM dbo.SelfJoinTable a
INNER JOIN dbo.SelfJoinTable b
ON a.SelfJoinTableID = b.SelfJoinTableID
INNER JOIN dbo.SelfJoinTable c
ON a.SelfJoinTableID = c.SelfJoinTableID
WHERE a.Status = 'Status to filter a'
AND b.Status = 'Status to filter b'
AND c.Status = 'Status to filter c'
To add one day to a date object:
var date = new Date();
// add a day
date.setDate(date.getDate() + 1);
To answer your question, no. That would be possible with div though. THe only question is would cause a hazzle if the functionality were done with div rather than tables.
For Sharepoint 2007
C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\LOGS
If you check out the subprocess section of the Python docs, you'll notice there is an example of how to replace os.system()
with subprocess.Popen()
:
sts = os.system("mycmd" + " myarg")
...does the same thing as...
sts = Popen("mycmd" + " myarg", shell=True).wait()
The "improved" code looks more complicated, but it's better because once you know subprocess.Popen()
, you don't need anything else. subprocess.Popen()
replaces several other tools (os.system()
is just one of those) that were scattered throughout three other Python modules.
If it helps, think of subprocess.Popen()
as a very flexible os.system()
.
With PHP 7.4 I do it like this:
$ipaddress = '';
if (isset($_SERVER['REMOTE_ADDR']))
$ipaddress = $_SERVER['REMOTE_ADDR'];
else if(isset($_SERVER['HTTP_X_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_X_FORWARDED']))
$ipaddress = $_SERVER['HTTP_X_FORWARDED'];
else if(isset($_SERVER['HTTP_FORWARDED_FOR']))
$ipaddress = $_SERVER['HTTP_FORWARDED_FOR'];
else if(isset($_SERVER['HTTP_FORWARDED']))
$ipaddress = $_SERVER['HTTP_FORWARDED'];
else if(isset($_SERVER['HTTP_CLIENT_IP']))
$ipaddress = $_SERVER['HTTP_CLIENT_IP'];
But keep in mind that REMOTE_ADDR
is the only reliable IP address that you can get. All other values can easily be manipulated. This is theoretically also possible for REMOTE_ADDRESS
, but that would require to spoof the IP address.
In MySQL you could try:
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
Of course this would be a massively inefficient query because it would do a full table scan.
Update: Here's a proof
create table A (MYCOL varchar(255));
create table B (MYCOL varchar(255));
insert into A (MYCOL) values ('foo'), ('bar'), ('baz');
insert into B (MYCOL) values ('fooblah'), ('somethingfooblah'), ('foo');
insert into B (MYCOL) values ('barblah'), ('somethingbarblah'), ('bar');
SELECT * FROM A INNER JOIN B ON B.MYCOL LIKE CONCAT('%', A.MYCOL, '%');
+-------+------------------+
| MYCOL | MYCOL |
+-------+------------------+
| foo | fooblah |
| foo | somethingfooblah |
| foo | foo |
| bar | barblah |
| bar | somethingbarblah |
| bar | bar |
+-------+------------------+
6 rows in set (0.38 sec)