Here is yet another approach, which was more convenient in my case (I just wanted to drop root privileges and do the rest of my script from restricted user): you can make the script restart itself from correct user. Let's suppose it is run as root initially. Then it will look like this:
#!/bin/bash
if [ $UID -eq 0 ]; then
user=$1
dir=$2
shift 2 # if you need some other parameters
cd "$dir"
exec su "$user" "$0" -- "$@"
# nothing will be executed beyond that line,
# because exec replaces running process with the new one
fi
echo "This will be run from user $UID"
...
Please find below codes for ios 10 request permission sample for info.plist
.
You can modify for your custom message.
<key>NSCameraUsageDescription</key>
<string>${PRODUCT_NAME} Camera Usage</string>
<key>NSBluetoothPeripheralUsageDescription</key>
<string>${PRODUCT_NAME} BluetoothPeripheral</string>
<key>NSCalendarsUsageDescription</key>
<string>${PRODUCT_NAME} Calendar Usage</string>
<key>NSContactsUsageDescription</key>
<string>${PRODUCT_NAME} Contact fetch</string>
<key>NSHealthShareUsageDescription</key>
<string>${PRODUCT_NAME} Health Description</string>
<key>NSHealthUpdateUsageDescription</key>
<string>${PRODUCT_NAME} Health Updates</string>
<key>NSHomeKitUsageDescription</key>
<string>${PRODUCT_NAME} HomeKit Usage</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>${PRODUCT_NAME} Use location always</string>
<key>NSLocationUsageDescription</key>
<string>${PRODUCT_NAME} Location Updates</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>${PRODUCT_NAME} WhenInUse Location</string>
<key>NSAppleMusicUsageDescription</key>
<string>${PRODUCT_NAME} Music Usage</string>
<key>NSMicrophoneUsageDescription</key>
<string>${PRODUCT_NAME} Microphone Usage</string>
<key>NSMotionUsageDescription</key>
<string>${PRODUCT_NAME} Motion Usage</string>
<key>kTCCServiceMediaLibrary</key>
<string>${PRODUCT_NAME} MediaLibrary Usage</string>
<key>NSPhotoLibraryUsageDescription</key>
<string>${PRODUCT_NAME} PhotoLibrary Usage</string>
<key>NSRemindersUsageDescription</key>
<string>${PRODUCT_NAME} Reminder Usage</string>
<key>NSSiriUsageDescription</key>
<string>${PRODUCT_NAME} Siri Usage</string>
<key>NSSpeechRecognitionUsageDescription</key>
<string>${PRODUCT_NAME} Speech Recognition Usage</string>
<key>NSVideoSubscriberAccountUsageDescription</key>
<string>${PRODUCT_NAME} Video Subscribe Usage</string>
iOS 11 and plus, If you want to add photo/image to your library then you must add this key
<key>NSPhotoLibraryAddUsageDescription</key>
<string>${PRODUCT_NAME} library Usage</string>
The easiest way to put the loader in the website.
HTML:
<div id="loading"></div>
CSS:
#loading {
position: fixed;
width: 100%;
height: 100vh;
background: #fff url('images/loader.gif') no-repeat center center;
z-index: 9999;
}
JQUERY:
<script>
jQuery(document).ready(function() {
jQuery('#loading').fadeOut(3000);
});
</script>
Sorry I didn't see your Java tag, was reading question only. I'll leave my other answers here anyway since I've typed them out.
Java
String myString = "9Hello World!";
if ( Character.isDigit(myString.charAt(0)) )
{
System.out.println("String begins with a digit");
}
C++:
string myString = "2Hello World!";
if (isdigit( myString[0]) )
{
printf("String begins with a digit");
}
Regular expression:
\b[0-9]
This below command worked for me
Python version - 2.7
package - python-jenkins
command - $ pip install 'python-jenkins>=1.1.1'
I had the same issue in Flask
and after trying the first 2 solutions which are the same (Authorization: Bearer <token>
), and getting this:
{
"description": "Unsupported authorization type",
"error": "Invalid JWT header",
"status_code": 401
}
I managed to finally solve it by using:
Authorization: jwt <token>
Thought it might save some time to people who encounter the same thing.
I have not tried in Selenium, but for Galen test this is working,
var list = driver.findElementByID("periodID"); // this will return web element
list.click(); // this will open the dropdown list.
list.typeText("14w"); // this will select option "14w".
You can try this in selenium, the galen and selenium working are similar.
Most / all answers caused issues for us when daylight savings time came around. Here's our working solution for all dates, without using JodaTime. It utilizes calendar objects:
public static int daysBetween(Calendar day1, Calendar day2){
Calendar dayOne = (Calendar) day1.clone(),
dayTwo = (Calendar) day2.clone();
if (dayOne.get(Calendar.YEAR) == dayTwo.get(Calendar.YEAR)) {
return Math.abs(dayOne.get(Calendar.DAY_OF_YEAR) - dayTwo.get(Calendar.DAY_OF_YEAR));
} else {
if (dayTwo.get(Calendar.YEAR) > dayOne.get(Calendar.YEAR)) {
//swap them
Calendar temp = dayOne;
dayOne = dayTwo;
dayTwo = temp;
}
int extraDays = 0;
int dayOneOriginalYearDays = dayOne.get(Calendar.DAY_OF_YEAR);
while (dayOne.get(Calendar.YEAR) > dayTwo.get(Calendar.YEAR)) {
dayOne.add(Calendar.YEAR, -1);
// getActualMaximum() important for leap years
extraDays += dayOne.getActualMaximum(Calendar.DAY_OF_YEAR);
}
return extraDays - dayTwo.get(Calendar.DAY_OF_YEAR) + dayOneOriginalYearDays ;
}
}
select a.ip, a.os, a.hostname, a.port, a.protocol,
b.state
from a
left join b on a.ip = b.ip
and a.port = b.port
I had this problem after I created a new developer certificate.
The following was already correct: The old private key was deleted from the keychain, all profiles where up to date, the build configuration and signing settings were correct. Yet I had this problem.
Solution: I had to restart Xcode (5.1.1), because it was not aware of my new developer certificate. I also deleted the obsolete profiles from my devices just to be sure and to clean up.
You can use a time_t
struct and clock()
function from time.h.
Store the start time in a time_t
struct by using clock()
and check the elapsed time by comparing the difference between stored time and current time.
Important to note is the INT32 limit of Batch: 'Invalid number. Numbers are limited to 32-bits of precision.'
Try the following statements:
IF 2147483647 GTR 2147483646 echo A is greater than B (will be TRUE)
IF 2147483648 GTR 2147483647 echo A is greater than B (will be FALSE!)
Any number greater than the max INT32 value will BREAK THE SCRIPT! Seeing as filesize is measured in bytes, the scripts will support a maximum filesize of about 255.9999997615814 MB !
There are at least three problems with putting a BOM in UTF-8 encoded files.
And, as others have mentioned, it is neither sufficient nor necessary to have a BOM to detect that something is UTF-8:
What Asaph said is right. However, not every YouTube video contains all nine thumbnails. Also, the thumbnails' image sizes depends on the video (the numbers below are based on one). There are some thumbnails guaranteed to exist:
Width | Height | URL
------|--------|----
120 | 90 | https://i.ytimg.com/vi/<VIDEO ID>/1.jpg
120 | 90 | https://i.ytimg.com/vi/<VIDEO ID>/2.jpg
120 | 90 | https://i.ytimg.com/vi/<VIDEO ID>/3.jpg
120 | 90 | https://i.ytimg.com/vi/<VIDEO ID>/default.jpg
320 | 180 | https://i.ytimg.com/vi/<VIDEO ID>/mq1.jpg
320 | 180 | https://i.ytimg.com/vi/<VIDEO ID>/mq2.jpg
320 | 180 | https://i.ytimg.com/vi/<VIDEO ID>/mq3.jpg
320 | 180 | https://i.ytimg.com/vi/<VIDEO ID>/mqdefault.jpg
480 | 360 | https://i.ytimg.com/vi/<VIDEO ID>/0.jpg
480 | 360 | https://i.ytimg.com/vi/<VIDEO ID>/hq1.jpg
480 | 360 | https://i.ytimg.com/vi/<VIDEO ID>/hq2.jpg
480 | 360 | https://i.ytimg.com/vi/<VIDEO ID>/hq3.jpg
480 | 360 | https://i.ytimg.com/vi/<VIDEO ID>/hqdefault.jpg
Additionally, the some other thumbnails may or may not exist. Their presence is probably based on whether the video is high-quality.
Width | Height | URL
------|--------|----
640 | 480 | https://i.ytimg.com/vi/<VIDEO ID>/sd1.jpg
640 | 480 | https://i.ytimg.com/vi/<VIDEO ID>/sd2.jpg
640 | 480 | https://i.ytimg.com/vi/<VIDEO ID>/sd3.jpg
640 | 480 | https://i.ytimg.com/vi/<VIDEO ID>/sddefault.jpg
1280 | 720 | https://i.ytimg.com/vi/<VIDEO ID>/hq720.jpg
1920 | 1080 | https://i.ytimg.com/vi/<VIDEO ID>/maxresdefault.jpg
You can find JavaScript and PHP scripts to retrieve thumbnails and other YouTube information in:
You can also use the YouTube Video Information Generator tool to get all the information about a YouTube video by submitting a URL or video id.
For me, I set two times:
(MimeBodyPart)messageBodyPart.setContent(content, text/html)
(Multipart)multipart.addBodyPart(messageBodyPart)
(MimeMessage)msg.setContent(multipart, text/html)
and its been working fine.
I've seen this style being used:
if (when || who || format || data || len);
This should work for images with all possible proportions
$(document).ready(function() {
$('.list img').each(function() {
var maxWidth = 100;
var maxHeight = 100;
var width = $(this).width();
var height = $(this).height();
var ratioW = maxWidth / width; // Width ratio
var ratioH = maxHeight / height; // Height ratio
// If height ratio is bigger then we need to scale height
if(ratioH > ratioW){
$(this).css("width", maxWidth);
$(this).css("height", height * ratioW); // Scale height according to width ratio
}
else{ // otherwise we scale width
$(this).css("height", maxHeight);
$(this).css("width", height * ratioH); // according to height ratio
}
});
});
If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.
Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.
If you want to audit a client application name along with each failed login, you can use an Extended Events session.
To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/
On Python 3.4, the pathlib
module was added, and the following code will reliably open a file in the same directory as the current script:
from pathlib import Path
p = Path(__file__).with_name('file.txt')
with p.open('r') as f:
print(f.read())
You can also use parent.absolute()
to get directory value as a string if needed:
p = Path(__file__)
dir_abs = p.parent.absolute() # Will return the executable directory absolute path
Ah-ha! The Lodash Changelog says it all...
"Removed _.pluck
in favor of _.map
with iteratee shorthand"
var objects = [{ 'a': 1 }, { 'a': 2 }];
// in 3.10.1
_.pluck(objects, 'a'); // ? [1, 2]
_.map(objects, 'a'); // ? [1, 2]
// in 4.0.0
_.map(objects, 'a'); // ? [1, 2]
Just use this this decrypter to decrypt your locally cached username & password.
By default, TortoiseSVN stores your cached credentials inside files in the %APPDATA%\Subversion\auth\svn.simple directory. The passwords are encrypted using the Windows Data Protection API, with a key tied to your user account. This tool reads the files and uses the API to decrypt your passwords
In Python 3.x and 2.x you can use use list
to force a copy of the keys to be made:
for i in list(d):
In Python 2.x calling keys
made a copy of the keys that you could iterate over while modifying the dict
:
for i in d.keys():
But note that in Python 3.x this second method doesn't help with your error because keys
returns an a view object instead of copynig the keys into a list.
You don't need 2 style attributes - just use one:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
style="height:100px;width:100px;" alt="25"/>
Consider, however, using a CSS class instead:
CSS:
.100pxSquare
{
width: 100px;
height: 100px;
}
HTML:
<img src="http://img705.imageshack.us/img705/119/original120x75.png"
class="100pxSquare" alt="25"/>
Everything is fine, just one mistake is there. Change this:
$query = mysql_query("SELECT username FROM Users WHERE username=$username", $con);
$query = mysql_query("SELECT Count(*) FROM Users WHERE username=$username, $con");
if (mysql_num_rows($query) != 0)
{
echo "Username already exists";
}
else
{
...
}
SELECT *
will not work, use with SELECT COUNT(*)
.
In the Table Designer on SQL Server Management Studio you can set the where the auto increment will start. Right-click on the table in Object Explorer and choose Design, then go to the Column Properties for the relevant column:
If you already have a wheel file (.whl) on your pc, then just go with the following code:
cd ../user
pip install file.whl
If you want to download a file from web, and then install it, go with the following in command line:
pip install package_name
or, if you have the url:
pip install http//websiteurl.com/filename.whl
This will for sure install the required file.
Note: I had to type pip2 instead of pip while using Python 2.
Since C++11, there's a safe alternative to new[]
and delete[]
which is zero-overhead unlike std::vector
:
std::unique_ptr<int[]> array(new int[size]);
In C++14:
auto array = std::make_unique<int[]>(size);
Both of the above rely on the same header file, #include <memory>
I am not very good in using sophisticated regular expressions, so I'd do such task in the following way:
files <- list.files()
dbf.files <- files[-grep(".xml", files, fixed=T)]
First line just lists all files from working dir. Second one drops everything containing ".xml" (grep returns indices of such strings in 'files' vector; subsetting with negative indices removes corresponding entries from vector). "fixed" argument for grep function is just my whim, as I usually want it to peform crude pattern matching without Perl-style fancy regexprs, which may cause surprise for me.
I'm aware that such solution simply reflects drawbacks in my education, but for a novice it may be useful =) at least it's easy.
You don't need to call $.toJSON
and add traditional = true
data: { sendInfo: array },
traditional: true
would do.
I made use of mysqlfrm
which is a great tool which generates table creation sql code from .frm files. I was getting this nasty table not found error although tables were being listed. Thus I used this tool to regenerate the tables. In ubuntu you need to install this as:
sudo apt install mysql-utilities
then,
mysqlfrm --diagnostic mysql/db_name/ > db_name.sql
Create a new database and then you can use,
mysql -u username -p < db_name.sql
However, this will give you the tables but not the data. In my case this was enough.
With all due respect to our unknown (yahoo) poster, I look at code like that and just die a little inside. Alphabet soup is just so insanely difficult to debug. A single typo anywhere in there can really ruin your whole day. Sadly, this particular example lacked variables with underscores. It's so much more fun when we have a_b-c_d*e_f-g_h. Especially when using a font where _ and - have the same pixel length.
Taking up Suvesh Pratapa on his suggestion, I note:
Given 3x3 matrix:
y0x0 y0x1 y0x2
y1x0 y1x1 y1x2
y2x0 y2x1 y2x2
Declared as double matrix [/*Y=*/3] [/*X=*/3];
(A) When taking a minor of a 3x3 array, we have 4 values of interest. The lower X/Y index is always 0 or 1. The higher X/Y index is always 1 or 2. Always! Therefore:
double determinantOfMinor( int theRowHeightY,
int theColumnWidthX,
const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
int x1 = theColumnWidthX == 0 ? 1 : 0; /* always either 0 or 1 */
int x2 = theColumnWidthX == 2 ? 1 : 2; /* always either 1 or 2 */
int y1 = theRowHeightY == 0 ? 1 : 0; /* always either 0 or 1 */
int y2 = theRowHeightY == 2 ? 1 : 2; /* always either 1 or 2 */
return ( theMatrix [y1] [x1] * theMatrix [y2] [x2] )
- ( theMatrix [y1] [x2] * theMatrix [y2] [x1] );
}
(B) Determinant is now: (Note the minus sign!)
double determinant( const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
return ( theMatrix [0] [0] * determinantOfMinor( 0, 0, theMatrix ) )
- ( theMatrix [0] [1] * determinantOfMinor( 0, 1, theMatrix ) )
+ ( theMatrix [0] [2] * determinantOfMinor( 0, 2, theMatrix ) );
}
(C) And the inverse is now:
bool inverse( const double theMatrix [/*Y=*/3] [/*X=*/3],
double theOutput [/*Y=*/3] [/*X=*/3] )
{
double det = determinant( theMatrix );
/* Arbitrary for now. This should be something nicer... */
if ( ABS(det) < 1e-2 )
{
memset( theOutput, 0, sizeof theOutput );
return false;
}
double oneOverDeterminant = 1.0 / det;
for ( int y = 0; y < 3; y ++ )
for ( int x = 0; x < 3; x ++ )
{
/* Rule is inverse = 1/det * minor of the TRANSPOSE matrix. *
* Note (y,x) becomes (x,y) INTENTIONALLY here! */
theOutput [y] [x]
= determinantOfMinor( x, y, theMatrix ) * oneOverDeterminant;
/* (y0,x1) (y1,x0) (y1,x2) and (y2,x1) all need to be negated. */
if( 1 == ((x + y) % 2) )
theOutput [y] [x] = - theOutput [y] [x];
}
return true;
}
And round it out with a little lower-quality testing code:
void printMatrix( const double theMatrix [/*Y=*/3] [/*X=*/3] )
{
for ( int y = 0; y < 3; y ++ )
{
cout << "[ ";
for ( int x = 0; x < 3; x ++ )
cout << theMatrix [y] [x] << " ";
cout << "]" << endl;
}
cout << endl;
}
void matrixMultiply( const double theMatrixA [/*Y=*/3] [/*X=*/3],
const double theMatrixB [/*Y=*/3] [/*X=*/3],
double theOutput [/*Y=*/3] [/*X=*/3] )
{
for ( int y = 0; y < 3; y ++ )
for ( int x = 0; x < 3; x ++ )
{
theOutput [y] [x] = 0;
for ( int i = 0; i < 3; i ++ )
theOutput [y] [x] += theMatrixA [y] [i] * theMatrixB [i] [x];
}
}
int
main(int argc, char **argv)
{
if ( argc > 1 )
SRANDOM( atoi( argv[1] ) );
double m[3][3] = { { RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) },
{ RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) },
{ RANDOM_D(0,1e3), RANDOM_D(0,1e3), RANDOM_D(0,1e3) } };
double o[3][3], mm[3][3];
if ( argc <= 2 )
cout << fixed << setprecision(3);
printMatrix(m);
cout << endl << endl;
SHOW( determinant(m) );
cout << endl << endl;
BOUT( inverse(m, o) );
printMatrix(m);
printMatrix(o);
cout << endl << endl;
matrixMultiply (m, o, mm );
printMatrix(m);
printMatrix(o);
printMatrix(mm);
cout << endl << endl;
}
You may also want to detect very large determinants as round-off errors will affect your accuracy!
Here's another approach (assuming you have control of the HTML): add an empty <span></span>
right after the input, and target that in CSS using input.mystyle + span:after
.field_with_errors {_x000D_
display: inline;_x000D_
color: red;_x000D_
}_x000D_
.field_with_errors input+span:after {_x000D_
content: "*"_x000D_
}
_x000D_
<div class="field_with_errors">Label:</div>_x000D_
<div class="field_with_errors">_x000D_
<input type="text" /><span></span> _x000D_
</div>
_x000D_
I'm using this approach in AngularJS because it will add .ng-invalid
classes automatically to <input>
form elements, and to the form, but not to the <label>
.
If you want the latest file in the directory and you are using only the LastWriteTime
to determine the latest file, you can do something like below:
gci path | sort LastWriteTime | select -last 1
On the other hand, if you want to only rely on the names that have the dates in them, you should be able to something similar
gci path | select -last 1
Also, if there are directories in the directory, you might want to add a ?{-not $_.PsIsContainer}
Yes, Slack has the ability to hyperlink words, as long as Format messages with markup is unchecked under Preferences > Advanced to show the formatting toolbar. According to the documentation, start out with one of these:
- Select text, then click the link icon in the formatting toolbar
- Select text, then press ?ShiftU on Mac or CtrlShiftU on Windows/Linux.
Then do this:
Copy the link you'd like to share and paste it in the empty field under Link, then click Save.
What follows is how this answer used to read when it first became so famous. It was correct until about February 2020.
No.
As a couple of commenters said, and as the Slack documentation says:
Note: It’s not possible to hyperlink words in a Slack message.
I think you shouldn't prepend themesDir
. You only pass the filename of the template to flask, it will then look in a folder called templates
relative to your python file.
It's browser dependent. "By default, Internet Explorer has a KeepAliveTimeout value of one minute and an additional limiting factor (ServerInfoTimeout) of two minutes. Either setting can cause Internet Explorer to reset the socket." - from IE support http://support.microsoft.com/kb/813827
Firefox is around the same value I think as well.
Usually though server timeout are set lower than browser timeouts, but at least you can control that and set it higher.
You'd rather handle the timeout though, so that way you can act upon such an event. See this thread: How to detect timeout on an AJAX (XmlHttpRequest) call in the browser?
you can make use of the following code:
from __future__ import division, unicode_literals
import codecs
from bs4 import BeautifulSoup
f=codecs.open("test.html", 'r', 'utf-8')
document= BeautifulSoup(f.read()).get_text()
print document
If you want to delete all the blank lines in between and get all the words as a string (also avoid special characters, numbers) then also include:
import nltk
from nltk.tokenize import word_tokenize
docwords=word_tokenize(document)
for line in docwords:
line = (line.rstrip())
if line:
if re.match("^[A-Za-z]*$",line):
if (line not in stop and len(line)>1):
st=st+" "+line
print st
*define st
as a string
initially, like st=""
If your spring-context.xml and my.config files are in different jars then you will need to use classpath*:my.config
?
More info here
Also, make sure you are using resource.getInputStream()
not resource.getFile()
when loading from inside a jar file.
what you are searching for is the Export-Csv file.csv
try using Get-Help Export-Csv to see whats possible
also Out-File -FilePath "file.csv"
will work
Here's how I do it, the keys are getItemViewType and getViewTypeCount in the Adapter
class. getViewTypeCount
returns how many types of items we have in the list, in this case we have a header item and an event item, so two. getItemViewType
should return what type of View
we have at the input position
.
Android will then take care of passing you the right type of View
in convertView
automatically.
Here what the result of the code below looks like:
First we have an interface that our two list item types will implement
public interface Item {
public int getViewType();
public View getView(LayoutInflater inflater, View convertView);
}
Then we have an adapter that takes a list of Item
public class TwoTextArrayAdapter extends ArrayAdapter<Item> {
private LayoutInflater mInflater;
public enum RowType {
LIST_ITEM, HEADER_ITEM
}
public TwoTextArrayAdapter(Context context, List<Item> items) {
super(context, 0, items);
mInflater = LayoutInflater.from(context);
}
@Override
public int getViewTypeCount() {
return RowType.values().length;
}
@Override
public int getItemViewType(int position) {
return getItem(position).getViewType();
}
@Override public View getView(int position, View convertView, ViewGroup parent) { return getItem(position).getView(mInflater, convertView); }
EDIT Better For Performance.. can be noticed when scrolling
private static final int TYPE_ITEM = 0;
private static final int TYPE_SEPARATOR = 1;
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
int rowType = getItemViewType(position);
View View;
if (convertView == null) {
holder = new ViewHolder();
switch (rowType) {
case TYPE_ITEM:
convertView = mInflater.inflate(R.layout.task_details_row, null);
holder.View=getItem(position).getView(mInflater, convertView);
break;
case TYPE_SEPARATOR:
convertView = mInflater.inflate(R.layout.task_detail_header, null);
holder.View=getItem(position).getView(mInflater, convertView);
break;
}
convertView.setTag(holder);
}
else
{
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
public static class ViewHolder {
public View View; }
}
Then we have classes the implement Item
and inflate the correct layouts. In your case you'll have something like a Header
class and a ListItem
class.
public class Header implements Item {
private final String name;
public Header(String name) {
this.name = name;
}
@Override
public int getViewType() {
return RowType.HEADER_ITEM.ordinal();
}
@Override
public View getView(LayoutInflater inflater, View convertView) {
View view;
if (convertView == null) {
view = (View) inflater.inflate(R.layout.header, null);
// Do some initialization
} else {
view = convertView;
}
TextView text = (TextView) view.findViewById(R.id.separator);
text.setText(name);
return view;
}
}
And then the ListItem
class
public class ListItem implements Item {
private final String str1;
private final String str2;
public ListItem(String text1, String text2) {
this.str1 = text1;
this.str2 = text2;
}
@Override
public int getViewType() {
return RowType.LIST_ITEM.ordinal();
}
@Override
public View getView(LayoutInflater inflater, View convertView) {
View view;
if (convertView == null) {
view = (View) inflater.inflate(R.layout.my_list_item, null);
// Do some initialization
} else {
view = convertView;
}
TextView text1 = (TextView) view.findViewById(R.id.list_content1);
TextView text2 = (TextView) view.findViewById(R.id.list_content2);
text1.setText(str1);
text2.setText(str2);
return view;
}
}
And a simple Activity
to display it
public class MainActivity extends ListActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Item> items = new ArrayList<Item>();
items.add(new Header("Header 1"));
items.add(new ListItem("Text 1", "Rabble rabble"));
items.add(new ListItem("Text 2", "Rabble rabble"));
items.add(new ListItem("Text 3", "Rabble rabble"));
items.add(new ListItem("Text 4", "Rabble rabble"));
items.add(new Header("Header 2"));
items.add(new ListItem("Text 5", "Rabble rabble"));
items.add(new ListItem("Text 6", "Rabble rabble"));
items.add(new ListItem("Text 7", "Rabble rabble"));
items.add(new ListItem("Text 8", "Rabble rabble"));
TwoTextArrayAdapter adapter = new TwoTextArrayAdapter(this, items);
setListAdapter(adapter);
}
}
Layout for R.layout.header
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
style="?android:attr/listSeparatorTextViewStyle"
android:id="@+id/separator"
android:text="Header"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#757678"
android:textColor="#f5c227" />
</LinearLayout>
Layout for R.layout.my_list_item
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal" >
<TextView
android:id="@+id/list_content1"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dip"
android:clickable="false"
android:gravity="center"
android:longClickable="false"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:text="sample"
android:textColor="#ff7f1d"
android:textSize="17dip"
android:textStyle="bold" />
<TextView
android:id="@+id/list_content2"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:layout_margin="5dip"
android:clickable="false"
android:gravity="center"
android:linksClickable="false"
android:longClickable="false"
android:paddingBottom="1dip"
android:paddingTop="1dip"
android:text="sample"
android:textColor="#6d6d6d"
android:textSize="17dip" />
</LinearLayout>
Layout for R.layout.activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<ListView
android:id="@android:id/list"
android:layout_width="fill_parent"
android:layout_height="fill_parent" />
</RelativeLayout>
You can also get fancier and use ViewHolders
, load stuff asynchronously, or whatever you like.
To create a new branch (locally):
With the commit hash (or part of it)
git checkout -b new_branch 6e559cb
or to go back 4 commits from HEAD
git checkout -b new_branch HEAD~4
Once your new branch is created (locally), you might want to replicate this change on a remote of the same name: How can I push my changes to a remote branch
For discarding the last three commits, see Lunaryorn's answer below.
For moving your current branch HEAD to the specified commit without creating a new branch, see Arpiagar's answer below.
Just in case anyone is trying to do this without java 8, there is a pretty good trick. List.toString() already returns a collection that looks like this:
[1,2,3]
Depending on your specific requirements, this can be post-processed to whatever you want as long as your list items don't contain [] or , .
For instance:
list.toString().replace("[","").replace("]","")
or if your data might contain square brackets this:
String s=list.toString();
s = s.substring(1,s.length()-1)
will get you a pretty reasonable output.
One array item on each line can be created like this:
list.toString().replace("[","").replace("]","").replaceAll(",","\r\n")
I used this technique to make html tooltips from a list in a small app, with something like:
list.toString().replace("[","<html>").replace("]","</html>").replaceAll(",","<br>")
If you have an array then start with Arrays.asList(list).toString() instead
I'll totally own the fact that this is not optimal, but it's not as inefficient as you might think and is pretty straightforward to read and understand. It is, however, quite inflexible--in particular don't try to separate the elements with replaceAll if your data might contain commas and use the substring version if you have square brackets in your data, but for an array of numbers it's pretty much perfect.
I have this error and could not solve this for two days.So the fix of error is very simple.
In body ,where you connect your script
, add type="text/jsx"
and this`ll resolve the problem.
The error "only length-1 arrays can be converted to Python scalars" is raised when the function expects a single value but you pass an array instead.
If you look at the call signature of np.int
, you'll see that it accepts a single value, not an array. In general, if you want to apply a function that accepts a single element to every element in an array, you can use np.vectorize
:
import numpy as np
import matplotlib.pyplot as plt
def f(x):
return np.int(x)
f2 = np.vectorize(f)
x = np.arange(1, 15.1, 0.1)
plt.plot(x, f2(x))
plt.show()
You can skip the definition of f(x) and just pass np.int to the vectorize function: f2 = np.vectorize(np.int)
.
Note that np.vectorize
is just a convenience function and basically a for loop. That will be inefficient over large arrays. Whenever you have the possibility, use truly vectorized functions or methods (like astype(int)
as @FFT suggests).
Use Collections.list(iterator).stream()...
As mentioned in many posts, this is not directly possible, but an easy and successful way is as follows: First, we put a form in the body of our html page, which does not have any buttons for the submit, and also its inputs are hidden. Then we use a javascript function to get the data and ,send the form. One of the advantages of this method is to redirect to other pages, which depends on the server-side code. The code is as follows: and now in anywhere you need an to be in "POST" method:
<script type="text/javascript" language="javascript">
function post_link(data){
$('#post_form').find('#form_input').val(data);
$('#post_form').submit();
};
</script>
<form id="post_form" action="anywhere/you/want/" method="POST">
{% csrf_token %}
<input id="form_input" type="hidden" value="" name="form_input">
</form>
<a href="javascript:{}" onclick="javascript:post_link('data');">post link is ready</a>
I ran into this error because I was trying to pass in a date from localStorage
. Passing the date into a new Date
object, and then calling .toISOString() did the trick for me:
const dateFromStorage = localStorage.getItem('someDate');
const date = new Date(dateFromStorage);
const momentDate = moment(date.toISOString());
This suppressed any warnings in the console.
Working upon @Demosthenex work, @Tmdean and @Jon Crowell invaluable comments! (+1 them)
I save module files in git\ dir beside workbook location. Change that to your liking.
This will NOT track changes to Workbook code. So it's up to you to synchronize them.
Sub SaveCodeModules()
'This code Exports all VBA modules
Dim i As Integer, name As String
With ThisWorkbook.VBProject
For i = .VBComponents.count To 1 Step -1
If .VBComponents(i).Type <> vbext_ct_Document Then
If .VBComponents(i).CodeModule.CountOfLines > 0 Then
name = .VBComponents(i).CodeModule.name
.VBComponents(i).Export Application.ThisWorkbook.Path & _
"\git\" & name & ".vba"
End If
End If
Next i
End With
End Sub
Sub ImportCodeModules()
Dim i As Integer
Dim ModuleName As String
With ThisWorkbook.VBProject
For i = .VBComponents.count To 1 Step -1
ModuleName = .VBComponents(i).CodeModule.name
If ModuleName <> "VersionControl" Then
If .VBComponents(i).Type <> vbext_ct_Document Then
.VBComponents.Remove .VBComponents(ModuleName)
.VBComponents.Import Application.ThisWorkbook.Path & _
"\git\" & ModuleName & ".vba"
End If
End If
Next i
End With
End Sub
And then in Workbook module:
Private Sub Workbook_Open()
ImportCodeModules
End Sub
Private Sub Workbook_BeforeSave(ByVal SaveAsUI As Boolean, Cancel As Boolean)
SaveCodeModules
End Sub
<system.webServer>
<httpErrors errorMode="DetailedLocalOnly">
<remove statusCode="404" subStatusCode="-1" />
<error statusCode="404" prefixLanguageFilePath="" path="your page" responseMode="Redirect" />
</httpErrors>
</system.webServer>
Please Try the following codes :
Import Execute
Execute("zbx_control.sh")
Most likely the remote repository doesn't exist or you have added the wrong one.
You have to first remove the origin and re-add it:
git remote remove origin
git remote add origin https://github.com/username/repository
In case someone stumbled upon this problem when working on Grails (or pure Spring) web application, here is the post that helped me:
http://forum.spring.io/forum/spring-projects/web/2491-solved-character-encoding-and-multipart-forms
To set default encoding to UTF-8 (instead of the ISO-8859-1) for multipart requests, I added the following code in resources.groovy (Spring DSL):
multipartResolver(ContentLengthAwareCommonsMultipartResolver) {
defaultEncoding = 'UTF-8'
}
if you find yourself doing this type of thing regular ( eg- creating undo redo functionality ) it might be worth looking into Immutable.js
const map1 = Immutable.fromJS( { a: 1, b: 2, c: { d: 3 } } );
const map2 = map1.setIn( [ 'c', 'd' ], 50 );
console.log( `${ map1.getIn( [ 'c', 'd' ] ) } vs ${ map2.getIn( [ 'c', 'd' ] ) }` ); // "3 vs 50"
I think you want to set the response of the call to the URL 'compz.php?prodid=' + x + '&qbuys=' + y
as value of the textbox right? If so, you have to do something like:
$.get('compz.php?prodid=' + x + '&qbuys=' + y, function(data) {
$('#subtotal').val(data);
});
Reference: get()
You have two errors in your code:
load()
puts the HTML returned from the Ajax into the specified element:
Load data from the server and place the returned HTML into the matched element.
You cannot set the value of a textbox with that method.
$(selector).load()
returns the a jQuery object. By default an object is converted to [object Object]
when treated as string.
Further clarification:
Assuming your URL returns 5
.
If your HTML looks like:
<div id="foo"></div>
then the result of
$('#foo').load('/your/url');
will be
<div id="foo">5</div>
But in your code, you have an input element. Theoretically (it is not valid HTML and does not work as you noticed), an equivalent call would result in
<input id="foo">5</input>
But you actually need
<input id="foo" value="5" />
Therefore, you cannot use load()
. You have to use another method, get the response and set it as value yourself.
I dealt with this before & had posted in the spring forums.
The advice we received was to use a type of SQlQuery. Here's an example of what we did when trying to get a value out of a DB that might not be there.
@Component
public class FindID extends MappingSqlQuery<Long> {
@Autowired
public void setDataSource(DataSource dataSource) {
String sql = "Select id from address where id = ?";
super.setDataSource(dataSource);
super.declareParameter(new SqlParameter(Types.VARCHAR));
super.setSql(sql);
compile();
}
@Override
protected Long mapRow(ResultSet rs, int rowNum) throws SQLException {
return rs.getLong(1);
}
In the DAO then we just call...
Long id = findID.findObject(id);
Not clear on performance, but it works and is neat.
$converted_res = isset ( $res ) ? ( $res ? 'true' : 'false' ) : 'false';
I have created a function which will convert a csv string to an array. The function knows how to escape special characters, and it works with or without enclosure chars.
$dataArray = csvstring_to_array( file_get_contents('Address.csv'));
I tried it with your csv sample and it works as expected!
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
// @author: Klemen Nagode
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue="";
$isEnclosured = false;
for($i=0; $i<$size;$i++) {
$char = $string{$i};
$addChar = "";
if($isEnclosured) {
if($char==$enclosureChar) {
if($i+1<$size && $string{$i+1}==$enclosureChar){
// escaped char
$addChar=$char;
$i++; // dont check next char
}else{
$isEnclosured = false;
}
}else {
$addChar=$char;
}
}else {
if($char==$enclosureChar) {
$isEnclosured = true;
}else {
if($char==$separatorChar) {
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex++;
}elseif($char==$newlineChar) {
echo $char;
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex=0;
$rowIndex++;
}else {
$addChar=$char;
}
}
}
if($addChar!=""){
$fieldValue.=$addChar;
}
}
if($fieldValue) { // save last field
$array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;
}
Error: 10060 Adding a timeout parameter to request solved the issue for me.
import urllib
import urllib2
g = "http://www.google.com/"
read = urllib2.urlopen(g, timeout=20)
A similar error also occurred while I was making a GET request. Again, passing a timeout
parameter solved the 10060 Error.
response = requests.get(param_url, timeout=20)
Create a ThreadSafeInvoke.snippet file, and then you can just select the update statements, right click and select 'Surround With...' or Ctrl-K+S:
<?xml version="1.0" encoding="utf-8" ?>
<CodeSnippet Format="1.0.0" xmlns="http://schemas.microsoft.com/VisualStudio/2005/CodeSnippet">
<Header>
<Title>ThreadsafeInvoke</Title>
<Shortcut></Shortcut>
<Description>Wraps code in an anonymous method passed to Invoke for Thread safety.</Description>
<SnippetTypes>
<SnippetType>SurroundsWith</SnippetType>
</SnippetTypes>
</Header>
<Snippet>
<Code Language="CSharp">
<![CDATA[
Invoke( (MethodInvoker) delegate
{
$selected$
});
]]>
</Code>
</Snippet>
</CodeSnippet>
<script>
setTimeout(function(){
window.location.href = 'form2.html';
}, 5000);
</script>
And for home page add only '/'
<script>
setTimeout(function(){
window.location.href = '/';
}, 5000);
</script>
It working for me. Try using this..it will help you out..
c:\Program Files\Google\Chrome\Application>chrome.exe --disable-web-security --user-data-dir="D:\chrome"
Another way to use itertools.ifilter
. This checks truthiness and process
(using lambda
)
Sample-
for x in itertools.ifilter(lambda x: x[2] == 0, my_list):
print x
I'd say you can, although it doesn't validate and Firefox will re-arrange the code (so what you see in 'View generated source' when using Web Developer may well surprise). I'm no expert, but putting
<form action="someexecpage.php" method="post">
just ahead of the
<tr>
and then using
</tr></form>
at the end of the row certainly gives the functionality (tested in Firefox, Chrome and IE7-9). Working for me, even if the number of validation errors it produced was a new personal best/worst! No problems seen as a consequence, and I have a fairly heavily styled table. I guess you may have a dynamically produced table, as I do, which is why parsing the table rows is a bit non-obvious for us mortals. So basically, open the form at the beginning of the row and close it just after the end of the row.
The chances are that the problem is in one of the unit tests that you've asked Maven to run.
As such, fiddling with the heap size is the wrong approach. Instead, you should be looking at the unit test that has caused the OOME, and trying to figure out if it is the fault of the unit test or the code that it is testing.
Start by looking at the stack trace. If there isn't one, run mvn ... test
again with the -e
option.
You could use the JavaScriptSerializer class, check this article to build an useful extension method.
Code from article:
namespace ExtensionMethods
{
public static class JSONHelper
{
public static string ToJSON(this object obj)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(obj);
}
public static string ToJSON(this object obj, int recursionDepth)
{
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.RecursionLimit = recursionDepth;
return serializer.Serialize(obj);
}
}
}
Usage:
using ExtensionMethods;
...
List<Person> people = new List<Person>{
new Person{ID = 1, FirstName = "Scott", LastName = "Gurthie"},
new Person{ID = 2, FirstName = "Bill", LastName = "Gates"}
};
string jsonString = people.ToJSON();
PHP's strtotime
function will interpret timezone codes, like UTC. If you get the date from the database/client without the timezone code, but know it's UTC, then you can append it.
Assuming you get the date with timestamp code (like "Fri Mar 23 2012 22:23:03 GMT-0700 (PDT)", which is what Javascript code ""+(new Date())
gives):
$time = strtotime($dateWithTimeZone);
$dateInLocal = date("Y-m-d H:i:s", $time);
Or if you don't, which is likely from MySQL, then:
$time = strtotime($dateInUTC.' UTC');
$dateInLocal = date("Y-m-d H:i:s", $time);
$('title').text();
returns all the title
but if you just want the page title then use
document.title
I ran into something similar - I wanted to create a range based on some variables. Using the Worksheet.Cells did not work directly since I think the cell's values were passed to Range.
This did work though:
Range(Cells(1, 1).Address(), Cells(lastRow, lastColumn).Address()).Select
That took care of converting the cell's numerical location to what Range expects, which is the A1 format.
There can be several things which cause this.
targetSdkVersion
and compileSdkVersion
.targetSdkVersion
and compileSdkVersion
are same.Other solutions can be:
File
? Invalidate Caches / Restarts...
Build
? Clean Project
Build
? Rebuild Project
Build
? Make Project
[this process may take some time]As @StahlRat already answered. I would like to add another method for it. There is extension pack for Python Default idle editor Python Extensions Package.
$("#bchange").click(function() {
$("body, this").css("background-color","yellow");
});
Here is your solution for the problem,
$letter = array();
for ($i = 'A'; $i !== 'ZZ'; $i++){
if(ord($i) % 2 != 0)
$letter[] .= $i;
}
print_r($letter);
You need to get the ASCII value for that character which will solve your problem.
Here is ord doc and working code.
For your requirement, you can do like this,
for ($i = 'A'; $i !== 'ZZ'; ord($i)+$x){
$letter[] .= $i;
}
print_r($letter);
Here set $x as per your requirement.
HTML only: use the download
attribute:
<a download="logo.gif" href="data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7">Download transparent png</a>
_x000D_
Javascript only: you can save any data URI with this code:
function saveAs(uri, filename) {_x000D_
var link = document.createElement('a');_x000D_
if (typeof link.download === 'string') {_x000D_
link.href = uri;_x000D_
link.download = filename;_x000D_
_x000D_
//Firefox requires the link to be in the body_x000D_
document.body.appendChild(link);_x000D_
_x000D_
//simulate click_x000D_
link.click();_x000D_
_x000D_
//remove the link when done_x000D_
document.body.removeChild(link);_x000D_
} else {_x000D_
window.open(uri);_x000D_
}_x000D_
}_x000D_
_x000D_
var file = 'data:image/gif;base64,R0lGODlhAQABAIAAAAAAAP///yH5BAEAAAAALAAAAAABAAEAAAIBRAA7'_x000D_
saveAs(file, 'logo.gif');
_x000D_
Chrome, Firefox, and Edge 13+ will use the specified filename.
IE11, Edge 12, and Safari 9 (which don't support the download
attribute) will download the file with their default name or they will simply display it in a new tab, if it's of a supported file type: images, videos, audio files, …
For me the revelation came when I realise that they all work the same way: by running something once, storing the value they get, and then cough up that same stored value when referenced through Dependency Injection.
Say we have:
app.factory('a', fn);
app.service('b', fn);
app.provider('c', fn);
The difference between the three is that:
a
's stored value comes from running fn
, in other words: fn()
b
’s stored value comes from new
ing fn
, in other words: new fn()
c
’s stored value comes from first getting an instance by new
ing fn
, and then running a $get
method of the instancewhich means, there’s something like a cache object inside angular, whose value of each injection is only assigned once, when they've been injected the first time, and where:
cache.a = fn()
cache.b = new fn()
cache.c = (new fn()).$get()
This is why we use this
in services, and define a this.$get
in providers.
Hope this helps.
If your file looks like this:
[
{
"firstname": "toto",
"lastname": "titi"
},
{
"firstname": "toto2",
"lastname": "titi2"
},
]
You can do:
import json from './json/data.json';
// ....
json.forEach(x => { console.log(x.firstname, x.lastname); });
You can also try this
<li><%= link_to "", application_welcome_path, class: "navbar-brand metas-logo" %></li>
Where "metas-logo" is a css class with a background image
I use the following extension methods. They have optimized overloads for when one stream is a MemoryStream.
public static void CopyTo(this Stream src, Stream dest)
{
int size = (src.CanSeek) ? Math.Min((int)(src.Length - src.Position), 0x2000) : 0x2000;
byte[] buffer = new byte[size];
int n;
do
{
n = src.Read(buffer, 0, buffer.Length);
dest.Write(buffer, 0, n);
} while (n != 0);
}
public static void CopyTo(this MemoryStream src, Stream dest)
{
dest.Write(src.GetBuffer(), (int)src.Position, (int)(src.Length - src.Position));
}
public static void CopyTo(this Stream src, MemoryStream dest)
{
if (src.CanSeek)
{
int pos = (int)dest.Position;
int length = (int)(src.Length - src.Position) + pos;
dest.SetLength(length);
while(pos < length)
pos += src.Read(dest.GetBuffer(), pos, length - pos);
}
else
src.CopyTo((Stream)dest);
}
Depending on how far back you need to go, you can build a table of daylight savings times and then join the table and do a dst-sensitive conversion. This particular one converts from EST to GMT (i.e. uses offsets of 5 and 4).
select createdon, dateadd(hour, case when dstlow is null then 5 else 4 end, createdon) as gmt
from photos
left outer join (
SELECT {ts '2009-03-08 02:00:00'} as dstlow, {ts '2009-11-01 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2010-03-14 02:00:00'} as dstlow, {ts '2010-11-07 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2011-03-13 02:00:00'} as dstlow, {ts '2011-11-06 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2012-03-11 02:00:00'} as dstlow, {ts '2012-11-04 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2013-03-10 02:00:00'} as dstlow, {ts '2013-11-03 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2014-03-09 02:00:00'} as dstlow, {ts '2014-11-02 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2015-03-08 02:00:00'} as dstlow, {ts '2015-11-01 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2016-03-13 02:00:00'} as dstlow, {ts '2016-11-06 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2017-03-12 02:00:00'} as dstlow, {ts '2017-11-05 02:00:00'} as dsthigh
UNION ALL SELECT {ts '2018-03-11 02:00:00'} as dstlow, {ts '2018-11-04 02:00:00'} as dsthigh
) dst
on createdon >= dstlow and createdon < dsthigh
Not in Linux at the moment, so can't double check, but I think it's:
rpm -ql ffmpeg
That should list all the files installed as part of the ffmpeg package.
I know this is a very old post, so some methods were not available back then. But here is my very simple take on it (based on Lolo's answer).
It relies on the HTML5 data-* attributes and therefore is very generic in that is uses jQuery's for-each function to get every .class matching "load-html" and uses its respective 'data-source' attribute to load the content:
<div class="container-fluid">
<div class="load-html" id="NavigationMenu" data-source="header.html"></div>
<div class="load-html" id="MainBody" data-source="body.html"></div>
<div class="load-html" id="Footer" data-source="footer.html"></div>
</div>
<script src="js/jquery.min.js"></script>
<script>
$(function () {
$(".load-html").each(function () {
$(this).load(this.dataset.source);
});
});
</script>
The CompletionService will take your Callables with the .submit() method and you can retrieve the computed futures with the .take() method.
One thing you must not forget is to terminate the ExecutorService by calling the .shutdown() method. Also you can only call this method when you have saved a reference to the executor service so make sure to keep one.
Example code - For a fixed number of work items to be worked on in parallel:
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CompletionService<YourCallableImplementor> completionService =
new ExecutorCompletionService<YourCallableImplementor>(service);
ArrayList<Future<YourCallableImplementor>> futures = new ArrayList<Future<YourCallableImplementor>>();
for (String computeMe : elementsToCompute) {
futures.add(completionService.submit(new YourCallableImplementor(computeMe)));
}
//now retrieve the futures after computation (auto wait for it)
int received = 0;
while(received < elementsToCompute.size()) {
Future<YourCallableImplementor> resultFuture = completionService.take();
YourCallableImplementor result = resultFuture.get();
received ++;
}
//important: shutdown your ExecutorService
service.shutdown();
Example code - For a dynamic number of work items to be worked on in parallel:
public void runIt(){
ExecutorService service = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
CompletionService<CallableImplementor> completionService = new ExecutorCompletionService<CallableImplementor>(service);
ArrayList<Future<CallableImplementor>> futures = new ArrayList<Future<CallableImplementor>>();
//Initial workload is 8 threads
for (int i = 0; i < 9; i++) {
futures.add(completionService.submit(write.new CallableImplementor()));
}
boolean finished = false;
while (!finished) {
try {
Future<CallableImplementor> resultFuture;
resultFuture = completionService.take();
CallableImplementor result = resultFuture.get();
finished = doSomethingWith(result.getResult());
result.setResult(null);
result = null;
resultFuture = null;
//After work package has been finished create new work package and add it to futures
futures.add(completionService.submit(write.new CallableImplementor()));
} catch (InterruptedException | ExecutionException e) {
//handle interrupted and assert correct thread / work packet count
}
}
//important: shutdown your ExecutorService
service.shutdown();
}
public class CallableImplementor implements Callable{
boolean result;
@Override
public CallableImplementor call() throws Exception {
//business logic goes here
return this;
}
public boolean getResult() {
return result;
}
public void setResult(boolean result) {
this.result = result;
}
}
speaking of which ...
python3.6 comes with f-strings
which makes things much easier in formatting!
now if your python version is greater than 3.6 you can format your strings with these available methods:
name = "python"
print ("i code with %s" %name) # with help of older method
print ("i code with {0}".format(name)) # with help of format
print (f"i code with {name}") # with help of f-strings
You need to call attemptRotationToDeviceOrientation (UIViewController)
to make the system call your supportedInterfaceOrientations
when the condition has changed.
Just add other control types:
public static void ClearControls(Control c)
{
foreach (Control Ctrl in c.Controls)
{
//Console.WriteLine(Ctrl.GetType().ToString());
//MessageBox.Show ( (Ctrl.GetType().ToString())) ;
switch (Ctrl.GetType().ToString())
{
case "System.Windows.Forms.CheckBox":
((CheckBox)Ctrl).Checked = false;
break;
case "System.Windows.Forms.TextBox":
((TextBox)Ctrl).Text = "";
break;
case "System.Windows.Forms.RichTextBox":
((RichTextBox)Ctrl).Text = "";
break;
case "System.Windows.Forms.ComboBox":
((ComboBox)Ctrl).SelectedIndex = -1;
((ComboBox)Ctrl).SelectedIndex = -1;
break;
case "System.Windows.Forms.MaskedTextBox":
((MaskedTextBox)Ctrl).Text = "";
break;
case "Infragistics.Win.UltraWinMaskedEdit.UltraMaskedEdit":
((UltraMaskedEdit)Ctrl).Text = "";
break;
case "Infragistics.Win.UltraWinEditors.UltraDateTimeEditor":
DateTime dt = DateTime.Now;
string shortDate = dt.ToShortDateString();
((UltraDateTimeEditor)Ctrl).Text = shortDate;
break;
case "System.Windows.Forms.RichTextBox":
((RichTextBox)Ctrl).Text = "";
break;
case " Infragistics.Win.UltraWinGrid.UltraCombo":
((UltraCombo)Ctrl).Text = "";
break;
case "Infragistics.Win.UltraWinEditors.UltraCurrencyEditor":
((UltraCurrencyEditor)Ctrl).Value = 0.0m;
break;
default:
if (Ctrl.Controls.Count > 0)
ClearControls(Ctrl);
break;
}
}
}
use
SELECT COUNT(DISTINCT productId) from table_name WHERE keyword='$keyword'
It is indeed probably allocated from the heap, but without the sources there is no way of knowing.
The typical implementation (taken from some code I have in emacs already) would be:
Singleton * Singleton::getInstance() {
if (!instance) {
instance = new Singleton();
};
return instance;
};
...and rely on the program going out of scope to clean up afterwards.
If you work on a platform where cleanup must be done manually, I'd probably add a manual cleanup routine.
Another issue with doing it this way is that it isn't thread-safe. In a multithreaded environment, two threads could get through the "if" before either has a chance to allocate the new instance (so both would). This still isn't too big of a deal if you are relying on program termination to clean up anyway.
In your SQL Developer Bin Folder find
\sqldeveloper\bin\sqldeveloper.conf
It should be
SetJavaHome \path\to\jdk
You said it was ../../jdk
originally so you could ultimatey do 1 of two things:
SetJavaHome C:\Program Files\Java\jdk1.7.0_60
This is assuming that you have JDK 1.7.60 installed in that directory; you don't want to point it to the bin
folder you want the whole JDK folder.
OR
The second thing you can do is find the jdk
folder in the sqldeveloper folder for me its sqldeveloper\jdk
and copy and paste the contents from C:\Program Files\Java\jdk1.7.0_60
. You then have to revert your change to read
SetJavaHome ../../jdk
in your sqldeveloper.conf
If all else fails you can always redownload the sqldeveloper that already contains the jdk7 all zipped up and ready for you to run at will: Download SQL Developer The file I talk about is called Windows 64-bit - zip file includes the JDK 7
To cross-correlate 1d arrays use numpy.correlate.
For 2d arrays, use scipy.signal.correlate2d.
There is also scipy.stsci.convolve.correlate2d.
There is also matplotlib.pyplot.xcorr which is based on numpy.correlate.
See this post on the SciPy mailing list for some links to different implementations.
Edit: @user333700 added a link to the SciPy ticket for this issue in a comment.
This goes back and forth to and from the \uXXXX format.
class Program {
static void Main( string[] args ) {
string unicodeString = "This function contains a unicode character pi (\u03a0)";
Console.WriteLine( unicodeString );
string encoded = EncodeNonAsciiCharacters(unicodeString);
Console.WriteLine( encoded );
string decoded = DecodeEncodedNonAsciiCharacters( encoded );
Console.WriteLine( decoded );
}
static string EncodeNonAsciiCharacters( string value ) {
StringBuilder sb = new StringBuilder();
foreach( char c in value ) {
if( c > 127 ) {
// This character is too big for ASCII
string encodedValue = "\\u" + ((int) c).ToString( "x4" );
sb.Append( encodedValue );
}
else {
sb.Append( c );
}
}
return sb.ToString();
}
static string DecodeEncodedNonAsciiCharacters( string value ) {
return Regex.Replace(
value,
@"\\u(?<Value>[a-zA-Z0-9]{4})",
m => {
return ((char) int.Parse( m.Groups["Value"].Value, NumberStyles.HexNumber )).ToString();
} );
}
}
Outputs:
This function contains a unicode character pi (p)
This function contains a unicode character pi (\u03a0)
This function contains a unicode character pi (p)
Use whatever you and your team find the most readable.
Other answers have suggested that a new string is created every time you use ""
. This is not true - due to string interning, it will be created either once per assembly or once per AppDomain (or possibly once for the whole process - not sure on that front). This difference is negligible - massively, massively insignificant.
Which you find more readable is a different matter, however. It's subjective and will vary from person to person - so I suggest you find out what most people on your team like, and all go with that for consistency. Personally I find ""
easier to read.
The argument that ""
and " "
are easily mistaken for each other doesn't really wash with me. Unless you're using a proportional font (and I haven't worked with any developers who do) it's pretty easy to tell the difference.
There is no fixed limit on how large a JSON data block is or any of the fields.
There are limits to how much JSON the JavaScript implementation of various browsers can handle (e.g. around 40MB in my experience). See this question for example.
You can't multiply string and float.instead of you try as below.it works fine
totalAmount = salesAmount * float(salesTax)
No. Any valid string is a valid key. It can even have "
as long as you escape it:
{"The \"meaning\" of life":42}
There is perhaps a chance you'll encounter difficulties loading such values into some languages, which try to associate keys with object field names. I don't know of any such cases, however.
After running following command:-
mvn clean package install
I found the issue:
'dependencies.dependency.scope' for org.springframework.boot:spring-boot-starter-data-rest:pom must be one of [provided, compile, runtime, test, system] but is 'import'. @ line 13, column 11
One of the dependency was marked as 'import'. Changing the 'scope' solved the issue for me.
The short answer is:
Func<T1, T2, ..., Tn, Tr>
represents a function, that takes (T1, T2, ..., Tn) arguments and returns Tr.
For example, if you have a function:
double sqr(double x) { return x * x; }
You could save it as some kind of a function-variable:
Func<double, double> f1 = sqr;
Func<double, double> f2 = x => x * x;
And then use exactly as you would use sqr:
f1(2);
Console.WriteLine(f2(f1(4)));
etc.
Remember though, that it's a delegate, for more advanced info refer to documentation.
You need to give the body
and the html
a height too. Otherwise, the body will only be as high as its contents (the single div), and 50% of that will be half the height of this div.
Updated fiddle: http://jsfiddle.net/j8bsS/5/
There are a series of inbuilt functions for coloring the console log:
//For pink background and red text
console.error("Hello World");
//For yellow background and brown text
console.warn("Hello World");
//For just a INFO symbol at the beginning of the text
console.info("Hello World");
//for custom colored text
console.log('%cHello World','color:blue');
//here blue could be replaced by any color code
//for custom colored text with custom background text
console.log('%cHello World','background:red;color:#fff')
The distinction between a bare and non-bare Git repository is artificial and misleading since a workspace is not part of the repository and a repository doesn't require a workspace. Strictly speaking, a Git repository includes those objects that describe the state of the repository. These objects may exist in any directory, but typically exist in the .git
directory in the top-level directory of the workspace. The workspace is a directory tree that represents a particular commit in the repository, but it may exist in any directory or not at all. Environment variable $GIT_DIR
links a workspace to the repository from which it originates.
Git commands git clone
and git init
both have options --bare
that create repositories without an initial workspace. It's unfortunate that Git conflates the two separate, but related concepts of workspace and repository and then uses the confusing term bare to separate the two ideas.
First, you need to create your branch locally
git checkout -b your_branch
After that, you can work locally in your branch, when you are ready to share the branch, push it. The next command push the branch to the remote repository origin and tracks it
git push -u origin your_branch
Your Teammates/colleagues can push to your branch by doing commits and then push explicitly
... work ...
git commit
... work ...
git commit
git push origin HEAD:refs/heads/your_branch
this
is a reference for the DOM element for which the event is being handled (the current target). event.target
refers to the element which initiated the event. They were the same in this case, and can often be, but they aren't necessarily always so.
You can get a good sense of this by reviewing the jQuery event docs, but in summary:
event.currentTarget
The current DOM element within the event bubbling phase.
event.delegateTarget
The element where the currently-called jQuery event handler was attached.
event.relatedTarget
The other DOM element involved in the event, if any.
event.target
The DOM element that initiated the event.
To get the desired functionality using jQuery, you must wrap it in a jQuery object using either: $(this)
or $(evt.target)
.
The .attr()
method only works on a jQuery object, not on a DOM element. $(evt.target).attr('href')
or simply evt.target.href
will give you what you want.
As this Spring's Jira ticket, it is an intentional design. But the following code works for me.
public static Map<String, Object> getAllKnownProperties(Environment env) {
Map<String, Object> rtn = new HashMap<>();
if (env instanceof ConfigurableEnvironment) {
for (PropertySource<?> propertySource : ((ConfigurableEnvironment) env).getPropertySources()) {
if (propertySource instanceof EnumerablePropertySource) {
for (String key : ((EnumerablePropertySource) propertySource).getPropertyNames()) {
rtn.put(key, propertySource.getProperty(key));
}
}
}
}
return rtn;
}
I like both @Qiao first answer and @Or's addition. For a sake of a little less processing I would like to add to Or's answer.
In @Or's answer keeping track of visited node is great. We can also allow the program to exit sooner that it currently is. At some point in the for loop the current_neighbour
will have to be the end
, and once that happens the shortest path is found and program can return.
I would modify the the method as follow, pay close attention to the for loop
graph = {
1: [2, 3, 4],
2: [5, 6],
3: [10],
4: [7, 8],
5: [9, 10],
7: [11, 12],
11: [13]
}
def bfs(graph_to_search, start, end):
queue = [[start]]
visited = set()
while queue:
# Gets the first path in the queue
path = queue.pop(0)
# Gets the last node in the path
vertex = path[-1]
# Checks if we got to the end
if vertex == end:
return path
# We check if the current node is already in the visited nodes set in order not to recheck it
elif vertex not in visited:
# enumerate all adjacent nodes, construct a new path and push it into the queue
for current_neighbour in graph_to_search.get(vertex, []):
new_path = list(path)
new_path.append(current_neighbour)
queue.append(new_path)
#No need to visit other neighbour. Return at once
if current_neighbour == end
return new_path;
# Mark the vertex as visited
visited.add(vertex)
print bfs(graph, 1, 13)
The output and everything else will be the same. However, the code will take less time to process. This is especially useful on larger graphs. I hope this helps someone in the future.
td style is not necessary but will make it easier to see this example in browser
<table>
<tr>
<td style="border: 1px solid black; width: 200px;">
<div style="width: 50%; float: left; text-align: left;">left</div>
<div style="width: 50%; float: left; text-align: right;">right</div>
</td>
</tr>
</table>
Open Bash prompt and type the below mentioned command to make a symbolic link to your file:
A) Goto the folder where you want to create a soft link and typeout the command as mentioned below:
$ ln -s (path-to-file) (symbolic-link-to-file)
$ ln -s /home/user/file new-file
B) Goto your new-file name path and type:
$ ls -lrt (To see if the new-file is linked to the file or not)
Example:
user@user-DT:[~/Desktop/soft]# ln -s /home/user/Desktop/soft/File_B /home/user/Desktop/soft/File_C
user@user-DT:[~/Desktop/soft]# ls -lrt
total 0
-rw-rw-r-- 1 user user 0 Dec 27 16:51 File_B
-rw-rw-r-- 1 user user 0 Dec 27 16:51 File_A
lrwxrwxrwx 1 user user 31 Dec 27 16:53 File_C -> /home/user/Desktop/soft/File_B
Note: Where, File_C -> /home/user/Desktop/soft/File_B Means, File_C is symbolically linked to File_B
Try to Use Flex as that is the new standard of html5.
http://jsfiddle.net/maxspan/1b431hxm/
<div id="row1">
<div id="column1">I am column one</div>
<div id="column2">I am column two</div>
</div>
#row1{
display:flex;
flex-direction:row;
justify-content: space-around;
}
#column1{
display:flex;
flex-direction:column;
}
#column2{
display:flex;
flex-direction:column;
}
I had this issue and I thought I was crazy. I have been using SSH for 20 years. and git over SSH since 2012... but why couldn't I fetch my bitbucket repository on my home computer?
well, I have two bitbucket accounts and had 4 SSH keys loaded inside my agent. even if my .ssh/config was configured to use the right key. when ssh was initializing the connection, it was using them in order loaded into the agent. so I was getting logged into my personal bitbucket account.
then getting a Forbidden error trying to fetch the repo. makes sense.
I unloaded the key from the agent
ssh-add -d ~/.ssh/personal_rsa
then I could fetch the repos.
... Later I found out I can force it to use the specified identity only
Host bitbucket.org-user2
HostName bitbucket.org
User git
IdentityFile ~/.ssh/user2
IdentitiesOnly yes
I didn't know about that last option IdentitiesOnly
from the bitbucket documentation itself
https://blog.developer.atlassian.com/different-ssh-keys-multiple-bitbucket-accounts/
Related to the question, I ended up here when searching for:
How do I make a local repo aware of a changed default branch on GitHub
For completeness, adding the answer:
git remote set-head origin -a
Style the ::-ms-clear
pseudo-element for the box:
.someinput::-ms-clear {
display: none;
}
In addition to Ignacio's answer, CLOCK_REALTIME
can go up forward in leaps, and occasionally backwards. CLOCK_MONOTONIC
does neither; it just keeps going forwards (although it probably resets at reboot).
A robust app needs to be able to tolerate CLOCK_REALTIME
leaping forwards occasionally (and perhaps backwards very slightly very occasionally, although that is more of an edge-case).
Imagine what happens when you suspend your laptop - CLOCK_REALTIME
jumps forwards following the resume, CLOCK_MONOTONIC
does not. Try it on a VM.
Is there a way to do this from the XML?
No, sorry. You can only specify the built-in typefaces through XML.
Is there a way to do it from code in one place, to say that the whole application and all the components should use the custom typeface instead of the default one?
Not that I am aware of.
There are a variety of options for these nowadays:
Font resources and backports in the Android SDK, if you are using appcompat
Third-party libraries for those not using appcompat
, though not all will support defining the font in layout resources
Using requests
import requests
import shutil,os
headers = {
'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36'
}
currentDir = os.getcwd()
path = os.path.join(currentDir,'Images')#saving images to Images folder
def ImageDl(url):
attempts = 0
while attempts < 5:#retry 5 times
try:
filename = url.split('/')[-1]
r = requests.get(url,headers=headers,stream=True,timeout=5)
if r.status_code == 200:
with open(os.path.join(path,filename),'wb') as f:
r.raw.decode_content = True
shutil.copyfileobj(r.raw,f)
print(filename)
break
except Exception as e:
attempts+=1
print(e)
if __name__ == '__main__':
ImageDl(url)
Other answers work, but
To get the full/default price:
$product->get_price_html();
The question is for linux but I had the same issue with git bash on my Windows machine.
My pqsql is installed here:
C:\Program Files\PostgreSQL\10\bin\psql.exe
You can add the location of psql.exe
to your Path environment variable as shown in this screenshot:
After changing the above, please close all cmd
and/or bash
windows, and re-open them (as mentioned in the comments @Ayush Shankar)
You might need to change default logging user using below command.
psql -U postgres
Here postgres
is the username. Without -U
, it will pick the windows loggedin user.
*
*
Linkers and Loaders from LinuxJournal explains this concept with clarity. It also explains how the classic name a.out came. (assembler output)
A quick summary,
c program --> [compiler] --> objectFile --> [linker] --> executable file (say, a.out)
we got the executable, now give this file to your friend or to your customer who is in need of this software :)
when they run this software, say by typing it in command line ./a.out
execute in command line ./a.out --> [Loader] --> [execve] --> program is loaded in memory
Once the program is loaded into the memory, control is transferred to this program by making the PC (program counter) pointing to the first instruction of a.out
select date_format(date_parse(t.payDate,'%Y-%m-%d %H:%i:%S'),'%Y-%m-%d') as payDate
from testTable t
where t.paydate is not null and t.paydate <> '';
Try this:
import java.net.HttpURLConnection;
URL url = new URL("http://www.myurl.com/sample.xml");
HttpURLConnection huc = (HttpURLConnection) url.openConnection();
HttpURLConnection.setFollowRedirects(false);
huc.setConnectTimeout(15 * 1000);
huc.setRequestMethod("GET");
huc.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows; U; Windows NT 6.0; en-US; rv:1.9.1.2) Gecko/20090729 Firefox/3.5.2 (.NET CLR 3.5.30729)");
huc.connect();
InputStream input = huc.getInputStream();
import org.jsoup.nodes.Document;
Document doc = null;
try {
doc = Jsoup.connect("http://www.myurl.com/sample.xml").get();
} catch (Exception e) {
//log error
}
And take look on how to use Jsoup: http://jsoup.org/cookbook/input/load-document-from-url
If you are inserting one record into your table, you can do
INSERT INTO yourTable
VALUES(value1, value2)
But since you want to insert more than one record, you can use a SELECT FROM
in your SQL statement.
so you will want to do this:
INSERT INTO prices (group, id, price)
SELECT 7, articleId, 1.50
from article
WHERE name LIKE 'ABC%'
You could use the Redis Keyspace Notifications by using psubscribe
and "__keyevent@<DB-INDEX>__:expired"
.
With that, each time that a key will expire, you will get a message published on your redis connection.
Regarding your question basically you create a temporary "normal" key using set
with an expiration time in s/ms. It should match the name of the key that you wish to delete in your set.
As your temporary key will be published to your redis connection holding the "__keyevent@0__:expired"
when it expired, you can easily delete your key from your original set as the message will have the name of the key.
A simple example in practice on that page : https://medium.com/@micah1powell/using-redis-keyspace-notifications-for-a-reminder-service-with-node-c05047befec3
doc : https://redis.io/topics/notifications ( look for the flag xE)
See .offset()
here in the jQuery doc. It gives the position relative to the document, not to the parent. You perhaps have .offset()
and .position()
confused. If you want the position in the window instead of the position in the document, you can subtract off the .scrollTop()
and .scrollLeft()
values to account for the scrolled position.
Here's an excerpt from the doc:
The .offset() method allows us to retrieve the current position of an element relative to the document. Contrast this with .position(), which retrieves the current position relative to the offset parent. When positioning a new element on top of an existing one for global manipulation (in particular, for implementing drag-and-drop), .offset() is the more useful.
To combine these:
var offset = $("selector").offset();
var posY = offset.top - $(window).scrollTop();
var posX = offset.left - $(window).scrollLeft();
You can try it here (scroll to see the numbers change): http://jsfiddle.net/jfriend00/hxRPQ/
In order to see the installed compiler version of VC#:
Open Visual Studio command prompt and just type csc then press Enter.
You will see something like following:
Microsoft (R) Visual C# Compiler version 4.0.30319.34209
for Microsoft (R) .NET Framework 4.5
Copyright (C) Microsoft Corporation. All rights reserved.
P.S.: "CSC" stand for "C Sharp Compiler". Actually using this command you run csc.exe which is an executable file which is located in "c:\Windows\Microsoft.NET\Framework\vX.X.XXX". For more information about CSC visit http://www.file.net/process/csc.exe.html
Once you have a library downloaded you can execute this from the MS-DOS command box:
python setup.py install
The setup.py
is located inside every library main folder.
[Update]
Matt Johnsons answer is much better than this one was.
new Date("Fri Jan 20 2012 11:51:36 GMT-0500").toUTCString()
Use a cast:
public enum MyEnum : int {
A = 0,
B = 1,
AB = 2,
}
int val = (int)MyEnum.A;
Find the playlist/manifest with the developer tools network tab. There is always one, as that's how it works. It might have a m3u8 extension that you can type into the Filter. (The youtube-dl tool can also find the m3u8 tool automatically some time give it direct link to the webpage where the video is being displayed.)
Give it to the youtube-dl tool (Download) . It can download much more than just YouTube. It'll auto-download each segment then combine everything with FFmpeg then discard the parts. There is a good chance it supports the site you want to download from natively, and you don't even need to do step #1.
If you find a site that is stubborn and you run into 403 errors... Telerik Fiddler to the rescue. It can catch and save anything transmitted (such as the video file) as it acts as a local proxy. Everything you see/hear can be downloaded, unless it's DRM content like Spotify.
Note: in windows, you can use youtube-dl.exe using "Command Prompt" or creating a batch file. i.e
d:\youtube-dl.exe https://www.youtube.com/watch?v=gbdFOwKHil0
Thanks
You could use location.go(url)
which will basically change your url, without change in route of application.
NOTE this could cause other effect like redirect to child route from the current route.
Related question which describes location.go
will not intimate to Router
to happen changes.
Spent some time working on a solution to my issue and thought it may be of interest. I ran into a problem trying to automate code generation using PowerShell 3.0 on Windows 8. The target IDE was the Keil compiler using MDK-ARM Essential Toolchain 5.24.1. A bit different from OP, as I am using PowerShell natively during the pre-build step. When I tried to #include the generated file, I received the error
fatal error: UTF-16 (LE) byte order mark detected '..\GITVersion.h' but encoding is not supported
I solved the problem by changing the line that generated the output file from:
out-file -FilePath GITVersion.h -InputObject $result
to:
out-file -FilePath GITVersion.h -Encoding ascii -InputObject $result
if u use css class then it will be taken by all 'hr' tags , but if u want for a particular 'hr' use the below code i.e, inline css
<hr style="color:#99CC99" />
if it's not working in chrome try below code:
<hr color="red" />
This will work but there is still the possibility of a null record being returned. Though you may be setting the email address to a string of length zero when you insert the record, you may still want to handle the case of a NULL email address getting into the system somehow.
$aUsers=$this->readToArray('
SELECT `userID`
FROM `users`
WHERE `userID`
IN(SELECT `userID`
FROM `users_indvSettings`
WHERE `indvSettingID`=5 AND `optionID`='.$time.')
AND `email` != "" AND `email` IS NOT NULL
');
Hello I was searching for a solution to reverse sorting a two dimensional numpy array, and I couldn't find anything that worked, but I think I have stumbled on a solution which I am uploading just in case anyone is in the same boat.
x=np.sort(array)
y=np.fliplr(x)
np.sort sorts ascending which is not what you want, but the command fliplr flips the rows left to right! Seems to work!
Hope it helps you out!
I guess it's similar to the suggest about -np.sort(-a) above but I was put off going for that by comment that it doesn't always work. Perhaps my solution won't always work either however I have tested it with a few arrays and seems to be OK.
Change array to string and compare
var arr = [1,2,3],
arr2 = [1,2,3];
console.log(arr.toString() === arr2.toString());
While idealism says use an XML library, IMHO if you have a basic idea of XML then common sense and performance says template it all the way. It's arguably more readable too. Though using the escaping routines of a library is probably a good idea.
Consider this: XML was meant to be written by humans.
Use libraries for generating XML when having your XML as an "object" better models your problem. For example, if pluggable modules participate in the process of building this XML.
Edit: as for how to actually escape XML in templates, use of CDATA or escapeXml(string)
from JSTL are two good solutions, escapeXml(string)
can be used like this:
<%@taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions"%>
<item>${fn:escapeXml(value)}</item>
This applies to "IntelliJ IDEA-2019.2.4" on Mac.
Saw this thread while looking for something else and I know it is super old, but I wanted to add my 2 cents.
NEVER USE VLOOKUP. It's one of the worst performing formulas in excel. Use index match instead. It even works without sorting data, unless you have a -1 or 1 in the end of the match formula (explained more below)
Here is a link with the appropriate formulas.
The Sheet 2 formula would be this: =IF(A2="","",INDEX(Sheet1!B:B,MATCH($A2,Sheet1!$A:$A,0)))
More information on the Index/Match formula
Other fun facts: $ means absolute in a formula. So if you specify $B$1 when filling a formula down or over keeps that same value. If you over $B1, the B remains the same across the formula, but if you fill down, the 1 increases with the row count. Likewise, if you used B$1, filling to the right will increment the B, but keep the reference of row 1.
I also included the use of indirect in the second section. What indirect does is allow you to use the text of another cell in a formula. Since I created a named range sheet1!A:A = ID, sheet1!B:B = Name, and sheet1!C:C=Price, I can use the column name to have the exact same formula, but it uses the column heading to change the search criteria.
Good luck! Hope this helps.
This can now be done as of docker-compose v2+ as part of the build
object;
docker-compose.yml
version: '2'
services:
my_image_name:
build:
context: . #current dir as build context
args:
var1: 1
var2: c
In the above example "var1" and "var2" will be sent to the build environment.
Note: any env variables (specified by using the environment
block) which have the same name as args
variable(s) will override that variable.
The problem is your dataType
and the format of your data
parameter. I just tested this in a sandbox and the following works:
C#
[HttpPost]
public string ConvertLogInfoToXml(string jsonOfLog)
{
return Convert.ToString(jsonOfLog);
}
javascript
<input type="button" onclick="test()"/>
<script type="text/javascript">
function test() {
data = { prop: 1, myArray: [1, "two", 3] };
//'data' is much more complicated in my real application
var jsonOfLog = JSON.stringify(data);
$.ajax({
type: 'POST',
dataType: 'text',
url: "Home/ConvertLogInfoToXml",
data: "jsonOfLog=" + jsonOfLog,
success: function (returnPayload) {
console && console.log("request succeeded");
},
error: function (xhr, ajaxOptions, thrownError) {
console && console.log("request failed");
},
processData: false,
async: false
});
}
</script>
Pay special attention to data
, when sending text, you need to send a variable that matches the name of your parameter. It's not pretty, but it will get you your coveted unformatted string.
When running this, jsonOfLog looks like this in the server function:
jsonOfLog "{\"prop\":1,\"myArray\":[1,\"two\",3]}" string
The HTTP POST header:
Key Value
Request POST /Home/ConvertLogInfoToXml HTTP/1.1
Accept text/plain, */*; q=0.01
Content-Type application/x-www-form-urlencoded; charset=UTF-8
X-Requested-With XMLHttpRequest
Referer http://localhost:50189/
Accept-Language en-US
Accept-Encoding gzip, deflate
User-Agent Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; WOW64; Trident/6.0)
Host localhost:50189
Content-Length 42
DNT 1
Connection Keep-Alive
Cache-Control no-cache
Cookie EnableSSOUser=admin
The HTTP POST body:
jsonOfLog={"prop":1,"myArray":[1,"two",3]}
The response header:
Key Value
Cache-Control private
Content-Type text/html; charset=utf-8
Date Fri, 28 Jun 2013 18:49:24 GMT
Response HTTP/1.1 200 OK
Server Microsoft-IIS/8.0
X-AspNet-Version 4.0.30319
X-AspNetMvc-Version 4.0
X-Powered-By ASP.NET
X-SourceFiles =?UTF-8?B?XFxwc2ZcaG9tZVxkb2N1bWVudHNcdmlzdWFsIHN0dWRpbyAyMDEyXFByb2plY3RzXE12YzRQbGF5Z3JvdW5kXE12YzRQbGF5Z3JvdW5kXEhvbWVcQ29udmVydExvZ0luZm9Ub1htbA==?=
The response body:
{"prop":1,"myArray":[1,"two",3]}
This worked for SQL Server 2005, 2008, and 2012. I found that the sys.identity_columns did not contain all my tables with identity columns.
SELECT a.name AS TableName, b.name AS IdentityColumn
FROM sys.sysobjects a
JOIN sys.syscolumns b
ON a.id = b.id
WHERE is_identity = 1
ORDER BY name;
Looking at the documentation page the status column can also be utilized. Also you can add the four part identifier and it will work across different servers.
SELECT a.name AS TableName, b.name AS IdentityColumn
FROM [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.sysobjects a
JOIN [YOUR_SERVER_NAME].[YOUR_DB_NAME].sys.syscolumns b
ON a.id = b.id
WHERE is_identity = 1
ORDER BY name;
Source: https://msdn.microsoft.com/en-us/library/ms186816.aspx
Just pick up the TDM-GCC 64x package. (It constains both the 32 and 64 bit versions of the MinGW toolchain and comes within a neat installer.) More importantly, it contains something called the "winpthread" library.
It comprises of the pthread.h
header, libwinpthread.a
, libwinpthread.dll.a
static libraries for both 32-bit and 64-bit and the required .dlls libwinpthread-1.dll
and libwinpthread_64-1.dll
(this, as of 01-06-2016).
You'll need to link to the libwinpthread.a
library during build. Other than that, your code can be the same as for native Pthread code on Linux. I've so far successfully used it to compile a few basic Pthread programs in 64-bit on windows.
Alternatively, you can use the following library which wraps the windows threading API into the pthreads API: pthreads-win32.
The above two seem to be the most well known ways for this.
Hope this helps.
I see what you are trying to do, you are trying to use the <body>
tag as the container for the main content of the page. Instead, use the <main>
tag, as specified in the HTML5 spec. I use this layout:
<!DOCTYPE html>
<html>
<head> *Metadata* </head>
<body>
<header>
*<h1> and other important stuff </h1>*
<nav> *Usually a formatted <Ul>* </nav>
</header>
<main> *All my content* </main>
<footer> *Copyright, links, social media etc* </footer>
</body>
</html>
I'm not 100% sure but I think that anything outside the <body>
tag is considered metadata and will not be rendered by the browser. I don't think that the DOM can access it either.
To conclude, use the <main>
tag for your content and keep formatting your HTML the correct way as you have in your first code snippet. You used the <section>
tag but I think that comes with some weird formatting issues when you try to apply CSS.
the solution of 'bootstrap modal is not opening' is, put your Jquery CDN first in the head tag (after starting head tag).
I wasted two days in finding this problem.
To connect Excel to Access using VBA is very useful I use it in my profession everyday. The connection string I use is according to the program found in the link below. The program can be automated to do multiple connections or tasks in on shot but the basic connection code looks the same. Good luck!
If the project is Maven, you can try this way :
Then the import issue should be solved .
You can store them in tasks, then await them all:
var catTask = FeedCat();
var houseTask = SellHouse();
var carTask = BuyCar();
await Task.WhenAll(catTask, houseTask, carTask);
Cat cat = await catTask;
House house = await houseTask;
Car car = await carTask;
If you want this sentence from foo.bar import foo2
to be loaded dynamically, you should do this
foo = __import__("foo")
bar = getattr(foo,"bar")
foo2 = getattr(bar,"foo2")
instance = foo2()
Try this:
var idColumn="id";
var list = dt.DefaultView
.ToTable(true, idColumn)
.Rows
.Cast<DataRow>()
.Select(row => row[idColumn])
.ToList();
1) you are calling it wrong way try:
$(input[name="searchBar"]).val('hi')
2) if it doesn't work call your .js file at the end of the page or trigger your function on document.ready event
$(document).ready(function() {
$(input[name="searchBar"]).val('hi');
});
Python has a min()
built-in function:
>>> darr = [1, 3.14159, 1e100, -2.71828]
>>> min(darr)
-2.71828
I found I had the same error. I was compiling a code with both lapack and blas. When I switched the order that the two libraries were called the error went away.
"LAPACK_LIB = -llapack -lblas" worked where "LAPACK_LIB = -lblas -llapack" gave the error described above.
This might be useful:
objectMapper.writeValue(new File("c:\\employee.json"), employee);
// display to console
Object json = objectMapper.readValue(
objectMapper.writeValueAsString(employee), Object.class);
System.out.println(objectMapper.writerWithDefaultPrettyPrinter()
.writeValueAsString(json));
For some weird reason "Java SE Development Kit 8u151" gives this trouble. Just install, "Java SE Development Kit 8u152" from the following link-
http://www.oracle.com/technetwork/java/javase/downloads/jdk8-downloads-2133151.html
It should work then.
Check your short_open_tag setting (use <?php phpinfo() ?>
to see its current setting).
This has worked for me in the past and it will even expand environment variables in the file if it can.
for /F "delims=" %%a in (LogName.txt) do (
echo %%a>>MyDestination.txt
)
I think you have to write some extra code. For example:
if 'MICHAEL89' in map(lambda name: name.upper(), USERNAMES):
...
In this case we are forming a new list with all entries in USERNAMES
converted to upper case and then comparing against this new list.
Update
As @viraptor says, it is even better to use a generator instead of map
. See @Nathon's answer.
Other 2 peoples on SO proposed possible CSS-only solution to the problem. David Thomas' solution is perfect but has the limit that scrollbar is visible only during scrolling.
In order to have scrollbars always visible, is possible to followin guidelines suggested on the following links:
SUPER KEY:
Attribute or set of attributes used to uniquely identify tuples in the database.
CANDIDATE KEY:
PRIMARY KEY:
one of the candidate key which is used to identify records in DB uniquely
not null
I think that the best solution would be to use Regular expressions. It's cleanest and probably the most effective. Regular Expressions are supported in all commonly used DB engines.
In MySql there is RLIKE
operator so your query would be something like:
SELECT * FROM buckets WHERE bucketname RLIKE 'Stylus|2100'
I'm not very strong in regexp so I hope the expression is ok.
Edit
The RegExp should rather be:
SELECT * FROM buckets WHERE bucketname RLIKE '(?=.*Stylus)(?=.*2100)'
More on MySql regexp support:
http://dev.mysql.com/doc/refman/5.1/en/regexp.html#operator_regexp
way too late for the party here but i will still add my $0.02, Google has released a free sample called universal music player with which you can learn to stream music across all android platforms(auto, watch,mobile,tv..) it uses service to play music in the background, do check it out very helpful. here's the link to the project
https://github.com/googlesamples/android-UniversalMusicPlayer
ddlData.SelectedIndex
will contain the int
value To select the specific value into DropDown
:
ddlData.SelectedIndex=ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
return
type of ddlData.Items.IndexOf(ddlData.Items.FindByText("value"));
is int
.
Maybe some AJAX page content injection could be used as an alternative, though I still can't get around why your teacher would refuse to rid the website of frames.
Additionally, is there any specific reason you personally want to us HTML5?
But if not, I believe <iframe>
s are still around.
You can access individual elements with the array [] operator:
<c:out value="${attachments[0].id}" />
This will work for arrays and lists. It won't work for maps and sets. In that case you must put the key of the element inside the brackets.
Dim sSheetName As String
Dim sConnection As String
Dim dtTablesList As DataTable
Dim oleExcelCommand As OleDbCommand
Dim oleExcelReader As OleDbDataReader
Dim oleExcelConnection As OleDbConnection
sConnection = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Test.xls;Extended Properties=""Excel 12.0;HDR=No;IMEX=1"""
oleExcelConnection = New OleDbConnection(sConnection)
oleExcelConnection.Open()
dtTablesList = oleExcelConnection.GetSchema("Tables")
If dtTablesList.Rows.Count > 0 Then
sSheetName = dtTablesList.Rows(0)("TABLE_NAME").ToString
End If
dtTablesList.Clear()
dtTablesList.Dispose()
If sSheetName <> "" Then
oleExcelCommand = oleExcelConnection.CreateCommand()
oleExcelCommand.CommandText = "Select * From [" & sSheetName & "]"
oleExcelCommand.CommandType = CommandType.Text
oleExcelReader = oleExcelCommand.ExecuteReader
nOutputRow = 0
While oleExcelReader.Read
End While
oleExcelReader.Close()
End If
oleExcelConnection.Close()
Exiting from Java running process is very easy, basically you need to do just two simple things:
System.exit(...)
at at application's quit point.
For example, if your application is frame based, you can add listener WindowAdapter
and and call System.exit(...)
inside its method windowClosing(WindowEvent e)
. Note: you must call System.exit(...)
otherwise your program is error involved.
System.exit(...)
at right point, but It does not mean that the method can be called always, because unexpected java exceptions may prevent the method from been called. This is strongly related to your programming skills.
** Following is a simplest sample (JFrame
based) which shows you how to call exit method
import java.awt.event.*;
import javax.swing.*;
public class ExitApp extends JFrame
{
public ExitApp()
{
addWindowListener(new WindowAdapter()
{
public void windowClosing(WindowEvent e)
{
dispose();
System.exit(0); //calling the method is a must
}
});
}
public static void main(String[] args)
{
ExitApp app=new ExitApp();
app.setBounds(133,100,532,400);
app.setVisible(true);
}
}
It can also be done with an IsoDateTimeConverter
instance, without changing global formatting settings:
string json = JsonConvert.SerializeObject(yourObject,
new IsoDateTimeConverter() { DateTimeFormat = "yyyy-MM-dd HH:mm:ss" });
This uses the JsonConvert.SerializeObject
overload that takes a params JsonConverter[]
argument.
It's also possible to use a regular expression to achieve this when you want to test for any whitespace character and not just a space.
var text = "sossjj ssskkk";
var regex = new Regex(@"\s");
regex.IsMatch(text); // true
I think you want to specify
-H "Content-Type:text/xml"
with a colon, not an equals.
This should accomplish what you want to do. I just tested it on a sheet of mine; let me know if this doesn't work. LTrim is if you only have leading spaces; the Trim function can be used as well as it takes care of leading and trailing spaces. Replace the range of cells in the area I have as "A1:C50" and also make sure to change "Sheet1" to the name of the sheet you're working on.
Dim cell As Range, areaToTrim As Range
Set areaToTrim = Sheet1.Range("A1:C50")
For Each cell In areaToTrim
cell.Value = LTrim(cell.Value)
Next cell
if you meant comparing nth item with n+1 th item in the list you could also do with
>>> for i in range(len(list[:-1])):
... print list[i]>list[i+1]
note there is no hard coding going on there. This should be ok unless you feel otherwise.
setup.py
is a python file, the presence of which is an indication that the module/package you are about to install has likely been packaged and distributed with Distutils, which is the standard for distributing Python Modules.
This allows you to easily install Python packages. Often it's enough to write:
$ pip install .
pip
will use setup.py
to install your module. Avoid calling setup.py
directly.
https://docs.python.org/3/installing/index.html#installing-index
You are not breaking code over multiple lines, but rather a single identifier. There is a difference.
For your issue, try
R> setwd(paste("~/a/very/long/path/here",
"/and/then/some/more",
"/and/then/some/more",
"/and/then/some/more", sep=""))
which also illustrates that it is perfectly fine to break code across multiple lines.
if you have downloaded a project,do in the project
npm install
Please see below typescript for re-applying css class again to an element to override parent container (usually a framework component) css styles and force your custom styles. Your app framework (be it angular/react, probably does this so the parent container css was re-applied and none of your expected effects in css-class-name is showing up for your child element. Call this.overrideParentCssRule(childElement, 'css-class-name'); to do what the framework just did (call this in document.ready or end of event handler):
overrideParentCssRule(elem: HTMLElement, className: string) {
let cssRules = this.getCSSStyle(className);
for (let r: number = 0; r < cssRules.length; r++) {
let rule: CSSStyleRule = cssRules[r];
Object.keys(rule.style).forEach(s => {
if (isNaN(Number(s)) && rule.style[s]) {
elem.style[s] = rule.style[s];
}
});
}
}
Not a technical answer but you might want to check the search box for the logcat. If there is any character inputted, your logcat will be empty as it will be searching for that certain character or word, and then if its not present, your logcat log will be totally empty.
Put export LD_LIBRARY_PATH=/usr/local/lib
in ~/.bashrc
[preferably towards end of script to avoid any overrides in between, Default ~/.bashrc
comes with many if-else
statements]
Post that whenever you open a new terminal/konsole, LD_LIBRARY_PATH
will be reflected
The appropriate regex would be the ' char followed by any number of any chars [including zero chars] ending with an end of string/line token:
'.*$
And if you wanted to capture everything after the ' char but not include it in the output, you would use:
(?<=').*$
This basically says give me all characters that follow the ' char until the end of the line.
Edit: It has been noted that $ is implicit when using .* and therefore not strictly required, therefore the pattern:
'.*
is technically correct, however it is clearer to be specific and avoid confusion for later code maintenance, hence my use of the $. It is my belief that it is always better to declare explicit behaviour than rely on implicit behaviour in situations where clarity could be questioned.
To check the Python version in a Jupyter notebook, you can use:
from platform import python_version
print(python_version())
to get version number, as:
3.7.3
or:
import sys
print(sys.version)
to get more information, as
3.7.3 (default, Apr 24 2019, 13:20:13) [MSC v.1915 32 bit (Intel)]
or:
sys.version_info
to get major, minor and micro versions, as
sys.version_info(major=3, minor=7, micro=3, releaselevel='final', serial=0)
This worked for me, curly braces are not required.
ng-style="{'background-image':'url(../../../app/img/notification/'+notification.icon+'.png)'}"
notification.icon here is scope variable.
You can open emacs (in terminal mode, using emacs -nw
for instance), and then use Hexl mode: M-x hexl-mode
.
https://www.gnu.org/software/emacs/manual/html_node/emacs/Editing-Binary-Files.html
This worked for me
.form-control {
box-shadow: none!important;}
Your log indicates ClientAbortException, which occurs when your HTTP client drops the connection with the server and this happened before server could close the server socket Connection.
Just a tip for this, you don't need the BEGIN and END if it only contains a single statement.
ie:
IF(@Trans_type = 'subscr_signup')
set @tmpType = 'premium'
ELSE iF(@Trans_type = 'subscr_cancel')
set @tmpType = 'basic'
To get the right ownership, you can set the group setuid bit on the directory with
chmod g+rwxs dirname
This will ensure that files created in the directory are owned by the group. You should then make sure everyone runs with umask 002 or 007 or something of that nature---this is why Debian and many other linux systems are configured with per-user groups by default.
I don't know of a way to force the permissions you want if the user's umask is too strong.
set /a countfiles-=%countfiles%
This will set countfiles to 0. I think you want to decrease it by 1, so use this instead:
set /a countfiles-=1
I'm not sure if the for loop will work, better try something like this:
:loop
cscript /nologo c:\deletefile.vbs %BACKUPDIR%
set /a countfiles-=1
if %countfiles% GTR 21 goto loop
In short, always prefer initialization lists when possible. 2 reasons:
If you do not mention a variable in a class's initialization list, the constructor will default initialize it before entering the body of the constructor you've written. This means that option 2 will lead to each variable being written to twice, once for the default initialization and once for the assignment in the constructor body.
Also, as mentioned by mwigdahl and avada in other answers, const members and reference members can only be initialized in an initialization list.
Also note that variables are always initialized on the order they are declared in the class declaration, not in the order they are listed in an initialization list (with proper warnings enabled a compiler will warn you if a list is written out of order). Similarly, destructors will call member destructors in the opposite order, last to first in the class declaration, after the code in your class's destructor has executed.
This macro adds a hyperlink to the worksheet with the same name, I also modify the range to be more flexible, just change the first cell in the code. Works like a charm
Sub hyper()
Dim cl As Range
Dim nS As String
Set MyRange = Sheets("Sheet1").Range("B16")
Set MyRange = Range(MyRange, MyRange.End(xlDown))
For Each cl In MyRange
nS = cl.Value
cl.Hyperlinks.Add Anchor:=cl, Address:="", SubAddress:="'" & nS & "'" & "!B16", TextToDisplay:=nS
Next
End Sub
Well, as /?__a=1
stopped working by now, it's better to use curl and parse the instagram page as written at this answer: Generate access token Instagram API, without having to log in?
This is what worked for me (Windows 10) :
Tip : You can pin mysql.exe to Start Menu so you don't always have to search for this folder
Example: button.titleLabel?.font = UIFont(name: "HelveticaNeue-Bold", size: 12)
The OR operator needs a much more complex evaluation process than the IN construct because it allows many conditions, not only equals like IN.
Here is a like of what you can use with OR but that are not compatible with IN: greater. greater or equal, less, less or equal, LIKE and some more like the oracle REGEXP_LIKE. In addition consider that the conditions may not always compare the same value.
For the query optimizer it's easier to to manage the IN operator because is only a construct that defines the OR operator on multiple conditions with = operator on the same value. If you use the OR operator the optimizer may not consider that you're always using the = operator on the same value and, if it doesn't perform a deeper and very much more complex elaboration, it could probably exclude that there may be only = operators for the same values on all the involved conditions, with a consequent preclusion of optimized search methods like the already mentioned binary search.
[EDIT] Probably an optimizer may not implement optimized IN evaluation process, but this doesn't exclude that one time it could happen(with a database version upgrade). So if you use the OR operator that optimized elaboration will not be used in your case.
There are no decompilers which I know about. W32dasm is good Win32 disassembler.
Like nearly everyone else said, go to file -> Import Settings.
But if you don't see the "Import Settings" option under the file menu, you need to disable 2 plugins : IDE Settings Sync and Settings Repository
zip -r "$destFileName.zip" "$srcFileName" -x "*/\__MACOSX" -x "*/\.*"
-x "*/\__MACOSX"
: ignore __MACOSX as you mention.-x "*/\.*"
: ignore any hidden file, such as .DS_Store .Also, you can build Automator Service to make it easily to use in Finder. Check link below to see detail if you need.
ifeq ($(CHIPSET),8960)
BLD_ENV_BUILD_ID="8960"
else ifeq ($(CHIPSET),8930)
BLD_ENV_BUILD_ID="8930"
else ifeq ($(CHIPSET),8064)
BLD_ENV_BUILD_ID="8064"
else ifeq ($(CHIPSET), 9x15)
BLD_ENV_BUILD_ID="9615"
else
BLD_ENV_BUILD_ID=
endif
You are trying to compare strings inside an arithmetic command (((...))
). Use [[
instead.
if [[ $username == "$username1" && $password == "$password1" ]] ||
[[ $username == "$username2" && $password == "$password2" ]]; then
Note that I've reduced this to two separate tests joined by ||
, with the &&
moved inside the tests. This is because the shell operators &&
and ||
have equal precedence and are simply evaluated from left to right. As a result, it's not generally true that a && b || c && d
is equivalent to the intended ( a && b ) || ( c && d )
.
Currently, and with the new versions of Mysql can insert the current date automatically without adding a code in your PHP file. You can achieve that from Mysql while setting up your database as follows:
Now, any new post will automatically get a unique date and time. Hope this can help.
This should be enough to force an IE
user to drop compatibility mode in any IE
version:
<meta http-equiv="X-UA-Compatible" content="IE=EDGE" />
However, there are a couple of caveats one should be aware of:
<head>
. Only the <title>
tag may be placed above it.If you don't do that, you'll get an error on IE9
Dev Tools: X-UA-Compatible META tag ignored because document mode is already finalized.
If you want this markup to validate, make sure you remember to close the meta
tag with a />
instead of just >
.
Starting with IE11
, edge mode is the preferred document mode. To support/enable that, use the HTML5 document type declaration <!doctype html>
.
If you need to support webfonts on IE7
, make sure you use <!DOCTYPE html>
. I've tested it and found that rendering webfonts on IE7
got pretty unreliable when using <!doctype html>
.
The use of Google Chrome Frame is popular, but unfortunately it's going to be dropped sometime this month, Jan. 2014.
<meta http-equiv="X-UA-Compatible" content="IE=EDGE,chrome=1">
Extensive related info here. The tip on using it as the first meta tag is on a previously mentioned source here, which has been updated.
You can also configure your component like this :
package mypackage;
import org.springframework.context.annotation.Configuration;
@Configuration
public class MyConstructorClassConfig {
@Bean
public MyConstructorClass myConstructorClass(){
return new myConstructorClass("foobar");
}
}
}
With the Bean
annotation, you are telling Spring to register the returned bean in the BeanFactory
.
So you can autowire it as you wish.
This is one of the popular question in any SQL interview. I am going to write down different queries to find out the nth highest value of a column.
I have created a table named “Emloyee” by running the below script.
CREATE TABLE Employee([Eid] [float] NULL,[Ename] [nvarchar](255) NULL,[Basic_Sal] [float] NULL)
Now I am going to insert 8 rows into this table by running below insert statement.
insert into Employee values(1,'Neeraj',45000)
insert into Employee values(2,'Ankit',5000)
insert into Employee values(3,'Akshay',6000)
insert into Employee values(4,'Ramesh',7600)
insert into Employee values(5,'Vikas',4000)
insert into Employee values(7,'Neha',8500)
insert into Employee values(8,'Shivika',4500)
insert into Employee values(9,'Tarun',9500)
Now we will find out 3rd highest Basic_sal from the above table using different queries. I have run the below query in management studio and below is the result.
select * from Employee order by Basic_Sal desc
We can see in the above image that 3rd highest Basic Salary would be 8500. I am writing 3 different ways of doing the same. By running all three mentioned below queries we will get same result i.e. 8500.
First Way: - Using row number function
select Ename,Basic_sal
from(
select Ename,Basic_Sal,ROW_NUMBER() over (order by Basic_Sal desc) as rowid from Employee
)A
where rowid=2
And to complement Rich's recursive answer, a non-recursive method.
Public Sub NonRecursiveMethod()
Dim fso, oFolder, oSubfolder, oFile, queue As Collection
Set fso = CreateObject("Scripting.FileSystemObject")
Set queue = New Collection
queue.Add fso.GetFolder("your folder path variable") 'obviously replace
Do While queue.Count > 0
Set oFolder = queue(1)
queue.Remove 1 'dequeue
'...insert any folder processing code here...
For Each oSubfolder In oFolder.SubFolders
queue.Add oSubfolder 'enqueue
Next oSubfolder
For Each oFile In oFolder.Files
'...insert any file processing code here...
Next oFile
Loop
End Sub
You can use a queue for FIFO behaviour (shown above), or you can use a stack for LIFO behaviour which would process in the same order as a recursive approach (replace Set oFolder = queue(1)
with Set oFolder = queue(queue.Count)
and replace queue.Remove(1)
with queue.Remove(queue.Count)
, and probably rename the variable...)
str_replace(PHP_EOL, null, $str);