Also notice a common pitfall: The non lazy operators have precedence over the lazy ones, so:
boolean a, b, c;
a || b && c; //resolves to a || (b && c)
a | b && c; //resolves to (a | b) && c
Be careful when mixing them.
I had this error too on the Windows machine.
My solution.
1) Download your language files from https://github.com/tesseract-ocr/tessdata/tree/3.04.00
For example, for eng, I downloaded all files with eng prefix.
2) Put them into tessdata directory inside of some folder. Add this folder into System Path variables as TESSDATA_PREFIX.
Result will be System env var: TESSDATA_PREFIX=D:/Java/OCR And OCR folder has tessdata with languages files.
This is a screenshot of the directory:
I'm hoping your problem has been solved by now. If not, try this... It looks like you have server=y
for both your app and IDEA. IDEA should probably be server=n
. Also, the (IDEA) client should have an address that includes both the host name and the port, e.g., address=127.0.0.1:9009
.
The only thing that worked for me was a combination of the above:
First the li
in the ul
<li><a onclick="LoadTab2_1()" href="JavaScript:void(0)">All Assigned</a></li>
Then in the LoadTab2_1 I manually switched the tab divs.
$("#tabs-2-1").hide();
$("#tabs-2-2").show();
This is because the disconnection of the also disconnects the action in the tabs.
You also need to manually do the tab styling when the primary tab changes things.
$("#secTab1").addClass("ui-tabs-active").addClass("ui-state-active").addClass("ui-state-hover").addClass("ui-state-focus");
$("#secTab1 a").css("color", "#ffffff");
<script>
// Instantiate your javascript function
niceJavascriptRoutine = null;
// Begin jQuery
$(document).ready(function() {
// Your jQuery function
function niceJqueryRoutine() {
// some code
}
// Point the javascript function to the jQuery function
niceJavaScriptRoutine = niceJueryRoutine;
});
</script>
You can use an svn changelist to keep track of a set of files that you want to commit together.
The linked page goes into lots of details, but here's an executive summary example:
$ svn changelist my-changelist mydir/dir1/file1.c mydir/dir2/myfile1.h
$ svn changelist my-changelist mydir/dir3/myfile3.c etc.
... (add all the files you want to commit together at your own rate)
$ svn commit -m"log msg" --changelist my-changelist
This query generates a list of dates 4000 days in the future and 5000 in the past as of today (inspired on http://blogs.x2line.com/al/articles/207.aspx):
SELECT * FROM (SELECT
(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) AS Date,
year(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) as Year,
month(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) as Month,
day(CONVERT(SMALLDATETIME, CONVERT(CHAR,GETDATE() ,103)) + 4000 -
n4.num * 1000 -
n3.num * 100 -
n2.num * 10 -
n1.num) as Day
FROM (SELECT 0 AS num union ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) n1
,(SELECT 0 AS num UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) n2
,(SELECT 0 AS num union ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8 UNION ALL
SELECT 9) n3
,(SELECT 0 AS num UNION ALL
SELECT 1 UNION ALL
SELECT 2 UNION ALL
SELECT 3 UNION ALL
SELECT 4 UNION ALL
SELECT 5 UNION ALL
SELECT 6 UNION ALL
SELECT 7 UNION ALL
SELECT 8) n4
) GenCalendar ORDER BY 1
# this is comment
this isn't comment
is the way to do it. You can place it anywhere in the line and anything that comes later will be ignored
SE defines a set of capabilities and functionalities; there are more complex editions (Enterprise Edition – EE) and simpler ones (Micro Edition – ME – for mobile environments).
The JDK includes the compiler and other tools needed to develop Java applications; JRE does not. So, to run a Java application someone else provides, you need JRE; to develop a Java application, you need JDK.
Edited: As Chris Marasti-Georg pointed out in a comment, you can find out lots of information at Sun's Java web site, and in particular from the Java SE section, (2nd option, Java SE Development Kit (JDK) 6 Update 10).
Edited 2011-04-06:
The world turns, and Java is now managed by Oracle, which bought Sun. Later this year, the sun.com
domain is supposed to go dark. The new page (based on a redirect) is this Java page at the Oracle Tech Network. (See also java.com.)
Edited 2013-01-11: And the world keeps on turning (2012-12-21 notwithstanding), and lo and behold, JRE 6 is about to reach its end of support. Oracle says no more public updates to Java 6 after February 2013.
Within a given version of Java, this answer remains valid. JDK is the Java Development Kit, JRE is the Java Runtime Environment, Java SE is the standard edition, and so on. But the version 6 (1.6) is becoming antiquated.
Edited 2015-04-29: And with another couple of revolutions around the sun, the time has come for the end of support for Java SE 7, too. In April 2015, Oracle affirmed that it was no longer providing public updates to Java SE 7. The tentative end of public updates for Java SE 8 is March 2017, but that end date is subject to change (later, not earlier).
Using Javascript
var elemDiv = document.createElement('div');
elemDiv.style.cssText = 'position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;';
document.body.appendChild(elemDiv);
Using jQuery
$('body').append('<div style="position:absolute;width:100%;height:100%;opacity:0.3;z-index:100;background:#000;"></div>');
perhaps
$id = isset($_GET['id'])?$_GET['id']:null;
and
$other_var = isset($_GET['othervar'])?$_GET['othervar']:null;
You must reload your TableView in main thread only. Otherwise your app will be crashed or will be updated after some time. For every UI update it is recommended to use main thread.
//To update UI only this below code is enough
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()//Your tableView here
})
//Perform some task and update UI immediately.
DispatchQueue.global(qos: .userInitiated).async {
// Call your function here
DispatchQueue.main.async {
// Update UI
self.tableView.reloadData()
}
}
//To call or execute function after some time and update UI
DispatchQueue.main.asyncAfter(deadline: .now() + 5.0) {
//Here call your function
//If you want to do changes in UI use this
DispatchQueue.main.async(execute: {
//Update UI
self.tableView.reloadData()
})
}
I was not absolutely happy with any of the answers. But I have picked up some ideas from @Matt Way.
Here is my solution:
Definitions:
const Switch = props => {
const { test, children = null } = props;
return children && children.find(child => child && child.props && child.props.casevalue === test) || null;
}
const Case = ({ casevalue = false, children = null }) => <div casevalue={`${casevalue}`}>{children}</div>;
Case.propTypes = {
casevalue: PropTypes.string.isRequired,
children: PropTypes.node.isRequired,
}
const Default = ({ children }) => children || <h1>NO_RESULT</h1>;
const SwitchCase = ({ test, cases = [], defaultValue = null }) => {
const defaultVal = defaultValue
&& React.cloneElement(defaultValue, { key: 'default-key', casevalue: `${test}` })
|| <Default key='default-key' casevalue={`${test}`} />;
return (
<Switch test={`${test}`} >
{
cases.map((cas, i) => {
const { props = {} } = cas || {};
const { casevalue = false, ...rest } = props || {};
return <Case key={`case-key-${i}`} casevalue={`${casevalue}`}>{ React.cloneElement(cas, rest)}</Case>
})
.concat(defaultVal)
}
</Switch>
);
}
Usage:
<SwitchCase
cases={[
<div casevalue={`${false}`}>#1</div>,
<div casevalue={`${true}`}>#2</div>,
<div casevalue={`${false}`}>#3</div>,
]}
defaultValue={<h1>...nothing to see here</h1>} // You can leave it blank.
test={`${true}`}
/>
If you literally want a one line equivalent to the commands in your original question, you could alias:
mongo --eval "db.getSiblingDB('admin').shutdownServer()"
Mark's answer on starting and stopping MongoDB via services is the more typical (and recommended) administrative approach.
According to the documentation, the route was found, even though the resource wasn't.
Note: This is not intended to be used for when a resource is not found. There is a difference between the router not finding a matched path and a valid URL that results in a resource not being found. The url courses/123 is a valid url and results in a matched route, therefore it was "found" as far as routing is concerned. Then, if we fetch some data and discover that the course 123 does not exist, we do not want to transition to a new route. Just like on the server, you go ahead and serve the url but render different UI (and use a different status code). You shouldn't ever try to transition to a NotFoundRoute.
So, you could always add a line in the Router.run()
before React.render()
to check if the resource is valid. Just pass a prop down to the component or override the Handler
component with a custom one to display the NotFound view.
You can find the log within you Magento root directory under
var/log
there are two types of log files system.log and exception.log
you need to give the correct permission to var folder, then enable logging from your Magento admin by going to
System > Configuration> Developer > Log Settings > Enable = Yes
system.log is used for general debugging and catches almost all log entries from Magento, including warning, debug and errors messages from both native and custom modules.
exception.log is reserved for exceptions only, for example when you are using try-catch statement.
To output to either the default system.log or the exception.log see the following code examples:
Mage::log('My log entry');
Mage::log('My log message: '.$myVariable);
Mage::log($myArray);
Mage::log($myObject);
Mage::logException($e);
You can create your own log file for more debugging
Mage::log('My log entry', null, 'mylogfile.log');
NOTE: Potentially outdated. ECMAScript 2017 includes
String.prototype.padStart
.
You'll have to convert the number to a string since numbers don't make sense with leading zeros. Something like this:
function pad(num, size) {
num = num.toString();
while (num.length < size) num = "0" + num;
return num;
}
Or, if you know you'd never be using more than X number of zeros, this might be better. This assumes you'd never want more than 10 digits.
function pad(num, size) {
var s = "000000000" + num;
return s.substr(s.length-size);
}
If you care about negative numbers you'll have to strip the -
and read it.
For Eclipse Mars the following worked
As suggested by @linqu you should not change your data for presentation. Since pandas 0.17.1, (conditional) formatting was made easier. Quoting the documentation:
You can apply conditional formatting, the visual styling of a
DataFrame
depending on the data within, by using theDataFrame.style
property. This is a property that returns apandas.Styler
object, which has useful methods for formatting and displayingDataFrames
.
For your example, that would be (the usual table will show up in Jupyter):
df.style.format({
'var1': '{:,.2f}'.format,
'var2': '{:,.2f}'.format,
'var3': '{:,.2%}'.format,
})
I do not like use pure "a" tag, too much typing. So I come with solution. In view it look
<%: Html.ActionLink(node.Name, "Show", "Browse",
Dic.Route("id", node.Id), Dic.New("data-nodeId", node.Id)) %>
Implementation of Dic class
public static class Dic
{
public static Dictionary<string, object> New(params object[] attrs)
{
var res = new Dictionary<string, object>();
for (var i = 0; i < attrs.Length; i = i + 2)
res.Add(attrs[i].ToString(), attrs[i + 1]);
return res;
}
public static RouteValueDictionary Route(params object[] attrs)
{
return new RouteValueDictionary(Dic.New(attrs));
}
}
1 - Your malloc() is wrong.
2 - You are overstepping the bounds of the allocated memory
3 - You should initialize your allocated memory
Here is the program with all the changes needed. I compiled and ran... no errors or warnings.
#include <stdio.h>
#include <stdlib.h> //malloc
#include <math.h> //sine
#include <string.h>
#define TIME 255
#define HARM 32
int main (void) {
double sineRads;
double sine;
int tcount = 0;
int hcount = 0;
/* allocate some heap memory for the large array of waveform data */
double *ptr = malloc(sizeof(double) * TIME);
//memset( ptr, 0x00, sizeof(double) * TIME); may not always set double to 0
for( tcount = 0; tcount < TIME; tcount++ )
{
ptr[tcount] = 0;
}
tcount = 0;
if (NULL == ptr) {
printf("ERROR: couldn't allocate waveform memory!\n");
} else {
/*evaluate and add harmonic amplitudes for each time step */
for(tcount = 0; tcount < TIME; tcount++){
for(hcount = 0; hcount <= HARM; hcount++){
sineRads = ((double)tcount / (double)TIME) * (2*M_PI); //angular frequency
sineRads *= (hcount + 1); //scale frequency by harmonic number
sine = sin(sineRads);
ptr[tcount] += sine; //add to other results for this time step
}
}
free(ptr);
ptr = NULL;
}
return 0;
}
Full easy copy and paste code built from @ZacBowling's solution (https://stackoverflow.com/a/1535427/2298002)
this will also bring the user to your app settings and allow them to enable immediately
I also added in a solution for checking if location services is enabled (and brings to settings as well)
// check if notification service is enabled
+ (void)checkNotificationServicesEnabled
{
if (![[UIApplication sharedApplication] isRegisteredForRemoteNotifications])
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Notification Services Disabled!"
message:@"Yo don't mess around bro! Enabling your Notifications allows you to receive important updates"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
alertView.tag = 300;
[alertView show];
return;
}
}
// check if location service is enabled (ref: https://stackoverflow.com/a/35982887/2298002)
+ (void)checkLocationServicesEnabled
{
//Checking authorization status
if (![CLLocationManager locationServicesEnabled] || [CLLocationManager authorizationStatus] == kCLAuthorizationStatusDenied)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Location Services Disabled!"
message:@"You need to enable your GPS location right now!!"
delegate:self
cancelButtonTitle:@"Cancel"
otherButtonTitles:@"Settings", nil];
//TODO if user has not given permission to device
if (![CLLocationManager locationServicesEnabled])
{
alertView.tag = 100;
}
//TODO if user has not given permission to particular app
else
{
alertView.tag = 200;
}
[alertView show];
return;
}
}
// handle bringing user to settings for each
+ (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if(buttonIndex == 0)// Cancel button pressed
{
//TODO for cancel
}
else if(buttonIndex == 1)// Settings button pressed.
{
if (alertView.tag == 100)
{
//This will open ios devices location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"prefs:root=LOCATION_SERVICES"]];
}
else if (alertView.tag == 200)
{
//This will open particular app location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
else if (alertView.tag == 300)
{
//This will open particular app location settings
[[UIApplication sharedApplication] openURL:[NSURL URLWithString:UIApplicationOpenSettingsURLString]];
}
}
}
GLHF!
Its very easy to create procedure in Mysql. Here, in my example I am going to create a procedure which is responsible to fetch all data from student table according to supplied name.
DELIMITER //
CREATE PROCEDURE getStudentInfo(IN s_name VARCHAR(64))
BEGIN
SELECT * FROM student_database.student s where s.sname = s_name;
END//
DELIMITER;
In the above example ,database and table names are student_database and student respectively. Note: Instead of s_name, you can also pass @s_name as global variable.
How to call procedure? Well! its very easy, simply you can call procedure by hitting this command
$mysql> CAll getStudentInfo('pass_required_name');
This is how you can set and get cookie values. This is what I was originally looking for when I found this question.
Note we use $cookieStore
instead of $cookies
<!DOCTYPE html>
<html ng-app="myApp">
<head>
<script src="http://code.angularjs.org/1.0.0rc10/angular-1.0.0rc10.js"></script>
<script src="http://code.angularjs.org/1.0.0rc10/angular-cookies-1.0.0rc10.js"></script>
<script>
angular.module('myApp', ['ngCookies']);
function CookieCtrl($scope, $cookieStore) {
$scope.lastVal = $cookieStore.get('tab');
$scope.changeTab = function(tabName){
$scope.lastVal = tabName;
$cookieStore.put('tab', tabName);
};
}
</script>
</head>
<body ng-controller="CookieCtrl">
<!-- ... -->
</body>
</html>
var $table = $('#myTable2');
$table.bootstrapTable('destroy');
Worked for me
for _ in {1..10}; do command; done
Note the underscore instead of using a variable.
For posterity: as of 0.15.0, there is a handy .dt accessor you can use to pull such values from a datetime/period series (in the above case, just sales.timestamp.dt.hour
!
You need to set the height of every parent element of the one you want the height defined.
<html style="height: 100%;">
<body style="height: 100%;">
<div style="height: 100%;">
<p>
Make this division 100% height.
</p>
</div>
</body>
</html>
EDIT: this is a very old answer. SHA1 was deprecated in 2011 and has now been broken in practice. https://shattered.io/ Use a newer standard instead (e.g. SHA256, SHA512, etc).
If your answer to the question in my comment is "No", here's what I use:
public static byte[] HashPassword(string password)
{
var provider = new SHA1CryptoServiceProvider();
var encoding = new UnicodeEncoding();
return provider.ComputeHash(encoding.GetBytes(password));
}
Disable the url button by following function
window.onload = function () {
if (typeof history.pushState === "function") {
history.pushState("jibberish", null, null);
window.onpopstate = function () {
history.pushState('newjibberish', null, null);
// Handle the back (or forward) buttons here
// Will NOT handle refresh, use onbeforeunload for this.
};
}
else {
var ignoreHashChange = true;
window.onhashchange = function () {
if (!ignoreHashChange) {
ignoreHashChange = true;
window.location.hash = Math.random();
// Detect and redirect change here
// Works in older FF and IE9
// * it does mess with your hash symbol (anchor?) pound sign
// delimiter on the end of the URL
}
else {
ignoreHashChange = false;
}
};
}
};
Just change the primary key of your object and run save().
obj = Foo.objects.get(pk=<some_existing_pk>)
obj.pk = None
obj.save()
If you want auto-generated key, set the new key to None.
More on UPDATE/INSERT here.
Official docs on copying model instances: https://docs.djangoproject.com/en/2.2/topics/db/queries/#copying-model-instances
So if you want something unique to the device itself, TM.getDeviceId()
should be sufficient.
Here is the code which shows how to get Telephony manager ID. The android Device ID that you are using can change on factory settings and also some manufacturers have issue in giving unique id.
TelephonyManager tm =
(TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE);
String androidId = Secure.getString(this.getContentResolver(), Secure.ANDROID_ID);
Log.d("ID", "Android ID: " + androidId);
Log.d("ID", "Device ID : " + tm.getDeviceId());
Be sure to take permissions for TelephonyManager
by using
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
I am contributing here, as the OP asked:
How to change collation of database, table, column?
The selected answer just states it on table level.
Changing it database wide:
ALTER DATABASE <database_name> CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Changing it per table:
ALTER TABLE <table_name> CONVERT TO CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
Good practice is to change it at table level as it'll change it for columns as well. Changing for specific column is for any specific case.
Changing collation for a specific column:
ALTER TABLE <table_name> MODIFY <column_name> VARCHAR(255) CHARACTER SET utf8mb4 COLLATE utf8mb4_unicode_ci;
The @Query annotation allows to execute native queries by setting the nativeQuery flag to true.
Quote from Spring Data JPA reference docs.
Also, see this section on how to do it with a named native query.
Have a look at: Greybox
It's an awesome version of lightbox that supports forms, external web pages as well as the traditional images and slideshows. It works perfectly from a link on a webpage.
You will find many information on how to use Greybox and also some great examples. Cheers Kara
What about running the google-drive-ftp-adapter application in your local pc and then connect your filezilla client to that application? The google-drive-ftp-adapter application is not an online service, but its an alternative solution to connect to google drive through ftp.
The google-drive-ftp-adapter is an open source application hosted in github and it is a kind of standalone ftp-server java application that connects to your google drive in behalf of you, acting as a bridge (or adapter) between your ftp client and the google drive service. Once you have running the google-drive-ftp adapter, you can connect your preferred FTP client to the google-drive-ftp-adapter ftp server in your localhost (or wherever the app is running, like in a remote machine) to manage your files.
I use it in conjunction with beyond compare to synchronize my local files against the ones I have in the google drive and it serves well for the purpose.
This is the current github link hosting the google-drive-ftp-adapter repository: https://github.com/andresoviedo/google-drive-ftp-adapter
Check the code below and the link to MDN
// var ts_hms = new Date(UTC);
// ts_hms.format("%Y-%m-%d %H:%M:%S")
// exact format
console.log(new Date().toISOString().replace('T', ' ').substring(0, 19))
// other formats
console.log(new Date().toUTCString())
console.log(new Date().toLocaleString('en-US'))
console.log(new Date().toString())
_x000D_
Here is a simple solution which handles tabs and/or whitespaces in the filename. If you have to deal with other strange characters in the filename like newlines, pick another answer.
The test directory
ls -F test
Baltimore/ Cherry Hill/ Edison/ New York City/ Philadelphia/ cities.txt
The code to go into the directories
find test -type d | while read f ; do
echo "$f"
done
The filename must be quoted ("$f"
) if used as argument. Without quotes, the spaces act as argument separator and multiple arguments are given to the invoked command.
And the output:
test/Baltimore
test/Cherry Hill
test/Edison
test/New York City
test/Philadelphia
@PropertySource
can be configured by factory
argument. So you can do something like:
@PropertySource(value = "classpath:application-test.yml", factory = YamlPropertyLoaderFactory.class)
Where YamlPropertyLoaderFactory
is your custom property loader:
public class YamlPropertyLoaderFactory extends DefaultPropertySourceFactory {
@Override
public PropertySource<?> createPropertySource(String name, EncodedResource resource) throws IOException {
if (resource == null){
return super.createPropertySource(name, resource);
}
return new YamlPropertySourceLoader().load(resource.getResource().getFilename(), resource.getResource(), null);
}
}
Inspired by https://stackoverflow.com/a/45882447/4527110
ThreeJS r77
var x = event.offsetX == undefined ? event.layerX : event.offsetX;
var y = event.offsetY == undefined ? event.layerY : event.offsetY;
mouse2D.x = ( x / renderer.domElement.width ) * 2 - 1;
mouse2D.y = - ( y / renderer.domElement.height ) * 2 + 1;
After trying many solutions. This worked for me. Might help someone else hence posting. Got it from here
You have to set the height
for the parents (container and child) explicitly, here is another work-around (if you don't want to set that height explicitly):
.child {
width: 30px;
background-color: red;
display: table-cell;
vertical-align: top;
position:relative;
}
.content {
position:absolute;
top:0;
bottom:0;
width:100%;
background-color: blue;
}
For your first method change ws.Range("A")
to ws.Range("A:A")
which will search the entirety of column a, like so:
Sub Find_Bingo()
Dim wb As Workbook
Dim ws As Worksheet
Dim FoundCell As Range
Set wb = ActiveWorkbook
Set ws = ActiveSheet
Const WHAT_TO_FIND As String = "Bingo"
Set FoundCell = ws.Range("A:A").Find(What:=WHAT_TO_FIND)
If Not FoundCell Is Nothing Then
MsgBox (WHAT_TO_FIND & " found in row: " & FoundCell.Row)
Else
MsgBox (WHAT_TO_FIND & " not found")
End If
End Sub
For your second method, you are using Bingo
as a variable instead of a string literal. This is a good example of why I add Option Explicit
to the top of all of my code modules, as when you try to run the code it will direct you to this "variable" which is undefined and not intended to be a variable at all.
Additionally, when you are using With...End With
you need a period .
before you reference Cells
, so Cells
should be .Cells
. This mimics the normal qualifying behavior (i.e. Sheet1.Cells.Find..)
Change Bingo
to "Bingo"
and change Cells
to .Cells
With Sheet1
Set FoundCell = .Cells.Find(What:="Bingo", After:=.Cells(1, 1), _
LookIn:=xlValues, lookat:=xlPart, SearchOrder:=xlByRows, _
SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With
If Not FoundCell Is Nothing Then
MsgBox ("""Bingo"" found in row " & FoundCell.Row)
Else
MsgBox ("Bingo not found")
End If
In my
With Sheet1
.....
End With
The Sheet1
refers to a worksheet's code name, not the name of the worksheet itself. For example, say I open a new blank Excel workbook. The default worksheet is just Sheet1
. I can refer to that in code either with the code name of Sheet1
or I can refer to it with the index of Sheets("Sheet1")
. The advantage to using a codename is that it does not change if you change the name of the worksheet.
Continuing this example, let's say I renamed Sheet1
to Data
. Using Sheet1
would continue to work, as the code name doesn't change, but now using Sheets("Sheet1")
would return an error and that syntax must be updated to the new name of the sheet, so it would need to be Sheets("Data")
.
In the VB Editor you would see something like this:
Notice how, even though I changed the name to Data
, there is still a Sheet1
to the left. That is what I mean by codename.
The Data
worksheet can be referenced in two ways:
Debug.Print Sheet1.Name
Debug.Print Sheets("Data").Name
Both should return Data
More discussion on worksheet code names can be found here.
You can use hexdump
's
import hexdump
hexdump.dump("Hello World", sep=":")
(append .lower()
if you require lower-case). This works for both Python 2 & 3.
To Join two string in SQL Query use function CONCAT(Express1,Express2,...)
Like....
SELECT CODE, CONCAT(Rtrim(FName), " " , TRrim(LName)) as Title FROM MyTable
You can additionally use libraries that perform type validation of your json, such as Sparkson. They allow you to define a TypeScript class, to which you'd like to parse your response, in your case it could be:
import { Field } from "sparkson";
class Response {
constructor(
@Field("name") public name: string,
@Field("error") public error: boolean
) {}
}
The library will validate if the required fields are present in the JSON payload and if their types are correct. It can also do a bunch of validations and conversions.
While pop and delete both take indices to remove an element as stated in above comments. A key difference is the time complexity for them. The time complexity for pop() with no index is O(1) but is not the same case for deletion of last element.
If your use case is always to delete the last element, it's always preferable to use pop() over delete(). For more explanation on time complexities, you can refer to https://www.ics.uci.edu/~pattis/ICS-33/lectures/complexitypython.txt
I had a different root cause
I had a script that basically searches all branches matching jira issue key in the for "PRJ-1234" among all branches to execute a git branch checkout command on the matching branch
The problem in my case was 2 or more branches shared the same jira key and hence caused my script to fail with the aforementioned error
By deleting the old unused branch and making sure only a single branch had the jira key reference fixed the problem
Here's my code in case someone wants to use it
git remote update
git fetch --all --prune
git branch -r --list *$1* | xargs git checkout --force
save this as switchbranch.sh
Then use it from the terminal ./switchbranch.sh PRJ-1234
If you're new to the library, consider double-checking whether the functionality you need is already offered by those Pandas objects.
My solution: use to_dict()
dict_of_lists = df.to_dict(orient='split')
This will give you a dictionary with three lists: index
, columns
, data
. If you decide you really don't need the columns and index names, you get the data with
dict_of_lists['data']
Add only This code in your ViewContorller
or in your AppDelegate
if([[[UIDevice currentDevice] systemVersion] floatValue] < 7.0)
{
//This is For iOS6
[self.navigationController.navigationBar setTintColor:[UIColor yellowColor]];
}
else
{
//This is For iOS7
[self.navigationController.navigationBar setBarTintColor:[UIColor yellowColor]];
}
a, b, c, d, e, g, h, i, j = (True,)*9
f = False
Alternate solution
Create a column that will store the month:
data['month'] = data['date'].dt.month
Create a column that will store the year:
data['year'] = data['date'].dt.year
Try This
<script type="text/javascript">
window.onload = function () {
var input = document.querySelector('input[type=checkbox]');
function check() {
if (input.checked) {
alert("checked");
} else {
alert("You didn't check it.");
}
}
input.onchange = check;
check();
}
</script>
Simpler with the aggregate function string_agg()
(Postgres 9.0 or later):
SELECT movie, string_agg(actor, ', ') AS actor_list
FROM tbl
GROUP BY 1;
The 1
in GROUP BY 1
is a positional reference and a shortcut for GROUP BY movie
in this case.
string_agg()
expects data type text
as input. Other types need to be cast explicitly (actor::text
) - unless an implicit cast to text
is defined - which is the case for all other character types (varchar
, character
, "char"
), and some other types.
As isapir commented, you can add an ORDER BY
clause in the aggregate call to get a sorted list - should you need that. Like:
SELECT movie, string_agg(actor, ', ' ORDER BY actor) AS actor_list
FROM tbl
GROUP BY 1;
But it's typically faster to sort rows in a subquery. See:
May be it will helpful:
<Border BorderBrush="Black" BorderThickness="1" HorizontalAlignment="Left" Height="160" Margin="10,55,0,0" VerticalAlignment="Top" Width="492"/>
I just run this command as a root from terminal and problem is solved,
sudo apt-get install -y postgis postgresql-9.3-postgis-2.1
pip install psycopg2
or
sudo apt-get install libpq-dev python-dev
pip install psycopg2
Have you tried using a view model instead of ViewData? Strongly typed helpers that end with For
and take a lambda expression cannot work with weakly typed structures such as ViewData
.
Personally I don't use ViewData/ViewBag. I define view models and have my controller actions pass those view models to my views.
For example in your case I would define a view model:
public class MyViewModel
{
[HiddenInput(DisplayValue = false)]
public string CRN { get; set; }
}
have my controller action populate this view model:
public ActionResult Index()
{
var model = new MyViewModel
{
CRN = "foo bar"
};
return View(model);
}
and then have my strongly typed view simply use an EditorFor
helper:
@model MyViewModel
@Html.EditorFor(x => x.CRN)
which would generate me:
<input id="CRN" name="CRN" type="hidden" value="foo bar" />
in the resulting HTML.
It is just syntax difference, in rails app there is CRUD, and seven actions basically by name index, new, create, show, update, edit, destroy.
Rails 4 make it developer friendly to change syntax before filter to before action.
before_action call method before the actions which we declare, like
before_action :set_event, only: [:show, :update, :destroy, :edit]
set_event is a method which will call always before show, update, edit and destroy.
Let's say you're building some chairs.
The diagram that shows how to build a chair and put it together corresponds to a software class.
Let's say you build five chairs according to the pattern in that diagram. Likewise, you could construct five software objects according to the pattern in a class.
Each chair has a unique number burned into the bottom of the seat to identify each specific chair. Chair 3 is one instance of a chair pattern. Likewise, memory location 3 can contain one instance of a software pattern.
So, an instance (chair 3) is a single unique, specific manifestation of a chair pattern.
You can use a combination of @JsonSetter, and @JsonGetter to control the deserialization, and serialization of your property, respectively. This will also allow you to keep standardized getter and setter method names that correspond to your actual field name.
import com.fasterxml.jackson.annotation.JsonSetter;
import com.fasterxml.jackson.annotation.JsonGetter;
class Coordinates {
private int red;
//# Used during serialization
@JsonGetter("r")
public int getRed() {
return red;
}
//# Used during deserialization
@JsonSetter("red")
public void setRed(int red) {
this.red = red;
}
}
I can't find latest answer, so I check it all with simulator.(iOS 11.0)
Device | Screen Height | Portrait | Landscape
iPhone 4s | 480.0 | 216.0 | 162.0
iPhone 5, iPhone 5s, iPhone SE | 568.0 | 216.0 | 162.0
iPhone 6, iPhone 6s, iPhone 7, iPhone 8, iPhone X | 667.0 | 216.0 | 162.0
iPhone 6 plus, iPhone 7 plus, iPhone 8 plus | 736.0 | 226.0 | 162.0
iPad 5th generation, iPad Air, iPad Air 2, iPad Pro 9.7, iPad Pro 10.5, iPad Pro 12.9 | 1024.0 | 265.0 | 353.0
Thanks!
Another way to do it is subclass it:
package my.own;
public class FQNDate extends Date {
}
And then import my.own.FQNDate in packages that have java.util.Date.
As HungryDB said the easier way for do that is:
$mystring = json_encode($my_json,JSON_UNESCAPED_SLASHES);
Have a look at your php version because this parameter has been added in version 5.4.0
I needed to throttle low internet on AndroidTV native device and based on what I have read, the most suitable solution was to limit the internet access directly in my router.
Go to router settings (locally it is smth like 192.168.0.1) -> set up DHCP server (if it's not running) -> choose IP address of a device and set the restriction;
In python strings are list of characters, but they are not explicitly list type, just list-like (i.e. it can be treated like a list). More formally, they're known as sequence
(see http://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange):
>>> a = 'foo bar'
>>> isinstance(a, list)
False
>>> isinstance(a, str)
True
Since strings are sequence, you can use slicing
to access parts of the list, denoted by list[start_index:end_index]
see Explain Python's slice notation . For example:
>>> a = [1,2,3,4]
>>> a[0]
1 # first element, NOT a sequence.
>>> a[0:1]
[1] # a slice from first to second, a list, i.e. a sequence.
>>> a[0:2]
[1, 2]
>>> a[:2]
[1, 2]
>>> x = "foo bar"
>>> x[0:2]
'fo'
>>> x[:2]
'fo'
When undefined, the slice notation takes the starting position as the 0, and end position as len(sequence).
In the olden C days, it's an array of characters, the whole issue of dynamic vs static list sounds like legend now, see Python List vs. Array - when to use?
Today you can select elements with the same id attribute this way:
document.querySelectorAll('[id=test]');
Or this way with jQuery:
$('[id=test]');
CSS selector #test { ... }
should work also for all elements with id = "test"
. ?ut the only thing: document.querySelectorAll('#test')
(or $('#test')
) - will return only a first element with this id.
Is it good, or not - I can't tell . But sometimes it is difficult to follow unique id standart .
For example you have the comment widget, with HTML-ids, and JS-code, working with these HTML-ids. Sooner or later you'll need to render this widget many times, to comment a different objects into a single page: and here the standart will broken (often there is no time or not allow - to rewrite built-in code).
For completeness, the answer is: you can't do that from within RStudio. @agstudy has it right - you need to install the newer version of R, then restart RStudio and it will automagically use the new version, as @Brandon noted.
It would be great if there was an update.R() function, analogous to the install.packages() function or the update.packages(function).
ok, I use a Mac, so I can only provide accurate details for the Mac - perhaps someone else can provide the accurate paths for windows/linux; I believe the process will be the same.
To ensure that your packages work with your shiny new version of R, you need to:
move the packages from the old R installation into the new version; on Mac OSX, this means moving all folders from here:
/Library/Frameworks/R.framework/Versions/2.15/Resources/library
to here:
/Library/Frameworks/R.framework/Versions/3.0/Resources/library
[where you'll replace "2.15" and "3.0" with whatever versions you're upgrading from and to. And only copy whatever packages aren't already in the destination directory. i.e. don't overwrite your new 'base' package with your old one - if you did, don't worry, we'll fix it in the next step anyway. If those paths don't work for you, try using installed.packages()
to find the proper pathnames.]
now you can update your packages by typing update.packages()
in your RStudio console, and answering 'y' to all of the prompts.
> update.packages(checkBuilt=TRUE)
class :
Version 7.3-7 installed in /Library/Frameworks/R.framework/Versions/3.0/Resources/library
Version 7.3-8 available at http://cran.rstudio.com
Update (y/N/c)? y
---etc---
finally, to reassure yourself that you have done everything, type these two commands in the RStudio console to see what you have got:
> version
> packageStatus()
<input type="file" id="picfile" name="picf" />
<input type="text" id="txtName" style="width: 144px;" />
$("#btncatsave").click(function () {
var Name = $("#txtName").val();
var formData = new FormData();
var totalFiles = document.getElementById("picfile").files.length;
var file = document.getElementById("picfile").files[0];
formData.append("FileUpload", file);
formData.append("Name", Name);
$.ajax({
type: "POST",
url: '/Category_Subcategory/Save_Category',
data: formData,
dataType: 'json',
contentType: false,
processData: false,
success: function (msg) {
alert(msg);
},
error: function (error) {
alert("errror");
}
});
});
[HttpPost]
public ActionResult Save_Category()
{
string Name=Request.Form[1];
if (Request.Files.Count > 0)
{
HttpPostedFileBase file = Request.Files[0];
}
}
function leapYear(year)
{
return ((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0);
}
I had the same problem. For some reason --initialize
did not work.
After about 5 hours of trial and error with different parameters, configs and commands I found out that the problem was caused by the file system.
I wanted to run a database on a large USB HDD drive. Drives larger than 2 TB are GPT partitioned! Here is a bug report with a solution:
https://bugs.mysql.com/bug.php?id=28913
In short words: Add the following line to your my.ini:
innodb_flush_method=normal
I had this problem with mysql 5.7 on Windows.
for(map<string, pair<string,string> >::const_iterator it = myMap.begin();
it != myMap.end(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
In C++11, you don't need to spell out map<string, pair<string,string> >::const_iterator
. You can use auto
for(auto it = myMap.cbegin(); it != myMap.cend(); ++it)
{
std::cout << it->first << " " << it->second.first << " " << it->second.second << "\n";
}
Note the use of cbegin()
and cend()
functions.
Easier still, you can use the range-based for loop:
for(auto elem : myMap)
{
std::cout << elem.first << " " << elem.second.first << " " << elem.second.second << "\n";
}
TinyXML, and also Boost.PropertyTree. The latter does not fulfill all official requirements, but is very simple.
Using :
Set the head of the list to it bottom lv.setStackFromBottom(true);
Worked for me and the list is scrolled to the bottom automatically when it is first brought into visibility. The list then scrolls as it should with TRANSCRIPT_MODE_ALWAYS_SCROLL
.
As Janoulle pointed out, you don't need to detect which extension it is if you use the WorkbookFactory, it will do it for you. I recently had to implement a solution using NPOI to read Excel files and import email addresses into a sql database. My main problem was that I was probably going to receive about 12 different Excel layouts from different customers so I needed something that could be changed quickly without much code. I ended up using Npoi.Mapper which is an awesome tool! Highly recommended!
Here is my complete solution:
using System.IO;
using System.Linq;
using Npoi.Mapper;
using Npoi.Mapper.Attributes;
using NPOI.SS.UserModel;
namespace JobCustomerImport.Processors
{
public class ExcelEmailProcessor
{
private UserManagementServiceContext DataContext { get; }
public ExcelEmailProcessor(int customerNumber)
{
DataContext = new UserManagementServiceContext();
}
public void Execute(string localPath, int sheetIndex)
{
IWorkbook workbook;
using (FileStream file = new FileStream(localPath, FileMode.Open, FileAccess.Read))
{
workbook = WorkbookFactory.Create(file);
}
var importer = new Mapper(workbook);
var items = importer.Take<MurphyExcelFormat>(sheetIndex);
foreach(var item in items)
{
var row = item.Value;
if (string.IsNullOrEmpty(row.EmailAddress))
continue;
UpdateUser(row);
}
DataContext.SaveChanges();
}
private void UpdateUser(MurphyExcelFormat row)
{
//LOGIC HERE TO UPDATE A USER IN DATABASE...
}
private class MurphyExcelFormat
{
[Column("District")]
public int District { get; set; }
[Column("DM")]
public string FullName { get; set; }
[Column("Email Address")]
public string EmailAddress { get; set; }
[Column(3)]
public string Username { get; set; }
public string FirstName
{
get
{
return Username.Split('.')[0];
}
}
public string LastName
{
get
{
return Username.Split('.')[1];
}
}
}
}
}
I am so happy with NPOI + Npoi.Mapper (from Donny Tian) as an Excel import solution that I wrote a blog post about it, going in to more detail about this code above. You can read it here if you wish: Easiest way to import excel files. The best thing about this solution is that it runs perfectly in a serverless azure/cloud environment which I couldn't get with other Excel tools/libraries.
If you use rs.next() you will move the cursor, than you should to move first() why don't check using first() directly?
public void fetchData(ResultSet res, JTable table) throws SQLException{
ResultSetMetaData metaData = res.getMetaData();
int fieldsCount = metaData.getColumnCount();
for (int i = 1; i <= fieldsCount; i++)
((DefaultTableModel) table.getModel()).addColumn(metaData.getColumnLabel(i));
if (!res.first())
JOptionPane.showMessageDialog(rootPane, "no data!");
else
do {
Vector<Object> v = new Vector<Object>();
for (int i = 1; i <= fieldsCount; i++)
v.addElement(res.getObject(i));
((DefaultTableModel) table.getModel()).addRow(v);
} while (res.next());
res.close();
}
You code should look like this:
public int getElement(int[] arrayOfInts, int index) {
return arrayOfInts[index];
}
Main points here are method return type, it should match with array elements type and if you are working from main()
- this method must be static also.
java.library.path
is initilized with the values of the variables above on its corresponding platform.
This should work on any IDE.
You can test if the value is what you expect by calling java -XshowSettings:properties
document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);
function initialiseMediaPlayer() {
mediaPlayer = document.getElementById('media-video');
mediaPlayer.controls = false;
mediaPlayer.addEventListener('volumechange', function(e) {
// Update the button to be mute/unmute
if (mediaPlayer.muted) changeButtonType(muteBtn, 'unmute');
else changeButtonType(muteBtn, 'mute');
}, false);
mediaPlayer.addEventListener('ended', function() { this.pause(); }, false);
}
onNewIntent()
is meant as entry point for singleTop activities which already run somewhere else in the stack and therefore can't call onCreate()
. From activities lifecycle point of view it's therefore needed to call onPause()
before onNewIntent()
. I suggest you to rewrite your activity to not use these listeners inside of onNewIntent()
. For example most of the time my onNewIntent()
methods simply looks like this:
@Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
// getIntent() should always return the most recent
setIntent(intent);
}
With all setup logic happening in onResume()
by utilizing getIntent()
.
By the power of Google I found a blogpost from 2007 which gives the following regex that matches string which don't contains a certain substring:
^((?!my string).)*$
It works as follows: it looks for zero or more (*) characters (.) which do not begin (?! - negative lookahead) your string and it stipulates that the entire string must be made up of such characters (by using the ^ and $ anchors). Or to put it an other way:
The entire string must be made up of characters which do not begin a given string, which means that the string doesn't contain the given substring.
You should add AutoPostBack="true" to DropDownList1
<asp:DropDownList ID="ddmanu" runat="server" AutoPostBack="true"
DataSourceID="Sql_fur_model_manu"
DataTextField="manufacturer" DataValueField="manufacturer"
onselectedindexchanged="ddmanu_SelectedIndexChanged">
</asp:DropDownList>
This site had a simple solution that worked with my Django 1.7 configuration.
FIRST: Make a symlink named admin_src in your project's template/ directory to your installed Django templates. For me on Dreamhost using a virtualenv, my "source" Django admin templates were in:
~/virtualenvs/mydomain/lib/python2.7/site-packages/django/contrib/admin/templates/admin
SECOND: Create an admin directory in templates/
So my project's template/ directory now looked like this:
/templates/
admin
admin_src -> [to django source]
base.html
index.html
sitemap.xml
etc...
THIRD: In your new template/admin/ directory create a base.html file with this content:
{% extends "admin_src/base.html" %}
{% block extrahead %}
<link rel='shortcut icon' href='{{ STATIC_URL }}img/favicon-admin.ico' />
{% endblock %}
FOURTH: Add your admin favicon-admin.ico into your static root img folder.
Done. Easy.
Check out the following two: 1) This field has no NULL value. For example:
public DateTime MyDate { get; set; }
Replace to:
public DateTime MyDate { get; set; }=DateTime.Now;
2) New the database again. For example:
db=new MyDb();
Use encodeURI()
in client JS and use URLDecoder.decode()
in server Java side works.
Example:
Javascript:
$.getJSON(
url,
{
"user": encodeURI(JSON.stringify(user))
},
onSuccess
);
Java:
java.net.URLDecoder.decode(params.user, "UTF-8");
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
Try to the following steps:
1) Open Git Bash and run: cd ~/.ssh
2) Try to run agent : eval $(ssh-agent)
3) Right now, you can run the following command : ssh-add -l
Older versions of git require you first define an ignore pattern and immediately (on the next line) define the exclusion. [tested on version 1.9.3 (Apple Git-50)]
/config.php
!/*/config.php
Later versions only require the following [tested on version 2.2.1]
/config.php
In notepad++ you can set it for the file specifically by pressing
Edit --> EOL Conversion --> UNIX/OSX Format
Also, if your service is sending an object instead of an array add isArray:false to its declaration.
'query': {method: 'GET', isArray: false }
Queue<String> qe=new LinkedList<String>();
qe.add("b");
qe.add("a");
qe.add("c");
Since Queue
is an interface, you can't create an instance of it as you illustrated
Since this is an old thread just adding an update:
If you run just npm install mysql
, you need to be in the same directory that your run your server. I would advise to do it as in one of the following examples:
npm install -g mysql
1- Add it to your package.json
in the dependencies:
"dependencies": {
"mysql": "~2.3.2",
...
2- run npm install
Note that for connections to happen you will also need to be running the mysql server (which is node independent)
There are a bunch of tutorials out there that explain this, and it is a bit dependent on operative system. Just go to google and search for how to install mysql server [Ubuntu|MacOSX|Windows]
. But in a sentence: you have to go to http://www.mysql.com/downloads/ and install it.
The pip
executable is actually a Python script.
By default it contains (on Linux):
#!/usr/bin/python
# EASY-INSTALL-ENTRY-SCRIPT: 'pip==1.5.6','console_scripts','pip'
__requires__ = 'pip==1.5.6'
import sys
from pkg_resources import load_entry_point
if __name__ == '__main__':
sys.exit(
load_entry_point('pip==1.5.6', 'console_scripts', 'pip')()
)
So if you got the same in MacOS, pip
would always use /usr/bin/python
.
But this is a default. You can still provide the version of python you want either by editing the file or by using python explicitly.
If which python
returns /usr/bin/python
then something went wrong when you installed your own version. If it is /Library/Frameworks/Python.framework/Versions/2.7/bin/python
, you can directly call:
sudo python `which pip` install scikit-learn --upgrade
However, chances are high that it won't work. The reason is that sudo
is resetting all your environment variables. To make it work, the easiest would be to use:
sudo -E pip install scikit-learn --upgrade
or
sudo -E python `which pip` install scikit-learn --upgrade
depending on your setup.
pip
was not thought of as something that root
should execute. The actual best way to use it is to install a local, non-root, python version. You just have to make sure that you use it by default by setting up the correct environment variables (such as PATH
on Linux) and then install pip
without sudo
using that python version.
An even better way would be to setup virtualenv
s from your root install.
This way, you can install/update whatever you want without root privileges and never bother again about why sudo pip
is not working. You would also avoid to provide root privileges to whatever is on Pypi and that would warrant that you don't mix system libs with your own.
you have to use self as the first parameters of a method
in the second case you should use
class MathOperations:
def testAddition (self,x, y):
return x + y
def testMultiplication (self,a, b):
return a * b
and in your code you could do the following
tmp = MathOperations
print tmp.testAddition(2,3)
if you use the class without instantiating a variable first
print MathOperation.testAddtion(2,3)
it gives you an error "TypeError: unbound method"
if you want to do that you will need the @staticmethod
decorator
For example:
class MathsOperations:
@staticmethod
def testAddition (x, y):
return x + y
@staticmethod
def testMultiplication (a, b):
return a * b
then in your code you could use
print MathsOperations.testAddition(2,3)
for (Direction dir : Direction.values()) {
System.out.println(dir);
}
We can also make use of lambda and streams (Tutorial):
Stream.of(Direction.values()).forEachOrdered(System.out::println);
Why forEachOrdered
and not forEach
with streams ?
The behaviour of forEach
is explicitly nondeterministic where as the forEachOrdered
performs an action for each element of this stream, in the encounter order of the stream if the stream has a defined encounter order. So forEach
does not guarantee that the order would be kept.
Also when working with streams (especially parallel ones) keep in mind the nature of streams. As per the doc:
Stream pipeline results may be nondeterministic or incorrect if the behavioral parameters to the stream operations are stateful. A stateful lambda is one whose result depends on any state which might change during the execution of the stream pipeline.
Set<Integer> seen = Collections.synchronizedSet(new HashSet<>());
stream.parallel().map(e -> { if (seen.add(e)) return 0; else return e; })...
Here, if the mapping operation is performed in parallel, the results for the same input could vary from run to run, due to thread scheduling differences, whereas, with a stateless lambda expression the results would always be the same.
Side-effects in behavioral parameters to stream operations are, in general, discouraged, as they can often lead to unwitting violations of the statelessness requirement, as well as other thread-safety hazards.
Streams may or may not have a defined encounter order. Whether or not a stream has an encounter order depends on the source and the intermediate operations.
Go to the actual FILE menu and create a new general project.
If the project type isn't recognized, preventing one of these import methods from working, then try this. Once you add the generic project, you can then add support for whatever language you require.
By default std::map
(and std::set
) use operator<
to determine sorting. Therefore, you need to define operator<
on your class.
Two objects are deemed equivalent if !(a < b) && !(b < a)
.
If, for some reason, you'd like to use a different comparator, the third template argument of the map
can be changed, to std::greater
, for example.
this one works for me (plain javascript)
var fixScroll = function (className, border) { // className = class of scrollElement(s), border: borderTop + borderBottom, due to offsetHeight
var reg = new RegExp(className,"i"); var off = +border + 1;
function _testClass(e) { var o = e.target; while (!reg.test(o.className)) if (!o || o==document) return false; else o = o.parentNode; return o;}
document.ontouchmove = function(e) { var o = _testClass(e); if (o) { e.stopPropagation(); if (o.scrollTop == 0) { o.scrollTop += 1; e.preventDefault();}}}
document.ontouchstart = function(e) { var o = _testClass(e); if (o && o.scrollHeight >= o.scrollTop + o.offsetHeight - off) o.scrollTop -= off;}
}
fixScroll("fixscroll",2); // assuming I have a 1px border in my DIV
html:
<div class="fixscroll" style="border:1px gray solid">content</div>
The following should do the trick:
div[class^='myclass'], div[class*=' myclass']{
color: #F00;
}
Edit: Added wildcard (*
) as suggested by David
td
cellThe answers provided do a great job to right-align text in a td
cell.
This might not be the solution when you're looking to align a block element as commented in the accepted answer. To achieve such with a block element, I have found it useful to make use of margins;
selector {
margin: top right bottom left;
}
td {
/* there is a shorthand, TODO! */
margin: auto 0 auto auto;
}
td {
margin: auto auto auto auto;
}
/* or the short-hand */
margin: auto;
td {
margin: auto;
}
Alternatively, you could make you td
content display inline-block
if that's an option, but that may distort the position of its child elements.
Using #selector will check your code at compile time to make sure the method you want to call actually exists. Even better, if the method doesn’t exist, you’ll get a compile error: Xcode will refuse to build your app, thus banishing to oblivion another possible source of bugs.
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.rightBarButtonItem =
UIBarButtonItem(barButtonSystemItem: .Add, target: self,
action: #selector(addNewFireflyRefernce))
}
func addNewFireflyReference() {
gratuitousReferences.append("Curse your sudden but inevitable betrayal!")
}
By overriding, you achieve dynamic polymorphism. When you say overriding static methods, the words you are trying to use are contradictory.
Static says - compile time, overriding is used for dynamic polymorphism. Both are opposite in nature, and hence can't be used together.
Dynamic polymorphic behavior comes when a programmer uses an object and accessing an instance method. JRE will map different instance methods of different classes based on what kind of object you are using.
When you say overriding static methods, static methods we will access by using the class name, which will be linked at compile time, so there is no concept of linking methods at runtime with static methods. So the term "overriding" static methods itself doesn't make any meaning.
Note: even if you access a class method with an object, still java compiler is intelligent enough to find it out, and will do static linking.
Well I figured out a work around. I'm making the call from a keyboard hook used to implement a hotkey. The call works as expected if I put it into a BackgroundWorker with a pause. It's a kludge, but I have no idea why it wasn't working originally.
void hotkey_execute()
{
IntPtr handle = new WindowInteropHelper(Application.Current.MainWindow).Handle;
BackgroundWorker bg = new BackgroundWorker();
bg.DoWork += new DoWorkEventHandler(delegate
{
Thread.Sleep(10);
SwitchToThisWindow(handle, true);
});
bg.RunWorkerAsync();
}
You can either use the answer from the duplicate link pointed by nvm.
Or you can resolve conflicts by using their changes (but some of your changes might be kept if they don't conflict with remote version):
git pull -s recursive -X theirs
Using a null reference as the first operand to instanceof
returns false
.
You can use Strings replace method with a regular expression.
"Hello World ".replace(/ /g, "");
The replace() method returns a new string with some or all matches of a pattern replaced by a replacement. The pattern can be a string or a RegExp
/ / - Regular expression matching spaces
g - Global flag; find all matches rather than stopping after the first match
const str = "H e l l o World! ".replace(/ /g, "");_x000D_
document.getElementById("greeting").innerText = str;
_x000D_
<p id="greeting"><p>
_x000D_
This query should give you result equivalent to trunc(sysdate)
in Oracle.
SELECT *
FROM your_table
WHERE CONVERT(varchar(12), your_column_name, 101)
= CONVERT(varchar(12), GETDATE(), 101)
Hope this helps!
var streetaddress = addy.split(',')[0];
I use it all the time on hackerrank/leetcode
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String lines = br.readLine();
String[] strs = lines.trim().split("\\s+");
for (int i = 0; i < strs.length; i++) {
a[i] = Integer.parseInt(strs[i]);
}
You can pass in the element to the controller, just like the scope:
function someControllerFunc($scope, $element){
}
Just for completeness and those unaware XSL 1 has choose for multiple conditions.
<xsl:choose>
<xsl:when test="expression">
... some output ...
</xsl:when>
<xsl:when test="another-expression">
... some output ...
</xsl:when>
<xsl:otherwise>
... some output ....
</xsl:otherwise>
</xsl:choose>
The syntax is using a colon - if there is no colon the above error will occur.
<?php while($query->fetch()): ?>
....
<?php endwhile; ?>
The alternative to this syntax is using curly brackets:
<?php while($query->fetch()) { ?>
....
<?php } ?>
conn.escape_string()
See MySQL C API function mapping: http://mysql-python.sourceforge.net/MySQLdb.html
The Sun JVM requires a lot of memory for HotSpot and it maps in the runtime libraries in shared memory.
If memory is an issue consider using another JVM suitable for embedding. IBM has j9, and there is the Open Source "jamvm" which uses GNU classpath libraries. Also Sun has the Squeak JVM running on the SunSPOTS so there are alternatives.
I have a quick solution for finding Waldo using OpenCV.
I used the template matching function available in OpenCV to find Waldo.
To do this a template is needed. So I cropped Waldo from the original image and used it as a template.
Next I called the cv2.matchTemplate()
function along with the normalized correlation coefficient as the method used. It returned a high probability at a single region as shown in white below (somewhere in the top left region):
The position of the highest probable region was found using cv2.minMaxLoc()
function, which I then used to draw the rectangle to highlight Waldo:
With Java 8 it is a bit easier:
OptionalDouble average = marks
.stream()
.mapToDouble(a -> a)
.average();
Thus your average value is average.getAsDouble()
return average.isPresent() ? average.getAsDouble() : 0;
select max(id) from customers
Here is a fast and easy way of parsing query strings in JavaScript:
function getQueryVariable(variable) {
var query = window.location.search.substring(1);
var vars = query.split('&');
for (var i = 0; i < vars.length; i++) {
var pair = vars[i].split('=');
if (decodeURIComponent(pair[0]) == variable) {
return decodeURIComponent(pair[1]);
}
}
console.log('Query variable %s not found', variable);
}
Now make a request to page.html?x=Hello:
console.log(getQueryVariable('x'));
you can simply use onBackPressed();
or if you are using fragment you can use getActivity().onBackPressed()
box-sizing: border-box;
width: 100%;
padding: 5px;
box-sizing: border box; makes it so that padding, margin and border are included in the width calculations.
The AWS support pointed a simpler solution. It's basically the same idea proposed by @Vivek M. Chawla, with a more simple implementation.
AWS S3:
aws.example.com
Redirect all requests to another host name
and enter your URL:
https://myaccount.signin.aws.amazon.com/console/
AWS Route53:
Yes
. Click on Alias
Target
field and select the S3 bucket you created in the previous
step.Reference: How to redirect domains using Amazon Web Services
AWS official documentation: Is there a way to redirect a domain to another domain using Amazon Route 53?
Without any server side solution, Theres is only one way in which a secure page can get something from a insecure page/request and that's thought postMessage and a popup
I said popup cuz the site isn't allowed to mix content. But a popup isn't really mixing. It has it's own window but are still able to communicate with the opener with postMessage.
So you can open a new http-page with window.open(...)
and have that making the request for you (that is if the site is using CORS as well)
XDomain came to mind when i wrote this but here is a modern approach using the new fetch api, the advantage is the streaming of large files, the downside is that it won't work in all browser
You put this proxy script on any http page
onmessage = evt => {
const port = evt.ports[0]
fetch(...evt.data).then(res => {
// the response is not clonable
// so we make a new plain object
const obj = {
bodyUsed: false,
headers: [...res.headers],
ok: res.ok,
redirected: res.redurected,
status: res.status,
statusText: res.statusText,
type: res.type,
url: res.url
}
port.postMessage(obj)
// Pipe the request to the port (MessageChannel)
const reader = res.body.getReader()
const pump = () => reader.read()
.then(({value, done}) => done
? port.postMessage(done)
: (port.postMessage(value), pump())
)
// start the pipe
pump()
})
}
Then you open a popup window in your https page (note that you can only do this on a user interaction event or else it will be blocked)
window.popup = window.open(http://.../proxy.html)
create your utility function
function xfetch(...args) {
// tell the proxy to make the request
const ms = new MessageChannel
popup.postMessage(args, '*', [ms.port1])
// Resolves when the headers comes
return new Promise((rs, rj) => {
// First message will resolve the Response Object
ms.port2.onmessage = ({data}) => {
const stream = new ReadableStream({
start(controller) {
// Change the onmessage to pipe the remaning request
ms.port2.onmessage = evt => {
if (evt.data === true) // Done?
controller.close()
else // enqueue the buffer to the stream
controller.enqueue(evt.data)
}
}
})
// Construct a new response with the
// response headers and a stream
rs(new Response(stream, data))
}
})
}
And make the request like you normally do with the fetch api
xfetch('http://httpbin.org/get')
.then(res => res.text())
.then(console.log)
Take a look at toggle()
jQuery function :
Also, innerHTML
jQuery Function is .html()
.
You do not need the latex2exp
package to do what you wanted to do. The following code would do the trick.
ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) +
geom_point() +
labs(title=expression("Fuel Efficiency"~(alpha*Omega)),
color=expression(alpha*Omega), x=expression(Delta~price))
Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*")
works, so I suggest giving it a try.
More comments asked about getting ? Price
and I find the most straightforward way to achieve that is expression(Delta~price))
. If you need to add something before the Greek letter, you can also do this:
expression(Indicative~Delta~price)
which gets you:
I would strongly recommend not to use synchronous (blocking) functions, as they hold other concurrent operations. Instead, use asynchronous fs.promises:
const fs = require('fs').promises
const setValue = (fn, value) =>
fs.readFile(fn)
.then(body => JSON.parse(body))
.then(json => {
// manipulate your data here
json.value = value
return json
})
.then(json => JSON.stringify(json))
.then(body => fs.writeFile(fn, body))
.catch(error => console.warn(error))
Remeber that setValue
returns a pending promise, you'll need to use .then function or, within async functions, the await operator.
// await operator
await setValue('temp.json', 1) // save "value": 1
await setValue('temp.json', 2) // then "value": 2
await setValue('temp.json', 3) // then "value": 3
// then-sequence
setValue('temp.json', 1) // save "value": 1
.then(() => setValue('temp.json', 2)) // then save "value": 2
.then(() => setValue('temp.json', 3)) // then save "value": 3
This should work:
DECLARE db_cursor CURSOR FOR SELECT name, age, color FROM table;
DECLARE @myName VARCHAR(256);
DECLARE @myAge INT;
DECLARE @myFavoriteColor VARCHAR(40);
OPEN db_cursor;
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
WHILE @@FETCH_STATUS = 0
BEGIN
--Do stuff with scalar values
FETCH NEXT FROM db_cursor INTO @myName, @myAge, @myFavoriteColor;
END;
CLOSE db_cursor;
DEALLOCATE db_cursor;
Edit 2018-05-28 I have changed the example to use Java 8's Time API:
LocalDate d1 = LocalDate.parse("2018-05-26", DateTimeFormatter.ISO_LOCAL_DATE);
LocalDate d2 = LocalDate.parse("2018-05-28", DateTimeFormatter.ISO_LOCAL_DATE);
Duration diff = Duration.between(d1.atStartOfDay(), d2.atStartOfDay());
long diffDays = diff.toDays();
If you are starting out a react-native app and seeing this issue, then you have to follow all the instructions listed in firebase (when you setup iOS/android app) or the instructions @ React-native google auth android DEVELOPER_ERROR Code 10 question
1) To remove white space everywhere:
df.columns = df.columns.str.replace(' ', '')
2) To remove white space at the beginning of string:
df.columns = df.columns.str.lstrip()
3) To remove white space at the end of string:
df.columns = df.columns.str.rstrip()
4) To remove white space at both ends:
df.columns = df.columns.str.strip()
5) To replace white space everywhere
df.columns = df.columns.str.replace(' ', '_')
6) To replace white space at the beginning:
df.columns = df.columns.str.replace('^ +', '_')
7) To replace white space at the end:
df.columns = df.columns.str.replace(' +$', '_')
8) To replace white space at both ends:
df.columns = df.columns.str.replace('^ +| +$', '_')
All above applies to a specific column as well, assume you have a column named col
, then just do:
df[col] = df[col].str.strip() # or .replace as above
--save-dev (only used in the development, not in production)
--save (production dependencies)
--global or -g (used globally i.e can be used anywhere in our local system)
If you happen to be using jQuery, you might want to give this a shot: http://api.jquery.com/category/deferred-object/
It allows you to defer the execution of your callback function until the ajax request (or any async operation) is completed. This can also be used to call a callback once several ajax requests have all completed.
That is okay for removing of data connections by using VBA as follows:
Sub deleteConn()
Dim xlBook As Workbook
Dim Cn As WorkbookConnection
Dim xlSheet As Worksheet
Dim Qt As QueryTable
Set xlBook = ActiveWorkbook
For Each Cn In xlBook.Connections
Debug.Print VarType(Cn)
Cn.Delete
Next Cn
For Each xlSheet In xlBook.Worksheets
For Each Qt In xlSheet.QueryTables
Debug.Print Qt.Name
Qt.Delete
Next Qt
Next xlSheet
End Sub
From Wikipedia (emphasis and link added):
When data that has been entered into HTML forms is submitted, the form field names and values are encoded and sent to the server in an HTTP request message using method GET or POST, or, historically, via email. The encoding used by default is based on a very early version of the general URI percent-encoding rules, with a number of modifications such as newline normalization and replacing spaces with "+" instead of "%20". The MIME type of data encoded this way is application/x-www-form-urlencoded, and it is currently defined (still in a very outdated manner) in the HTML and XForms specifications.
So, the real percent encoding uses %20
while form data in URLs is in a modified form that uses +
. So you're most likely to only see +
in URLs in the query string after an ?
.
If you need more than 1 class
You can do this:
<i id="icon"
v-bind:class="{ 'fa fa-star': showStar }"
v-on:click="showStar = !showStar"
>
</i>
data: {
showStar: true
}
Notice the single quotes ' around the classes!
Thanks to everyone else's solutions.
I faced the same issue, and finally i got a solution. Please go through with the below steps, if you are using MAMP.
This works for me.
This way you can Create NSArray, NSMutableArray.
NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];
NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];
color
and fill
are separate aesthetics. Since you want to modify the color you need to use the corresponding scale:
d + scale_color_manual(values=c("#CC6666", "#9999CC"))
is what you want.
Just use jQuery's attr()
method
$(this).closest("tr").next().show().find('.longboxsmall').attr('disabled', 'disabled');
Try http://loadimpact.com the best I have found so far, but no alternative to it I can find.
Might be strange to answer my own question, but here is another really cool color picker I never saw before. It does not solve my problem either :-(((( however I think it's much cooler to these I know already.
On the right, under Tools select "Color Sphere", a very powerful and customizable sphere (see what you can do with the pop-ups on top), "Color Galaxy", I'm still not sure how this works, but looks cool and "Color Studio" is also nice. Further it can export to all kind of formats (e.g. Illustrator or Photoshop, etc.)
How about this, I choose my background color there, let it create a complimentary color (from the first pop up) - this should have highest contrast and thus be best readable, now select the complementary color as main color and select neutral? Hmmm... not too great either, but we are getting better ;-)
just add
<dependency>
<groupId>com.microsoft.sqlserver</groupId>
<artifactId>sqljdbc4</artifactId>
<version>4.0</version>
<scope>runtime</scope>
</dependency>
Update 2:
Xcode 9 appears to have a "feature" where it will ignore the file's current line endings, and instead just use your default line-ending setting when inserting lines into a file, resulting in files with mixed line endings.
I'm pretty sure this bug didn't exist in Xcode 7; not sure about Xcode 8. The good news is that it appears to be fixed in Xcode 10.
For the time it existed, this bug caused a small amount of hilarity in the codebase I refer to in the question (which to this day uses autocrlf=false
), and led to many "EOL" commit messages and eventually to my writing a git pre-commit
hook to check for/prevent introducing mixed line endings.
Update:
Note: As noted by VonC, starting from Git 2.8, merge markers will not introduce Unix-style line-endings to a Windows-style file.
Original:
One little hiccup that I've noticed with this setup is that when there are merge conflicts, the lines git adds to mark up the differences do not have Windows line-endings, even when the rest of the file does, and you can end up with a file with mixed line endings, e.g.:
// Some code<CR><LF>
<<<<<<< Updated upstream<LF>
// Change A<CR><LF>
=======<LF>
// Change B<CR><LF>
>>>>>>> Stashed changes<LF>
// More code<CR><LF>
This doesn't cause us any problems (I imagine any tool that can handle both types of line-endings will also deal sensible with mixed line-endings--certainly all the ones we use do), but it's something to be aware of.
The other thing* we've found, is that when using git diff
to view changes to a file that has Windows line-endings, lines that have been added display their carriage returns, thus:
// Not changed
+ // New line added in^M
+^M
// Not changed
// Not changed
* It doesn't really merit the term: "issue".
By using java 8 java.time.LocalDate
String date = "1/13/2012";
LocalDate lastDayOfMonth = LocalDate.parse(date, DateTimeFormatter.ofPattern("M/dd/yyyy"))
.with(TemporalAdjusters.lastDayOfMonth());
It seems like one closing brace is missing at ,right(a2.chdlm,2)))) from sysibm.sysdummy1 a1,
So your Query will be
select days(current date) - days(date(select concat(concat(concat(concat(left(a2.chdlm,4),'-'),substr(a2.chdlm,4,2)),'-'),right(a2.chdlm,2)))) from sysibm.sysdummy1 a1, chcart00 a2 where chstat = '05';
In addition, notice that if your mongo shell client fails to connect correctly to the mongod
instance, you can receive such "Permission Denied" errors.
Make sure that your client opens a connection by checking the connection port, but also that the port you are using in mongod
is not in use. You can set a different port by using the --port <port>
parameter in both the shell and the process.
The answer given above can't solve my problem.So I change async into false to get the alert message.
jQuery.ajax({
type:"post",
dataType:"json",
async: false,
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(data) {
alert("Data was succesfully captured");
},
});
You can easily create your own extension method on IEnumerable or IQueryable:
public static IOrderedEnumerable<TSource> OrderByWithDirection<TSource,TKey>
(this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
public static IOrderedQueryable<TSource> OrderByWithDirection<TSource,TKey>
(this IQueryable<TSource> source,
Expression<Func<TSource, TKey>> keySelector,
bool descending)
{
return descending ? source.OrderByDescending(keySelector)
: source.OrderBy(keySelector);
}
Yes, you lose the ability to use a query expression here - but frankly I don't think you're actually benefiting from a query expression anyway in this case. Query expressions are great for complex things, but if you're only doing a single operation it's simpler to just put that one operation:
var query = dataList.OrderByWithDirection(x => x.Property, direction);
I had a somehow similar problem working with AFNetworking from a Swift codebase so I'm just leaving this here in the remote case someone is as unlucky as me having to work in such a setup. If you are, I feel you buddy, stay strong!
The operation was failing due to "unacceptable content-type", despite me actually setting the acceptableContentTypes
with a Set
containing the content type value in question.
The solution for me was to tweak the Swift code to be more Objective-C friendly, I guess:
serializer.acceptableContentTypes = NSSet(array: ["application/xml", "text/xml", "text/plain"]) as Set<NSObject>
Put your whole content in linear layout which is placed inside ScrollView
.
ScrollView
takes only one layout as its child.
isScrollContainer="true"
This property is used when your softkey in android pops up and still you want your view to scroll.
You can use Git GUI on Windows, see instructions:
Having tackled this same problem myself today, I'd like to present a solution that (currently) works on the major browsers. Some of the other answers on this page did work once, but recent updates, whether it be browser or OS, have voided most/all of these answers.
The key is to place the image in a container, and to transform:scale that container out of it's overflow:hidden parent. Then, the blur gets applied to the img inside the container, instead of on the container itself.
Working Fiddle: https://jsfiddle.net/x2c6txk2/
HTML
<div class="container">
<div class="img-holder">
<img src="https://unsplash.it/500/300/?random">
</div>
</div>
CSS
.container {
width : 90%;
height : 400px;
margin : 50px 5%;
overflow : hidden;
position : relative;
}
.img-holder {
position : absolute;
left : 0;
top : 0;
bottom : 0;
right : 0;
transform : scale(1.2, 1.2);
}
.img-holder img {
width : 100%;
height : 100%;
-webkit-filter : blur(15px);
-moz-filter : blur(15px);
filter : blur(15px);
}
First I'd say you probably want to turn off persistent connections as they almost always do more harm than good.
Secondly I'd say you want to double check your MySQL users, just to make sure it's not possible for anyone to be connecting from a remote server. This is also a major security thing to check.
Thirdly I'd say you want to turn on the MySQL Slow Query Log to keep an eye on any queries that are taking a long time, and use that to make sure you don't have any queries locking up key tables for too long.
Some other things you can check would be to run the following query while the CPU load is high:
SHOW PROCESSLIST;
This will show you any queries that are currently running or in the queue to run, what the query is and what it's doing (this command will truncate the query if it's too long, you can use SHOW FULL PROCESSLIST to see the full query text).
You'll also want to keep an eye on things like your buffer sizes, table cache, query cache and innodb_buffer_pool_size (if you're using innodb tables) as all of these memory allocations can have an affect on query performance which can cause MySQL to eat up CPU.
You'll also probably want to give the following a read over as they contain some good information.
It's also a very good idea to use a profiler. Something you can turn on when you want that will show you what queries your application is running, if there's duplicate queries, how long they're taking, etc, etc. An example of something like this is one I've been working on called PHP Profiler but there are many out there. If you're using a piece of software like Drupal, Joomla or Wordpress you'll want to ask around within the community as there's probably modules available for them that allow you to get this information without needing to manually integrate anything.
I found myself fixing a past commit frequently enough that I wrote a script for it.
Here's the workflow:
git commit-edit <commit-hash>
This will drop you at the commit you want to edit.
Fix and stage the commit as you wish it had been in the first place.
(You may want to use git stash save
to keep any files you're not committing)
Redo the commit with --amend
, eg:
git commit --amend
Complete the rebase:
git rebase --continue
For the above to work, put the below script into an executable file called git-commit-edit
somewhere in your $PATH
:
#!/bin/bash
set -euo pipefail
script_name=${0##*/}
warn () { printf '%s: %s\n' "$script_name" "$*" >&2; }
die () { warn "$@"; exit 1; }
[[ $# -ge 2 ]] && die "Expected single commit to edit. Defaults to HEAD~"
# Default to editing the parent of the most recent commit
# The most recent commit can be edited with `git commit --amend`
commit=$(git rev-parse --short "${1:-HEAD~}")
message=$(git log -1 --format='%h %s' "$commit")
if [[ $OSTYPE =~ ^darwin ]]; then
sed_inplace=(sed -Ei "")
else
sed_inplace=(sed -Ei)
fi
export GIT_SEQUENCE_EDITOR="${sed_inplace[*]} "' "s/^pick ('"$commit"' .*)/edit \\1/"'
git rebase --quiet --interactive --autostash --autosquash "$commit"~
git reset --quiet @~ "$(git rev-parse --show-toplevel)" # Reset the cache of the toplevel directory to the previous commit
git commit --quiet --amend --no-edit --allow-empty # Commit an empty commit so that that cache diffs are un-reversed
echo
echo "Editing commit: $message" >&2
echo
You have not one, but many mistakes. It should be:
int[] tall = new int[28123];
for (int j=0;j<28123;j++){
tall[j] = j+1;
}
Your code is putting a 0 in all the positions of the array.
Morover, it'll throw an exception, because the last index of the array is 28123-1 (arrays in Java start in 0!).
Use a virtual machine. Start fresh as often as you want, and stop doing these hacks that may or may not simulate a clean machine.
Seriously, use VMWare or VirtualPC.
This answer builds on the solution from @iain-elder, which works well except for the large database case (as pointed out in his solution). The entire table needs to fit in your system's memory, and for me this was not an option. I suspect the best solution would use the System.Data.SqlClient.SqlDataReader and a custom CSV serializer (see here for an example) or another language with an MS SQL driver and CSV serialization. In the spirit of the original question which was probably looking for a no dependency solution, the PowerShell code below worked for me. It is very slow and inefficient especially in instantiating the $data array and calling Export-Csv in append mode for every $chunk_size lines.
$chunk_size = 10000
$command = New-Object System.Data.SqlClient.SqlCommand
$command.CommandText = "SELECT * FROM <TABLENAME>"
$command.Connection = $connection
$connection.open()
$reader = $command.ExecuteReader()
$read = $TRUE
while($read){
$counter=0
$DataTable = New-Object System.Data.DataTable
$first=$TRUE;
try {
while($read = $reader.Read()){
$count = $reader.FieldCount
if ($first){
for($i=0; $i -lt $count; $i++){
$col = New-Object System.Data.DataColumn $reader.GetName($i)
$DataTable.Columns.Add($col)
}
$first=$FALSE;
}
# Better way to do this?
$data=@()
$emptyObj = New-Object System.Object
for($i=1; $i -le $count; $i++){
$data += $emptyObj
}
$reader.GetValues($data) | out-null
$DataRow = $DataTable.NewRow()
$DataRow.ItemArray = $data
$DataTable.Rows.Add($DataRow)
$counter += 1
if ($counter -eq $chunk_size){
break
}
}
$DataTable | Export-Csv "output.csv" -NoTypeInformation -Append
}catch{
$ErrorMessage = $_.Exception.Message
Write-Output $ErrorMessage
$read=$FALSE
$connection.Close()
exit
}
}
$connection.close()
If you want a really simple answer:
s_1 = "abc def ghi"
s_2 = "def ghi abc"
flag = 0
for i in s_1:
if i not in s_2:
flag = 1
if flag == 0:
print("a == b")
else:
print("a != b")
Use an extension method.
Ex:
namespace ExtensionMethods
{
public static class MyExtensionMethods
{
public static DateTime Tomorrow(this DateTime date)
{
return date.AddDays(1);
}
}
}
Usage:
DateTime.Now.Tomorrow();
or
AnyObjectOfTypeDateTime.Tomorrow();
Yeah, the best way is to convert the object notation to a flat key-value string representation, as mentioned in this comment: https://stackoverflow.com/a/39357531/2529199
I wanted to highlight an alternative method using this NPM library: https://www.npmjs.com/package/dot-object which lets you manipulate different objects using dot notation.
I used this pattern to programatically create a nested object property when accepting the key-value as a function variable, as follows:
const dot = require('dot-object');
function(docid, varname, varvalue){
let doc = dot.dot({
[varname]: varvalue
});
Mongo.update({_id:docid},{$set:doc});
}
This pattern lets me use nested as well as single-level properties interchangeably, and insert them cleanly into Mongo.
If you need to play around with JS Objects beyond just Mongo, especially on the client-side but have consistency when working with Mongo, this library gives you more options than the earlier mentioned mongo-dot-notation
NPM module.
P.S I originally wanted to just mention this as a comment but apparently my S/O rep isn't high enough to post a comment. So, not trying to muscle in on SzybkiSasza's comment, just wanted to highlight providing an alternative module.
It can also be retrieved from the registry:
Get-ItemProperty -Path 'HKLM:\SYSTEM\CurrentControlSet\Services\Tcpip\Parameters' |
% { $_.'NV HostName', $_.'NV Domain' -join '.' }
You do not really need jQuery for such tasks. In the ES6 specification they already have out of the box methods startsWith and endsWith.
var str = "To be, or not to be, that is the question.";
alert(str.startsWith("To be")); // true
alert(str.startsWith("not to be")); // false
alert(str.startsWith("not to be", 10)); // true
var str = "To be, or not to be, that is the question.";
alert( str.endsWith("question.") ); // true
alert( str.endsWith("to be") ); // false
alert( str.endsWith("to be", 19) ); // true
Currently available in FF and Chrome. For old browsers you can use their polyfills or substr
Copy and paste this xml to show as a Dropdown and change your Dropdown color
<?xml version="1.0" encoding="UTF-8"?><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"
android:background="@drawable/back1"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity" >
<LinearLayout
android:id="@+id/linearLayout1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_alignParentTop="true"
android:layout_marginTop="20dp"
android:background="@drawable/red">
<Spinner android:id="@+id/spinner1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:dropDownWidth="fill_parent"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
</LinearLayout>
<EditText
android:id="@+id/editText1"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/linearLayout1"
android:layout_alignRight="@+id/linearLayout1"
android:layout_below="@+id/linearLayout1"
android:layout_marginTop="25dp"
android:background="@drawable/red"
android:ems="10"
android:hint="enter card number" >
<requestFocus />
</EditText>
<LinearLayout
android:id="@+id/linearLayout2"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignLeft="@+id/editText1"
android:layout_alignRight="@+id/editText1"
android:layout_below="@+id/editText1"
android:layout_marginTop="33dp"
android:orientation="horizontal"
android:background="@drawable/red">
<Spinner
android:id="@+id/spinner3"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
<Spinner
android:id="@+id/spinner2"
android:layout_width="72dp"
android:layout_height="wrap_content"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"
/>
<EditText
android:id="@+id/editText2"
android:layout_width="22dp"
android:layout_height="match_parent"
android:layout_weight="0.18"
android:ems="10"
android:hint="enter cvv" />
</LinearLayout>
<LinearLayout
android:id="@+id/linearLayout3"
android:layout_width="wrap_content"
android:layout_height="55dp"
android:layout_alignParentLeft="true"
android:layout_alignRight="@+id/linearLayout2"
android:layout_below="@+id/linearLayout2"
android:layout_marginTop="26dp"
android:orientation="vertical"
android:background="@drawable/red" >
</LinearLayout>
<Spinner
android:id="@+id/spinner4"
android:layout_width="15dp"
android:layout_height="18dp"
android:layout_alignBottom="@+id/linearLayout3"
android:layout_alignLeft="@+id/linearLayout3"
android:layout_alignRight="@+id/linearLayout3"
android:layout_alignTop="@+id/linearLayout3"
android:popupBackground="@drawable/textbox"
android:spinnerMode="dropdown"
android:background="@drawable/drop_down_large"/>
<Button
android:id="@+id/button1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_below="@+id/linearLayout3"
android:layout_marginTop="18dp"
android:text="Add Amount"
android:background="@drawable/buttonsty"/>
sometimes require a carriage return:
os.popen("sudo -S %s"%(command), 'w').write('mypass\n')
I met this issue due to operation system, simple to different platform about JRE implementation.
new SecureRandom(key.getBytes())
will get the same value in Windows, while it's different in Linux. So in Linux need to be changed to
SecureRandom secureRandom = SecureRandom.getInstance("SHA1PRNG");
secureRandom.setSeed(key.getBytes());
kgen.init(128, secureRandom);
"SHA1PRNG" is the algorithm used, you can refer here for more info about algorithms.
You cannot use var
in a field, only on local variables.
But even this won't work:
Site master = Master as Site;
Because you cannot use this
in a field and Master as Site
is the same as this.Master as Site
. So just initialize the field from Page_Init
when the page is fully initialized and you can use this
:
Site master = null;
protected void Page_Init(object sender, EventArgs e)
{
master = this.Master as Site;
}
I have added text in ToolBar :
menu_skip.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context=".MainActivity">
<item
android:id="@+id/action_settings"
android:title="@string/text_skip"
app:showAsAction="never" />
</menu>
MainActivity.java
@Override
boolean onCreateOptionsMenu(Menu menu) {
inflater = getMenuInflater();
inflater.inflate(R.menu.menu_otp_skip, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
// action with ID action_refresh was selected
case R.id.menu_item_skip:
Toast.makeText(this, "Skip selected", Toast.LENGTH_SHORT)
.show();
break;
default:
break;
}
return true;
}
I like to use:
git diff HEAD^
Or if I only want to diff a specific file:
git diff HEAD^ -- /foo/bar/baz.txt
Without rooting: If you can't root your phone, use the run-as <package>
command to be able to access data of your application.
Example:
$ adb exec-out run-as com.yourcompany.app ls -R /data/data/com.yourcompany.app/
exec-out
executes the command without starting a shell and mangling the output.
If you'd like a hardware solution, Netgear has a series of cheap ($50 or so) switches that do bandwidth limiting. Netgear Prosafe GS105E and similar switches are worth investigating.
bootstrap 4 :
<!-- Default (left-aligned) -->
<ul class="pagination" style="margin:20px 0">
<li class="page-item">...</li>
</ul>
<!-- Center-aligned -->
<ul class="pagination justify-content-center" style="margin:20px 0">
<li class="page-item">...</li>
</ul>
<!-- Right-aligned -->
<ul class="pagination justify-content-end" style="margin:20px 0">
<li class="page-item">...</li>
</ul>
Its supported in notepad++ 5.0+ but not enabled by default. You can enable it from settings -> preferences
Another way to achieve this is using old printf()
function of C language
You can use this like
int dd = 1, mm = 9, yy = 1;
printf("%02d - %02d - %04d", mm, dd, yy);
This will print 09 - 01 - 0001
on the console.
You can also use another function sprintf()
to write formatted output to a string like below:
int dd = 1, mm = 9, yy = 1;
char s[25];
sprintf(s, "%02d - %02d - %04d", mm, dd, yy);
cout << s;
Don't forget to include stdio.h
header file in your program for both of these functions
You can fill blank space either by 0 or by another char (not number).
If you do write something like %24d
format specifier than this will not fill 2
in blank spaces. This will set pad to 24
and will fill blank spaces.
As others pointed out, it seems like you can't override nested text-decoration styles... BUT you can change the text-decoration-color.
As a hack, I changed the color to be transparent:
text-decoration-color: transparent;
I met a similar problem.But the error report is about
[SSL: TLSV1_ALERT_ACCESS_DENIED] tlsv1 alert access denied (_ssl.c:777)
First I tried this https://python-forum.io/Thread-All-pip-install-attempts-are-met-with-SSL-error#pid_28035 ,but seems it couldn't solve my problems,and still repeat the same issue.
And Second if you are working on a business computer,generally it may exist a web content filter(but I can access https://pypi.python.org through browser directly).And solve this issue by adding a proxy server.
For windows,open the Internet properties
through IE or Chrome or whatsoever ,then set valid proxy address and port,and this way solve my problems
Or just adding the option pip --proxy [proxy-address]:port install mitmproxy
.But you always need to add this option while installing by pypi
The above two solution is alternative for you demand.
gitweb will allow you to browse through the code (and changes) via a browser.
http://git.or.cz/gitwiki/Gitweb
(Don't know if someone has already setup a public gitweb for Android, but it's probably not too hard.)
You need to use built-in pathMatcher
:
@RequestMapping("/{id}/**")
public void test(HttpServletRequest request, @PathVariable long id) throws Exception {
ResourceUrlProvider urlProvider = (ResourceUrlProvider) request
.getAttribute(ResourceUrlProvider.class.getCanonicalName());
String restOfUrl = urlProvider.getPathMatcher().extractPathWithinPattern(
String.valueOf(request.getAttribute(HandlerMapping.BEST_MATCHING_PATTERN_ATTRIBUTE)),
String.valueOf(request.getAttribute(HandlerMapping.PATH_WITHIN_HANDLER_MAPPING_ATTRIBUTE)));
There are (at least) two types of package dependencies you can indicate in your package.json files:
Those packages that are required in order to use your module are listed under the "dependencies" property. Using npm you can add those dependencies to your package.json file this way:
npm install --save packageName
Those packages required in order to help develop your module are listed under the "devDependencies" property. These packages are not necessary for others to use the module, but if they want to help develop the module, these packages will be needed. Using npm you can add those devDependencies to your package.json file this way:
npm install --save-dev packageName
Like Robert Nishihara mentioned, Apache Arrow makes this easy, specifically with the Plasma in-memory object store, which is what Ray is built on.
I made brain-plasma specifically for this reason - fast loading and reloading of big objects in a Flask app. It's a shared-memory object namespace for Apache Arrow-serializable objects, including pickle
'd bytestrings generated by pickle.dumps(...)
.
The key difference with Apache Ray and Plasma is that it keeps track of object IDs for you. Any processes or threads or programs that are running on locally can share the variables' values by calling the name from any Brain
object.
$ pip install brain-plasma
$ plasma_store -m 10000000 -s /tmp/plasma
from brain_plasma import Brain
brain = Brain(path='/tmp/plasma/)
brain['a'] = [1]*10000
brain['a']
# >>> [1,1,1,1,...]
Try this:
$.ajax({
beforeSend: function() { textreplace(description); },
type: "POST",
url: "updatedjob.php",
data: "jobID="+ job +"& description="+ description +"& startDate="+ startDate +"& releaseDate="+ releaseDate +"& status="+ status,
success: function(){
$("form#updatejob").hide(function(){$("div.success").fadeIn();});
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Status: " + textStatus); alert("Error: " + errorThrown);
}
});
The beforeSend
property is set to function() { textreplace(description); }
instead of textreplace(description)
. The beforeSend
property needs a function.
If you happen to already have a diff tool associated with filetypes (say, because you installed TortoiseSVN which comes with a diff viewer) you could just pipe the regular git diff
output to a "temp" file, then just open that file directly without needing to know anything about the viewer:
git diff > "~/temp.diff" && start "~/temp.diff"
Setting it as a global alias works even better: git what
[alias]
what = "!f() { git diff > "~/temp.diff" && start "~/temp.diff"; }; f"
You can implement an IEqualityComparer and use that in your Distinct extension.
class CarEqualityComparer : IEqualityComparer<Car>
{
#region IEqualityComparer<Car> Members
public bool Equals(Car x, Car y)
{
return x.CarCode.Equals(y.CarCode);
}
public int GetHashCode(Car obj)
{
return obj.CarCode.GetHashCode();
}
#endregion
}
And then
var uniqueCars = cars.Distinct(new CarEqualityComparer());
More simply in one line:
proxy=192.168.2.1:8080;curl -v example.com
eg. $proxy=192.168.2.1:8080;curl -v example.com
xxxxxxxxx-ASUS:~$ proxy=192.168.2.1:8080;curl -v https://google.com|head -c 15 % Total % Received % Xferd Average Speed Time Time Time Current Dload Upload Total Spent Left Speed 0 0 0 0 0 0 0 0 --:--:-- --:--:-- --:--:-- 0
While @perrejba s answer is correct, it uses the legacy C-style functions. As the question is tagged C++, you may want to use a method instead:
inputMat.copyTo(outputMat, maskMat);
All objects are of type cv::Mat
.
Please be aware that the masking is binary. Any non-zero value in the mask is interpreted as 'do copy'. Even if the mask is a greyscale image.
Also be aware that the .copyTo() function does not clear the output before copying.
If you want to permanently alter the original Image, you have to do an additional copy/clone/assignment. The copyTo() function is not defined for overlapping input/output images. So you can't use the same image as both input and output.
Most answers here forget the obvious culprit why recursion is often slower than iterative solutions. It's linked with the build up and tear down of stack frames but is not exactly that. It's generally a big difference in the storage of the auto variable for each recursion. In an iterative algorithm with a loop, the variables are often held in registers and even if they spill, they will reside in the Level 1 cache. In a recursive algorithm, all intermediary states of the variable are stored on the stack, meaning they will engender many more spills to memory. This means that even if it makes the same amount of operations, it will have a lot memory accesses in the hot loop and what makes it worse, these memory operations have a lousy reuse rate making the caches less effective.
TL;DR recursive algorithms have generally a worse cache behavior than iterative ones.
If order does not matter, you can use
"".join(set(foo))
set()
will create a set of unique letters in the string, and "".join()
will join the letters back to a string in arbitrary order.
If order does matter, you can use a dict
instead of a set, which since Python 3.7 preserves the insertion order of the keys. (In the CPython implementation, this is already supported in Python 3.6 as an implementation detail.)
foo = "mppmt"
result = "".join(dict.fromkeys(foo))
resulting in the string "mpt"
. In earlier versions of Python, you can use collections.OrderedDict
, which has been available starting from Python 2.7.
This also closely relates to:
if ("foo".equals(bar)) {
which is convenient if you don't want to deal with NPEs:
if (bar!=null && bar.equals("foo")) {
Another option is to use the defer attribute on the script, but it's only appropriate for external scripts with a src attribute:
<script src = "exampleJsFile.js" defer> </script>
Following worked for me:
CSS
.round {
border-radius: 50%;
overflow: hidden;
width: 30px;
height: 30px;
background: no-repeat 50%;
object-fit: cover;
}
.round img {
display: block;
height: 100%;
width: 100%;
}
HTML
<div class="round">
<img src="test.png" />
</div>
You can achieve that using DATE_FORMAT() (click the link for more other formats)
SELECT DATE_FORMAT(colName, '%Y-%m-%d') DATEONLY,
DATE_FORMAT(colName,'%H:%i:%s') TIMEONLY
UILabel *mycoollabel=[[UILabel alloc]initWithFrame:CGRectMake(10, 70, 50, 50)];
mycoollabel.text=@"I am cool";
// for multiple lines,if text lenght is long use next line
mycoollabel.numberOfLines=0;
[self.View addSubView:mycoollabel];
Check if the activity isFinishing()
before showing the fragment and pay attention to commitAllowingStateLoss()
.
Example:
if(!isFinishing()) {
FragmentManager fm = getSupportFragmentManager();
FragmentTransaction ft = fm.beginTransaction();
DummyFragment dummyFragment = DummyFragment.newInstance();
ft.add(R.id.dummy_fragment_layout, dummyFragment);
ft.commitAllowingStateLoss();
}
Momentjs.com has good documentation on how to manipulate the date/time in relation to the current moment. Since Momentjs is required for the Datetimepicker, might as well use it.
var startDefault = moment().startof('day').add(1, 'minutes');
$('#startdatetime-from').datetimepicker({
defaultDate: startDefault,
language: 'en',
format: 'yyyy-MM-dd hh:mm'
});
I ended up using Javascript to perfect everything.
My JS fiddle: https://jsfiddle.net/QEpJH/612/
HTML:
<div class="container">
<img src="http://placekitten.com/240/300">
</div>
<h3 style="clear: both;">Full Size Image - For Reference</h3>
<img src="http://placekitten.com/240/300">
CSS:
.container {
background-color:#000;
width:100px;
height:200px;
display:flex;
justify-content:center;
align-items:center;
overflow:hidden;
}
JS:
$(".container").each(function(){
var divH = $(this).height()
var divW = $(this).width()
var imgH = $(this).children("img").height();
var imgW = $(this).children("img").width();
if ( (imgW/imgH) < (divW/divH)) {
$(this).addClass("1");
var newW = $(this).width();
var newH = (newW/imgW) * imgH;
$(this).children("img").width(newW);
$(this).children("img").height(newH);
} else {
$(this).addClass("2");
var newH = $(this).height();
var newW = (newH/imgH) * imgW;
$(this).children("img").width(newW);
$(this).children("img").height(newH);
}
})
Find your php.ini
and look for XDebug.
Set xdebug autostart to false
xdebug.remote_autostart=0
xdebug.remote_enable=0
Disable your profiler
xdebug.profiler_enable=0
Note that there can be a performance loss even with xdebug disabled but loaded. To disable loading of the extension itself, you need to comment it in your php.ini. Find an entry looking like this:
zend_extension = "/path/to/php_xdebug.dll"
and put a ;
to comment it, e.g. ;zend_extension = …
.
Check out this post XDebug, how to disable remote debugging for single .php file?
This is for windows:
For example, I have a folder named "mygrapher" on my desktop. Inside, there's folders called "calculation" and "graphing" that contain Python files that my main file "grapherMain.py" needs. Also, "grapherMain.py" is stored in "graphing". To run everything without moving files, I can make a batch script. Let's call this batch file "rungraph.bat".
@ECHO OFF
setlocal
set PYTHONPATH=%cd%\grapher;%cd%\calculation
python %cd%\grapher\grapherMain.py
endlocal
This script is located in "mygrapher". To run things, I would get into my command prompt, then do:
>cd Desktop\mygrapher (this navigates into the "mygrapher" folder)
>rungraph.bat (this executes the batch file)
My answer is similar but different, there are a few ways to achieve toggling effect. I guess it depends on your circumstance. This may not be the best way for you in the end.
The missing piece you've been looking for is to create an if
statement. This allows for you to toggle your text.
JSFiddle: http://jsfiddle.net/8u2jF/
Javascript:
var status = "less";
function toggleText()
{
var text="Here is some text that I want added to the HTML file";
if (status == "less") {
document.getElementById("textArea").innerHTML=text;
document.getElementById("toggleButton").innerText = "See Less";
status = "more";
} else if (status == "more") {
document.getElementById("textArea").innerHTML = "";
document.getElementById("toggleButton").innerText = "See More";
status = "less"
}
}
There are two ways to set this up. If you have an SID, use this (older) format:
jdbc:oracle:thin:@[HOST][:PORT]:SID
If you have an Oracle service name, use this (newer) format:
jdbc:oracle:thin:@//[HOST][:PORT]/SERVICE
Source: this OraFAQ page
The call to getConnection()
is correct.
Also, as duffymo said, make sure the actual driver code is present by including ojdbc6.jar
in the classpath, where the number corresponds to the Java version you're using.
Wouldn't doing it this way be much more unlikely for mistakes?
int[] intArray = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int[] temp = new int[intArray.length];
for(int i = intArray.length - 1; i > -1; i --){
temp[intArray.length - i -1] = intArray[i];
}
intArray = temp;
You can use lock variables "a" and "b" and synchronize them for locking the "critical section" in reverse order. Eg. Notify "a" then Lock "b" ,"PRINT", Notify "b" then Lock "a".
Please refer the below the code :
public class EvenOdd {
static int a = 0;
public static void main(String[] args) {
EvenOdd eo = new EvenOdd();
A aobj = eo.new A();
B bobj = eo.new B();
aobj.a = Lock.lock1;
aobj.b = Lock.lock2;
bobj.a = Lock.lock2;
bobj.b = Lock.lock1;
Thread t1 = new Thread(aobj);
Thread t2 = new Thread(bobj);
t1.start();
t2.start();
}
static class Lock {
final static Object lock1 = new Object();
final static Object lock2 = new Object();
}
class A implements Runnable {
Object a;
Object b;
public void run() {
while (EvenOdd.a < 10) {
try {
System.out.println(++EvenOdd.a + " A ");
synchronized (a) {
a.notify();
}
synchronized (b) {
b.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
class B implements Runnable {
Object a;
Object b;
public void run() {
while (EvenOdd.a < 10) {
try {
synchronized (b) {
b.wait();
System.out.println(++EvenOdd.a + " B ");
}
synchronized (a) {
a.notify();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
OUTPUT :
1 A
2 B
3 A
4 B
5 A
6 B
7 A
8 B
9 A
10 B