I think LayeredPane is your best bet here. You would need a third panel though to contain A and B. This third panel would be the layeredPane and then panel A and B could still have a nice LayoutManagers. All you would have to do is center B over A and there is quite a lot of examples in the Swing trail on how to do this. Tutorial for positioning without a LayoutManager.
public class Main {
private JFrame frame = new JFrame();
private JLayeredPane lpane = new JLayeredPane();
private JPanel panelBlue = new JPanel();
private JPanel panelGreen = new JPanel();
public Main()
{
frame.setPreferredSize(new Dimension(600, 400));
frame.setLayout(new BorderLayout());
frame.add(lpane, BorderLayout.CENTER);
lpane.setBounds(0, 0, 600, 400);
panelBlue.setBackground(Color.BLUE);
panelBlue.setBounds(0, 0, 600, 400);
panelBlue.setOpaque(true);
panelGreen.setBackground(Color.GREEN);
panelGreen.setBounds(200, 100, 100, 100);
panelGreen.setOpaque(true);
lpane.add(panelBlue, new Integer(0), 0);
lpane.add(panelGreen, new Integer(1), 0);
frame.pack();
frame.setVisible(true);
}
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
new Main();
}
}
You use setBounds to position the panels inside the layered pane and also to set their sizes.
Edit to reflect changes to original post You will need to add component listeners that detect when the parent container is being resized and then dynamically change the bounds of panel A and B.
After removing the innodb_additional_mem_pool_size=4M from my.ini and killing that process that used the port that Mysql wanted I managed it to go.
Suggested fix: 1) The quick solution: Comment the line innodb_additional_mem_pool_size=4M in the service's 'my.ini' file, 2) exclude the option from the 5.7.4 default config file or 3) un-unknow the variable to mysql ;)
link: http://bugs.mysql.com/bug.php?id=72533
Use number 1, remove the whole line. Save to my.ini. Kill the process if you have one running (look at them with resmon.exe and kill them with command taskkill /pid pid-of-process /f), then start wampmysql and your icon should turn green.
Regards SB
With ES6 you can do something like this:
const swapPositions = (array, a ,b) => {
[array[a], array[b]] = [array[b], array[a]]
}
let array = [1,2,3,4,5];
swapPositions(array,0,1);
/// => [2, 1, 3, 4, 5]
Anyone can define "token_type" as an OAuth 2.0 extension, but currently "bearer" token type is the most common one.
https://tools.ietf.org/html/rfc6750
Basically that's what Facebook is using. Their implementation is a bit behind from the latest spec though.
If you want to be more secure than Facebook (or as secure as OAuth 1.0 which has "signature"), you can use "mac" token type.
However, it will be hard way since the mac spec is still changing rapidly.
Instead of:
var host = req.get('host');
var origin = req.get('origin');
you can also use:
var host = req.headers.host;
var origin = req.headers.origin;
Use Notepad ++ and use the option to Convert the file to UNIX format. That should solve this problem.
Here's how to do the same with Swift;
var valueToSave = "someValue"
NSUserDefaults.standardUserDefaults().setObject(valueToSave, forKey: "preferenceName")
To get it back later;
if let savedValue = NSUserDefaults.standardUserDefaults().stringForKey("preferenceName") {
// Do something with savedValue
}
In Swift 3.0
var valueToSave = "someValue"
UserDefaults.standard.set(valueToSave, forKey: "preferenceName")
if let savedValue = UserDefaults.standard.string(forKey: "preferenceName") {
}
Same issue here using IDEA 15.0.6, and nothing helped except when I renamed the package the test class was in. Afterwards I renamed it back to its original name and it still worked, so the rename action might have cleared some cache.
You can use Apache POI for creating native binary xls files.
Or you can use JExcelApi which is another, and somewhat light-weight as far as I can remember, Java library for Excel.
As of Laravel 5.6, if you have this kind of structure and you want to include another blade file inside a subfolder,
|--- views
|------- parentFolder (Folder)
|---------- name.blade.php (Blade File)
|---------- childFolder (Folder)
|-------------- mypage.blade.php (Blade File)
name.blade.php
<html>
@include('parentFolder.childFolder.mypage')
</html>
Is there something that prevents you from merging all revisions on trunk since the last merge?
svn merge -rLastRevisionMergedFromTrunkToBranch:HEAD url/of/trunk path/to/branch/wc
should work just fine. At least if you want to merge all changes on trunk to your branch.
That solved my problem on Ubuntu 14.04:
apt-get install libcurl4-gnutls-dev
The reason is that the Scanner class is designed for reading in whitespace-separated tokens. It's a convenience class that wraps an underlying input stream. Before scanner all you could do was read in single bytes, and that's a big pain if you want to read words or lines. With Scanner you pass in System.in, and it does a number of read() operations to tokenize the input for you. Reading a single character is a more basic operation. Source
You can use (char) System.in.read();
.
First off, BigDecimal.multiply()
returns a BigDecimal
and you're trying to store that in an int
.
Second, it takes another BigDecimal
as the argument, not an int
.
If you just use the BigDecimal
for all variables involved in these calculations, it should work fine.
All of the answers address the question posed in the title. However, I would like to add a caveat that is implicit in the text. Bézier patches are used to represent the surface, but you cannot just transform the points of the patch and tessellate the patch into polygons, because this will result in distorted geometry. You can, however, tessellate the patch first into polygons using a transformed screen tolerance and then transform the polygons, or you can convert the Bézier patches to rational Bézier patches, then tessellate those using a screen-space tolerance. The former is easier, but the latter is better for a production system.
I suspect that you want the easier way. For this, you would scale the screen tolerance by the norm of the Jacobian of the inverse perspective transformation and use that to determine the amount of tessellation that you need in model space (it might be easier to compute the forward Jacobian, invert that, then take the norm). Note that this norm is position-dependent, and you may want to evaluate this at several locations, depending on the perspective. Also remember that since the projective transformation is rational, you need to apply the quotient rule to compute the derivatives.
Try this
// UILabel *myLabel;
CGSize labelSize = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping];
CGFloat labelHeight = labelSize.height;
int lines = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:NSLineBreakByWordWrapping].height/16;
// '16' is font size
or
int lines = labelHeight/16;
NSLog(@"lines count : %i \n\n",lines);
or
int lines = [myLabel.text sizeWithFont:myLabel.font
constrainedToSize:myLabel.frame.size
lineBreakMode:UILineBreakModeWordWrap].height /myLabel.font.pointSize; //fetching font size from font
By Using Categories, Just Create the category class named as
UILabel+UILabelDynamicHeight.h
UILabel+UILabelDynamicHeight.m
No more tension about the height calculation. Please review the below implementation.
Updates for iOS7 & Above,iOS 7 below : Dynamically calculate the UILabel height
#define SYSTEM_VERSION_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedSame)
#define SYSTEM_VERSION_GREATER_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedDescending)
#define SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] == NSOrderedAscending)
#define SYSTEM_VERSION_LESS_THAN_OR_EQUAL_TO(v) ([[[UIDevice currentDevice] systemVersion] compare:v options:NSNumericSearch] != NSOrderedDescending)
#define iOS7_0 @"7.0"
UILabel+UILabelDynamicHeight.h
#import <UIKit/UIKit.h>
@interface UILabel (UILabelDynamicHeight)
#pragma mark - Calculate the size the Multi line Label
/*====================================================================*/
/* Calculate the size of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel;
@end
UILabel+UILabelDynamicHeight.m
#import "UILabel+UILabelDynamicHeight.h"
@implementation UILabel (UILabelDynamicHeight)
#pragma mark - Calculate the size,bounds,frame of the Multi line Label
/*====================================================================*/
/* Calculate the size,bounds,frame of the Multi line Label */
/*====================================================================*/
/**
* Returns the size of the Label
*
* @param aLabel To be used to calculte the height
*
* @return size of the Label
*/
-(CGSize)sizeOfMultiLineLabel{
//Label text
NSString *aLabelTextString = [self text];
//Label font
UIFont *aLabelFont = [self font];
//Width of the Label
CGFloat aLabelSizeWidth = self.frame.size.width;
if (SYSTEM_VERSION_LESS_THAN(iOS7_0)) {
//version < 7.0
return [aLabelTextString sizeWithFont:aLabelFont
constrainedToSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
lineBreakMode:NSLineBreakByWordWrapping];
}
else if (SYSTEM_VERSION_GREATER_THAN_OR_EQUAL_TO(iOS7_0)) {
//version >= 7.0
//Return the calculated size of the Label
return [aLabelTextString boundingRectWithSize:CGSizeMake(aLabelSizeWidth, MAXFLOAT)
options:NSStringDrawingUsesLineFragmentOrigin
attributes:@{
NSFontAttributeName : aLabelFont
}
context:nil].size;
}
return [self bounds].size;
}
@end
If this is related to a form submission, use a hidden inputinside the form and change the hidden input value to this variable value. Then you can get that hidden input value in the php page and assign it to your php variable after form submission.
Update:
According to your edit, it seems you don't understand how javascript and php works. Javascript is a client side language, and php is a serverside language. Therefore you cannot execute javascript logic and use that variable value to a php variable when you execute relevant page in the server. You can run the relevant javascript logic after client browser process the web page returned from the web server (which has already executed the php code for the relevant page). After the execution of the javascript code and after assigning the relevant value to the relevant javascript variable, you can use form submission or ajax to send that javascript variable value to use by another php page (or a request to process and get the same php page).
List<Person> list = new ArrayList<Person>();
Criteria criteria = this.getSessionFactory().getCurrentSession().createCriteria(Person.class);
for (final Object o : criteria.list()) {
list.add((Person) o);
}
One item that seems to have been missed is star transformations. Index Intersection operators resolve the predicate by calculating the set of rows hit by each of the predicates before any I/O is done on the fact table. On a star schema you would index each individual dimension key and the query optimiser can resolve which rows to select by the index intersection computation. The indexes on individual columns give the best flexibility for this.
I was looking a lot to find a solution for sticy menue with old school JS (without JQuery). So I build small test to play with it. I think it can be helpfull to those looking for solution in js. It needs improvments of unsticking the menue back, and making it more smooth. Also I find a nice solution with JQuery that clones the original div instead of position fixed, its better since the rest of page element dont need to be replaced after fixing. Anyone know how to that with JS ? Please remark, correct and improve.
<!DOCTYPE html>
<html>
<head>
<script>
// addEvent function by John Resig:
// http://ejohn.org/projects/flexible-javascript-events/
function addEvent( obj, type, fn ) {
if ( obj.attachEvent ) {
obj['e'+type+fn] = fn;
obj[type+fn] = function(){obj['e'+type+fn]( window.event );};
obj.attachEvent( 'on'+type, obj[type+fn] );
} else {
obj.addEventListener( type, fn, false );
}
}
function getScrollY() {
var scrOfY = 0;
if( typeof( window.pageYOffset ) == 'number' ) {
//Netscape compliant
scrOfY = window.pageYOffset;
} else if( document.body && document.body.scrollTop ) {
//DOM compliant
scrOfY = document.body.scrollTop;
}
return scrOfY;
}
</script>
<style>
#mydiv {
height:100px;
width:100%;
}
#fdiv {
height:100px;
width:100%;
}
</style>
</head>
<body>
<!-- HTML for example event goes here -->
<div id="fdiv" style="background-color:red;position:fix">
</div>
<div id="mydiv" style="background-color:yellow">
</div>
<div id="fdiv" style="background-color:green">
</div>
<script>
// Script for example event goes here
addEvent(window, 'scroll', function(event) {
var x = document.getElementById("mydiv");
var y = getScrollY();
if (y >= 100) {
x.style.position = "fixed";
x.style.top= "0";
}
});
</script>
</body>
</html>
You are right, the documentation lacks of those methods. However when I dug into rxjs repository, I found nice comments about tap (too long to paste here) and pipe operators:
/**
* Used to stitch together functional operators into a chain.
* @method pipe
* @return {Observable} the Observable result of all of the operators having
* been called in the order they were passed in.
*
* @example
*
* import { map, filter, scan } from 'rxjs/operators';
*
* Rx.Observable.interval(1000)
* .pipe(
* filter(x => x % 2 === 0),
* map(x => x + x),
* scan((acc, x) => acc + x)
* )
* .subscribe(x => console.log(x))
*/
Pipe: Used to stitch together functional operators into a chain. Before we could just do observable.filter().map().scan()
, but since every RxJS operator is a standalone function rather than an Observable's method, we need pipe()
to make a chain of those operators (see example above).
Tap: Can perform side effects with observed data but does not modify the stream in any way. Formerly called do()
. You can think of it as if observable was an array over time, then tap()
would be an equivalent to Array.forEach()
.
Look at the exception:
No qualifying bean of type [edu.java.spring.ws.dao.UserDao] found for dependency
This means that there's no bean available to fulfill that dependency. Yes, you have an implementation of the interface, but you haven't created a bean for that implementation. You have two options:
UserDaoImpl
with @Component
or @Repository
, and let the component scan do the work for you, exactly as you have done with UserService
.UserBoImpl
.Remember that if you create the bean explicitly you need to put the definition before the component scan. In this case the order is important.
View -> Show Symbol -> uncheck Show All characters
A simple two lines of code works for me.
dataGridView.DataSource = dataTable;
dataGridView.AutoResizeColumns();
Quote from this post (it's written by the author of doxygen himself) :
run doxygen -g and change the following options of the generated Doxyfile:
EXTRACT_ALL = YES
HAVE_DOT = YES
UML_LOOK = YES
run doxygen again
Hey i think The fastest way to handle that kind of operation is to memset() the memory.
Example-
memset(&myPage.pageArray[0][0], 0, sizeof(myPage.pageArray));
A similar C++ way would be to use std::fill
char *begin = myPage.pageArray[0][0];
char *end = begin + sizeof(myPage.pageArray);
std::fill(begin, end, 0);
You need to specify how you'll authenticate with the database. If you want to use integrated security (this means using Windows authentication using your local or domain Windows account), add this to the connection string:
Integrated Security = True;
If you want to use SQL Server authentication (meaning you specify a login and password rather than using a Windows account), add this:
User ID = "username"; Password = "password";
Let's go to the source -- 2.6.32, for example. The message is printed by show_signal_msg() function in arch/x86/mm/fault.c if the show_unhandled_signals sysctl is set.
"error" is not an errno nor a signal number, it's a "page fault error code" -- see definition of enum x86_pf_error_code.
"[7fa44d2f8000+f6f000]" is starting address and size of virtual memory area where offending object was mapped at the time of crash. Value of "ip" should fit in this region. With this info in hand, it should be easy to find offending code in gdb.
Open a port in your server with netcat and start listening:
nc -lvp port number
And on the machine you are reading the serial port, send it with netcat as root:
nc <IP address> portnumber < /dev/ttyACM0
If you want to store the data on the server you can redirect the data to a text file.
First create a file where you are saving the data:
touch data.txt
And then start saving data
nc -lvp port number > data.txt
The right way to do this, starting with Spring 4.1, is to use a @TestPropertySource
annotation.
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:whereever/context.xml")
@TestPropertySource(properties = {"myproperty = foo"})
public class TestWarSpringContext {
...
}
See @TestPropertySource in the Spring docs and Javadocs.
Another possibility is a mixture of release and debug builds in the dependencies. For example, Assembly A depends on Assembly B, A was built in Debug mode while the copy of B in GAC was built in Release mode, or vice versa.
This may be helpful whenever you need a very very random token
<?php
echo mb_strtoupper(strval(bin2hex(openssl_random_pseudo_bytes(16))));
?>
Just call the onBackPressed()
method in the activity you want to show the dialog and inside it show your dialog.
Go in xampp/apache/conf/httpd.conf and open it. Then just chang 2 lines
Listen 80
to
Listen 81
And
ServerName localhost:80
to
ServerName localhost:81
Then start using admin privileges.
As I am working in a corporate environment where developers faces firewall issues, none of the other answers resolved my issue.
As the port is not used by Skype, but by some other internal applications, I followed the below steps to resolve the issue:
Step 1 - From the XAMPP Control Panel, under Apache, click the Config button, and select the Apache (httpd.conf).
Inside the httpd.conf file, somehow I found a line that says:
Listen 80 And change the 80 into any number / port you want. In my scenario I’m using port 8080.
Listen 8080 Still from the httpd.conf file,
You should also do this in the same process Still from the httpd-ssl.conf file, find another line that says
ServerName localhost:443 And change 443 to 4433.
ServerName localhost:4433 Remember to save the httpd.conf and httpd-ssl.conf files after performing some changes. Then restart the Apache service.
Here is a working example in both Javascript and jQuery:
http://jsfiddle.net/GuLYN/312/
//In jQuery
$("#calculate").click(function() {
var num = parseFloat($("#textbox").val());
var new_num = $("#textbox").val(num.toFixed(2));
});
// In javascript
document.getElementById('calculate').onclick = function() {
var num = parseFloat(document.getElementById('textbox').value);
var new_num = num.toFixed(2);
document.getElementById('textbox').value = new_num;
};
?
I've used like this
function chatSearchCtrl($scope, $http,$sce) {
// some more my code
// take this
data['message'] = $sce.trustAsHtml(data['message']);
$scope.searchresults = data;
and in html I did
<p class="clsPyType clsChatBoxPadding" ng-bind-html="searchresults.message"></p>
thats it I get my <br/>
tag rendered
Welcome to Microsoft Marketing Speak hell. With the 2012 release of SQL Server, the BIDS, Business Intelligence Designer Studio, plugin for Visual Studio was renamed to SSDT, SQL Server Data Tools. SSDT is available for 2010 and 2012. The problem is, there are two different products called SSDT.
There is SSDT which replaces the database designer thing which was called Data Dude in VS 2008 and in 2010 became database projects. That a free install and if you snag the web installer, that's what you get when you install SSDT. It puts the correct project templates and such into Visual Studio.
There's also the SSDT which is the "BIDS" replacement for developing SSIS, SSRS and SSAS stuff. As of March 2013, it is now available for the 2012 release of Visual Studio. The download is labeled SSDTBI_VS2012_X86.msi Perhaps that's a signal on how the product is going to be referred to in marketing materials. Download links are
None the less, we have Business Intelligence projects available to us in Visual Studio 2012. And the people did rejoice and did feast upon the lambs and toads and tree-sloths and fruit-bats and orangutans and breakfast cereals
As you have noticed, xscale
and yscale
does not support a simple linear re-scaling (unfortunately). As an alternative to Hooked's answer, instead of messing with the data, you can trick the labels like so:
ticks = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x*scale))
ax.xaxis.set_major_formatter(ticks)
A complete example showing both x and y scaling:
import numpy as np
import pylab as plt
import matplotlib.ticker as ticker
# Generate data
x = np.linspace(0, 1e-9)
y = 1e3*np.sin(2*np.pi*x/1e-9) # one period, 1k amplitude
# setup figures
fig = plt.figure()
ax1 = fig.add_subplot(121)
ax2 = fig.add_subplot(122)
# plot two identical plots
ax1.plot(x, y)
ax2.plot(x, y)
# Change only ax2
scale_x = 1e-9
scale_y = 1e3
ticks_x = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_x))
ax2.xaxis.set_major_formatter(ticks_x)
ticks_y = ticker.FuncFormatter(lambda x, pos: '{0:g}'.format(x/scale_y))
ax2.yaxis.set_major_formatter(ticks_y)
ax1.set_xlabel("meters")
ax1.set_ylabel('volt')
ax2.set_xlabel("nanometers")
ax2.set_ylabel('kilovolt')
plt.show()
And finally I have the credits for a picture:
Note that, if you have text.usetex: true
as I have, you may want to enclose the labels in $
, like so: '${0:g}$'
.
Use this
style="@android:style/Widget.ProgressBar.Horizontal"
There is a temporary work around in Reenable (temporary) showModalDialog support in Chrome (for Windows) 37+.
Basically, create a new string in the registry at
HKEY_LOCAL_MACHINE\SOFTWARE\Policies\Google\Chrome\EnableDeprecatedWebPlatformFeatures
Under the EnableDeprecatedWebPlatformFeatures key, create a string value with the name 1
and a value of ShowModalDialog_EffectiveUntil20150430
. To verify that the policy is enabled, visit chrome://policy
URL.
You can easily customize the android Navigation drawer once you know how its implemented. here is a nice tutorial where you can set it up.
This will be the structure of your mainXML:
<android.support.v4.widget.DrawerLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!-- Framelayout to display Fragments -->
<FrameLayout
android:id="@+id/frame_container"
android:layout_width="match_parent"
android:layout_height="match_parent" />
<!-- Listview to display slider menu -->
<ListView
android:id="@+id/list_slidermenu"
android:layout_width="240dp"
android:layout_height="match_parent"
android:layout_gravity="right"
android:choiceMode="singleChoice"
android:divider="@color/list_divider"
android:dividerHeight="1dp"
android:listSelector="@drawable/list_selector"
android:background="@color/list_background"/>
</android.support.v4.widget.DrawerLayout>
You can customize this listview to your liking by adding the header. And radiobuttons.
Imagine this scenario
In this case you could set certain styles in your global CSS file as important, thus overriding inline styles set directly on elements.
This kind of scenario usually happens when you don't have total control over your HTML. Think of solutions in SharePoint for instance. You'd like your part to be globally defined (styled), but some inline styles you can't control are present. !important
makes such situations easier to deal with.
Other real life scenarios would also include some badly written jQuery plugins that also use inline styles...
I suppose you got the idea by now and can come up with some others as well.
!important
?I suggest you don't use !important
unless you can't do it any other way. Whenever it's possible to avoid it, avoid it. Using lots of !important
styles will make maintenance a bit harder, because you break the natural cascading in your stylesheets.
The docs indicate that numpy.correlate
is not what you are looking for:
numpy.correlate(a, v, mode='valid', old_behavior=False)[source]
Cross-correlation of two 1-dimensional sequences.
This function computes the correlation as generally defined in signal processing texts:
z[k] = sum_n a[n] * conj(v[n+k])
with a and v sequences being zero-padded where necessary and conj being the conjugate.
Instead, as the other comments suggested, you are looking for a Pearson correlation coefficient. To do this with scipy try:
from scipy.stats.stats import pearsonr
a = [1,4,6]
b = [1,2,3]
print pearsonr(a,b)
This gives
(0.99339926779878274, 0.073186395040328034)
You can also use numpy.corrcoef
:
import numpy
print numpy.corrcoef(a,b)
This gives:
[[ 1. 0.99339927]
[ 0.99339927 1. ]]
I could get image width and height by its drawable;
int width = imgView.getDrawable().getIntrinsicWidth();
int height = imgView.getDrawable().getIntrinsicHeight();
Use the following representation instead:
local items = { apple=true, orange=true, pear=true, banana=true }
if items.apple then
...
end
Can also be thought of as the number of ways of choosing pairs of nodes n choose 2 = n(n-1)/2. True if only any pair can have only one edge. Multiply by 2 otherwise
If splitting very large files, the solution I found is an adaptation from this, with PowerShell "embedded" in a batch file. This works fast, as opposed to many other things I tried (I wouldn't know about other options posted here).
The way to use mysplit.bat
below is
mysplit.bat <mysize> 'myfile'
Note: The script was intended to use the first argument as the split size. It is currently hardcoded at 100Mb. It should not be difficult to fix this.
Note 2: The filname should be enclosed in single quotes. Other alternatives for quoting apparently do not work.
Note 3: It splits the file at given number of bytes, not at given number of lines. For me this was good enough. Some lines of code could be probably added to complete each chunk read, up to the next CR/LF. This will split in full lines (not with a constant number of them), with no sacrifice in processing time.
Script mysplit.bat
:
@REM Using https://stackoverflow.com/questions/19335004/how-to-run-a-powershell-script-from-a-batch-file
@REM and https://stackoverflow.com/questions/1001776/how-can-i-split-a-text-file-using-powershell
@PowerShell ^
$upperBound = 100MB; ^
$rootName = %2; ^
$from = $rootName; ^
$fromFile = [io.file]::OpenRead($from); ^
$buff = new-object byte[] $upperBound; ^
$count = $idx = 0; ^
try { ^
do { ^
'Reading ' + $upperBound; ^
$count = $fromFile.Read($buff, 0, $buff.Length); ^
if ($count -gt 0) { ^
$to = '{0}.{1}' -f ($rootName, $idx); ^
$toFile = [io.file]::OpenWrite($to); ^
try { ^
'Writing ' + $count + ' to ' + $to; ^
$tofile.Write($buff, 0, $count); ^
} finally { ^
$tofile.Close(); ^
} ^
} ^
$idx ++; ^
} while ($count -gt 0); ^
} ^
finally { ^
$fromFile.Close(); ^
} ^
%End PowerShell%
Here is a copy of code which works fine for me
import json
with open("test.json") as json_file:
json_data = json.load(json_file)
print(json_data)
with the data
{
"a": [1,3,"asdf",true],
"b": {
"Hello": "world"
}
}
you may want to wrap your json.load line with a try catch because invalid JSON will cause a stacktrace error message.
Come out of the "python interpreter."
I hope this should work
You can use bookmarklets if you want run bigger scripts in more convenient way and run them automatically by one click.
http://encosia.com/using-cors-to-access-asp-net-services-across-domains/
refer the above link for more details on Cross domain resource sharing.
you can try using JSONP . If the API is not supporting jsonp, you have to create a service which acts as a middleman between the API and your client. In my case, i have created a asmx service.
sample below:
ajax call:
$(document).ready(function () {
$.ajax({
crossDomain: true,
type:"GET",
contentType: "application/json; charset=utf-8",
async:false,
url: "<your middle man service url here>/GetQuote?callback=?",
data: { symbol: 'ctsh' },
dataType: "jsonp",
jsonpCallback: 'fnsuccesscallback'
});
});
service (asmx) which will return jsonp:
[WebMethod]
[ScriptMethod(UseHttpGet = true, ResponseFormat = ResponseFormat.Json)]
public void GetQuote(String symbol,string callback)
{
WebProxy myProxy = new WebProxy("<proxy url here>", true);
myProxy.Credentials = new System.Net.NetworkCredential("username", "password", "domain");
StockQuoteProxy.StockQuote SQ = new StockQuoteProxy.StockQuote();
SQ.Proxy = myProxy;
String result = SQ.GetQuote(symbol);
StringBuilder sb = new StringBuilder();
JavaScriptSerializer js = new JavaScriptSerializer();
sb.Append(callback + "(");
sb.Append(js.Serialize(result));
sb.Append(");");
Context.Response.Clear();
Context.Response.ContentType = "application/json";
Context.Response.Write(sb.ToString());
Context.Response.End();
}
SQL has no built in notion of order, so you need to order by some column for this to be meaningful. Something like this:
select t1.value - t2.value from table t1, table t2
where t1.primaryKey = t2.primaryKey - 1
If you know how to order things but not how to get the previous value given the current one (EG, you want to order alphabetically) then I don't know of a way to do that in standard SQL, but most SQL implementations will have extensions to do it.
Here is a way for SQL server that works if you can order rows such that each one is distinct:
select rank() OVER (ORDER BY id) as 'Rank', value into temp1 from t
select t1.value - t2.value from temp1 t1, temp1 t2
where t1.Rank = t2.Rank - 1
drop table temp1
If you need to break ties, you can add as many columns as necessary to the ORDER BY.
Depending on the type of application, another thing to check is under the Advanced Settings for the Application Pool make sure "Enable 32-Bit Applications" is set to True.
I'd checked everything in this thread when I had this issue but all had already been setup correctly, I found this was the problem for me.
It does seem you would have to use a MessageBodyReader
here. Here's an example, using jdom:
import org.jdom.Document;
import javax.ws.rs.ext.MessageBodyReader;
import javax.ws.rs.ext.Provider;
import javax.ws.rs.ext.MediaType;
import javax.ws.rs.ext.MultivaluedMap;
import java.lang.reflect.Type;
import java.lang.annotation.Annotation;
import java.io.InputStream;
@Provider // this annotation is necessary!
@ConsumeMime("application/xml") // this is a hint to the system to only consume xml mime types
public class XMLMessageBodyReader implements MessageBodyReader<Document> {
private SAXBuilder builder = new SAXBuilder();
public boolean isReadable(Class type, Type genericType, Annotation[] annotations, MediaType mediaType) {
// check if we're requesting a jdom Document
return Document.class.isAssignableFrom(type);
}
public Document readFrom(Class type, Type genericType, Annotation[] annotations, MediaType mediaType, MultivaluedMap<String, String> httpHeaders, InputStream entityStream) {
try {
return builder.build(entityStream);
}
catch (Exception e) {
// handle error somehow
}
}
}
Add this class to the list of resources your jersey deployment will process (usually configured via web.xml, I think). You can then use this reader in one of your regular resource classes like this:
@Path("/somepath") @POST
public void handleXMLData(Document doc) {
// do something with the document
}
I haven't verified that this works exactly as typed, but that's the gist of it. More reading here:
Make sure you have granted permission for both Sender and Receiver to send email and receive email from Unknown sources(External Sources) in Email Account.
import smtplib
#Ports 465 and 587 are intended for email client to email server communication - sending email
server = smtplib.SMTP('smtp.gmail.com', 587)
#starttls() is a way to take an existing insecure connection and upgrade it to a secure connection using SSL/TLS.
server.starttls()
#Next, log in to the server
server.login("#email", "#password")
msg = "Hello! This Message was sent by the help of Python"
#Send the mail
server.sendmail("#Sender", "#Reciever", msg)
I can't comment, so I will put this as a separate answer. I found a few issues with the accepted one-liner answer:
Here is a simplified version that removes the passphrase, ups the security to suppress warnings and includes a suggestion in comments to pass in -subj to remove the full question list:
openssl genrsa -out server.key 2048
openssl rsa -in server.key -out server.key
openssl req -sha256 -new -key server.key -out server.csr -subj '/CN=localhost'
openssl x509 -req -sha256 -days 365 -in server.csr -signkey server.key -out server.crt
Replace 'localhost' with whatever domain you require. You will need to run the first two commands one by one as OpenSSL will prompt for a passphrase.
To combine the two into a .pem file:
cat server.crt server.key > cert.pem
Is using System.Threading.Timer
mandatory?
If not, System.Timers.Timer
has handy Start()
and Stop()
methods (and an AutoReset
property you can set to false, so that the Stop()
is not needed and you simply call Start()
after executing).
Okay, looks like big solutions.
Why not to add width: 100%;
directly in your iframe. ;)
So your code would looks something like <iframe style="width: 100%;" ...></iframe>
Try this it'll work as it worked in my case.
Enjoy! :)
in my case: i got a new pc and I had to download and install a brand new eclipse. by default the proxy was set to native. I was getting that error at first. I then changed it to active. And still it didn't work. And then i put it back to "native" and it worked.
Store the return of setInterval
in a variable, and use it later to clear the interval.
var timer = null;
$("textarea").blur(function(){
timer = window.setInterval(function(){ ... whatever ... }, 2000);
}).focus(function(){
if(timer){
window.clearInterval(timer);
timer = null
}
});
private AudioManager audio;
Inside onCreate:
audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
Override onKeyDown:
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
switch (keyCode) {
case KeyEvent.KEYCODE_VOLUME_UP:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_RAISE, AudioManager.FLAG_SHOW_UI);
return true;
case KeyEvent.KEYCODE_VOLUME_DOWN:
audio.adjustStreamVolume(AudioManager.STREAM_MUSIC,
AudioManager.ADJUST_LOWER, AudioManager.FLAG_SHOW_UI);
return true;
default:
return false;
}
}
x = [i for i in x if len(i)==2]
For general purposes of copying any text to the clipboard, I wrote the following function:
function textToClipboard (text) {
var dummy = document.createElement("textarea");
document.body.appendChild(dummy);
dummy.value = text;
dummy.select();
document.execCommand("copy");
document.body.removeChild(dummy);
}
The value of the parameter is inserted into value of a newly created <textarea>
, which is then selected, its value is copied to the clipboard and then it gets removed from the document.
Here's how I do it using a DataTable. This is a working piece of TEST code.
using (SqlConnection con = new SqlConnection(connStr))
{
con.Open();
// Create a table with some rows.
DataTable table = MakeTable();
// Get a reference to a single row in the table.
DataRow[] rowArray = table.Select();
using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
{
bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";
try
{
// Write the array of rows to the destination.
bulkCopy.WriteToServer(rowArray);
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
}//using
This might depend on how much you want to engineer the solution - if the array is never going to be that big and you don't care about sorting the list you might want to try something similar to the following:
public string[] RemoveDuplicates(string[] myList) {
System.Collections.ArrayList newList = new System.Collections.ArrayList();
foreach (string str in myList)
if (!newList.Contains(str))
newList.Add(str);
return (string[])newList.ToArray(typeof(string));
}
I tried to use the code above but didn't work. The JSON structure returned by Google is so different and there is a very important miss in the helper function: a call to DataContractJsonSerializer.ReadObject()
that actually deserializes the JSON data into the object.
Here is the code that WORKS in 2011:
using System;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Text;
using System.Collections.Generic;
namespace <YOUR_NAMESPACE>
{
public class JSONHelper
{
public static T Deserialise<T>(string json)
{
T obj = Activator.CreateInstance<T>();
MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(json));
DataContractJsonSerializer serialiser = new DataContractJsonSerializer(obj.GetType());
obj = (T)serialiser.ReadObject(ms);
ms.Close();
return obj;
}
}
public class Result
{
public string GsearchResultClass { get; set; }
public string unescapedUrl { get; set; }
public string url { get; set; }
public string visibleUrl { get; set; }
public string cacheUrl { get; set; }
public string title { get; set; }
public string titleNoFormatting { get; set; }
public string content { get; set; }
}
public class Page
{
public string start { get; set; }
public int label { get; set; }
}
public class Cursor
{
public string resultCount { get; set; }
public Page[] pages { get; set; }
public string estimatedResultCount { get; set; }
public int currentPageIndex { get; set; }
public string moreResultsUrl { get; set; }
public string searchResultTime { get; set; }
}
public class ResponseData
{
public Result[] results { get; set; }
public Cursor cursor { get; set; }
}
public class GoogleSearchResults
{
public ResponseData responseData { get; set; }
public object responseDetails { get; set; }
public int responseStatus { get; set; }
}
}
To get the content of the first result, do:
GoogleSearchResults googleResults = new GoogleSearchResults();
googleResults = JSONHelper.Deserialise<GoogleSearchResults>(jsonData);
string contentOfFirstResult = googleResults.responseData.results[0].content;
If you're still stuck on PowerShell v1.0 or v2.0, here is my variation on Jason Stangroome's excellent answer.
Create a powershell4.cmd
somewhere on your path with the following contents:
@echo off
:: http://stackoverflow.com/questions/7308586/using-batch-echo-with-special-characters
if exist %~dp0powershell.exe.activation_config goto :run
echo.^<?xml version="1.0" encoding="utf-8" ?^> > %~dp0powershell.exe.activation_config
echo.^<configuration^> >> %~dp0powershell.exe.activation_config
echo. ^<startup useLegacyV2RuntimeActivationPolicy="true"^> >> %~dp0powershell.exe.activation_config
echo. ^<supportedRuntime version="v4.0"/^> >> %~dp0powershell.exe.activation_config
echo. ^</startup^> >> %~dp0powershell.exe.activation_config
echo.^</configuration^> >> %~dp0powershell.exe.activation_config
:run
:: point COMPLUS_ApplicationMigrationRuntimeActivationConfigPath to the directory that this cmd file lives in
:: and the directory contains a powershell.exe.activation_config file which matches the executable name powershell.exe
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=%~dp0
%SystemRoot%\System32\WindowsPowerShell\v1.0\powershell.exe %*
set COMPLUS_ApplicationMigrationRuntimeActivationConfigPath=
This will allow you to launch an instance of the powershell console running under .NET 4.0.
You can see the difference on my system where I have PowerShell 2.0 by examining the output of the following two commands run from cmd.
C:\>powershell -ExecutionPolicy ByPass -Command $PSVersionTable
Name Value
---- -----
CLRVersion 2.0.50727.5485
BuildVersion 6.1.7601.17514
PSVersion 2.0
WSManStackVersion 2.0
PSCompatibleVersions {1.0, 2.0}
SerializationVersion 1.1.0.1
PSRemotingProtocolVersion 2.1
C:\>powershell4.cmd -ExecutionPolicy ByPass -Command $PSVersionTable
Name Value
---- -----
PSVersion 2.0
PSCompatibleVersions {1.0, 2.0}
BuildVersion 6.1.7601.17514
CLRVersion 4.0.30319.18408
WSManStackVersion 2.0
PSRemotingProtocolVersion 2.1
SerializationVersion 1.1.0.1
Install Cygwin, which includes Bash among many other GNU and Unix utilities (without whom its unlikely that bash will be very useful anyway).
Another option is MinGW's MSYS which includes bash and a smaller set of the more important utilities such as awk. Personally I would have preferred Cygwin because it includes such heavy lifting tools as Perl and Python which I find I cannot live without, while MSYS skimps on these and assumes you are going to install them yourself.
Updated: If anyone is interested in this answer and is running MS-Windows 10, please note that MS-Windows 10 has a "Windows Subsystem For Linux" feature which - once enabled - allows you to install a user-mode image of Ubuntu and then run Bash on that. This provides 100% compatibility with Ubuntu for debugging and running Bash scripts, but this setup is completely standalone from Windows and you cannot use Bash scripts to interact with Windows features (such as processes and APIs) except for limited access to files through the DrvFS feature.
Do not make the situation complex. Use ID
if they are available.
driver.get("http://www.rediff.com");
WebElement sign = driver.findElement(By.linkText("Sign in"));
sign.click();
WebElement email_id= driver.findElement(By.id("c_uname"));
email_id.sendKeys("hi");
If you are trying to debug your virtual host configuration, you may find the Apache -S command line switch useful. That is, type the following command:
httpd -S
This command will dump out a description of how Apache parsed the configuration file. Careful examination of the IP addresses and server names may help uncover configuration mistakes. (See the docs for the httpd program for other command line options).
I am on mingw bash, so I have created ~.profile file with following: alias atom='~/AppData/Local/atom/bin/atom'
Value validation wouldn't be a responsibility of jQuery. You can use pure JavaScript for this. Two ways that come to my mind are:
/^\d+$/.match(value)
Number(value) == value
It should also be mentioned that the "pk" should be a key field. The self-join
SELECT t1.* FROM db.table t1
JOIN db.table t2 ON t1.someField = t2.someField AND t1.pk != t2.pk
by Bill Karwin give you all the records that are duplicates which is what I wanted. Because some have more than two, you can get the same record more than once. I wrote all to another table with the same fields to get rid of the same records by key fields suppression. I tried
SELECT * FROM db.table HAVING COUNT(someField) > 1
above first. The data returned from it give only one of the duplicates, less than 1/2 of what this gives you but the count is good if that is all you want.
The problem is that /var/www
doesn't exist either, and mkdir
isn't recursive by default -- it expects the immediate parent directory to exist.
Use:
mkdir -p /var/www/app
...or install a package that creates a /var/www
prior to reaching this point in your Dockerfile.
If you're on a Mac with Homebrew, use
brew info mysql
You'll see something like
$ brew info mysql
mysql: stable 5.6.13 (bottled)
http://dev.mysql.com/doc/refman/5.6/en/
Conflicts with: mariadb, mysql-cluster, percona-server
/usr/local/Cellar/mysql/5.6.13 (9381 files, 354M) *
That last line is the INSTALLERDIR
per the MySQL docs
I think it's just __file__
Sounds like you may also want to checkout the inspect module.
From: http://www.delorie.com/djgpp/v2faq/faq8_20.html
gcc -c -g -Wa,-a,-ad [other GCC options] foo.c > foo.lst
in alternative to PhirePhly's answer Or just use -S as everyone said.
Since strings are lists of characters in Python, we can concatenate strings the same way we concatenate lists (with the + sign):
{{ var1 + '-' + var2 + '-' + var3 }}
If you want to pipe the resulting string to some filter, make sure you enclose the bits in parentheses:
e.g. To concatenate our 3 vars, and get a sha512 hash:
{{ (var1 + var2 + var3) | hash('sha512') }}
Note: this works on Ansible 2.3. I haven't tested it on earlier versions.
For users working with the Genesis framework.
Add the following to your child theme functions.php
add_action( 'genesis_before', 'script_urls' );
function script_urls() {
?>
<script type="text/javascript">
var stylesheetDir = '<?= get_bloginfo("stylesheet_directory"); ?>';
</script>
<?php
}
And use that variable to set the relative url in your script. For example:
Reset.style.background = " url('"+stylesheetDir+"/images/searchfield_clear.png') ";
from collections import Counter
x = array( [1,1,1,2,2,2,5,25,1,1] )
mode = counter.most_common(1)[0][0]
Given a String str:
str = str.replaceAll("\\\\r","")
str = str.replaceAll("\\\\n","")
They're all similar in that they're essentially zip files containing the actual file components. You can see the contents just by replacing the extension with .zip and opening them up. The difference with xlsb seems to be that the components are not XML-based but are in a binary format: supposedly this is beneficial when working with large files.
https://blogs.msdn.microsoft.com/dmahugh/2006/08/22/new-binary-file-format-for-spreadsheets/
If you try appending the number like, say
listName.append(4)
, this will append 4
at last.
But if you are trying to take <int>
and then append it as, num = 4
followed by listName.append(num)
, this will give you an error as 'num' is of <int> type
and listName is of type <list>
. So do type cast int(num)
before appending it.
Run the following command from your terminal:
sudo apt-get purge ruby
Usually works well for me.
This solves the issue when you scroll past the beginning or end of the div
var selScrollable = '.scrollable';
// Uses document because document will be topmost level in bubbling
$(document).on('touchmove',function(e){
e.preventDefault();
});
// Uses body because jQuery on events are called off of the element they are
// added to, so bubbling would not work if we used document instead.
$('body').on('touchstart', selScrollable, function(e) {
if (e.currentTarget.scrollTop === 0) {
e.currentTarget.scrollTop = 1;
} else if (e.currentTarget.scrollHeight === e.currentTarget.scrollTop + e.currentTarget.offsetHeight) {
e.currentTarget.scrollTop -= 1;
}
});
// Stops preventDefault from being called on document if it sees a scrollable div
$('body').on('touchmove', selScrollable, function(e) {
e.stopPropagation();
});
Note that this won't work if you want to block whole page scrolling when a div does not have overflow. To block that, use the following event handler instead of the one immediately above (adapted from this question):
$('body').on('touchmove', selScrollable, function(e) {
// Only block default if internal div contents are large enough to scroll
// Warning: scrollHeight support is not universal. (https://stackoverflow.com/a/15033226/40352)
if($(this)[0].scrollHeight > $(this).innerHeight()) {
e.stopPropagation();
}
});
<style type="text/css">
>> .imgTop {
>> display: block;
>> text-align: right;
>> }
>> </style>
<img class="imgTop" src="imgName.gif" alt="image description" height="100" width="100">
git log --cherry-mark --oneline from_branch...to_branch
(3dots) but sometimes it shows '+' instead of '='
An example might have been useful, but if I understood you correctly, this would work:
echo "Hello: world" | cut -f1 -d":"
This will convert Hello: world
into Hello
.
class Hash
def compact
def _empty?(val)
case val
when Hash then val.compact.empty?
when Array then val.all? { |v| _empty?(v) }
when String then val.empty?
when NilClass then true
# ... custom checking
end
end
delete_if { |_key, val| _empty?(val) }
end
end
See the last example on page https://developer.mozilla.org/en/Core_JavaScript_1.5_Reference:Global_Objects:Date:
/* Use a function for the exact format desired... */
function ISODateString(d) {
function pad(n) {return n<10 ? '0'+n : n}
return d.getUTCFullYear()+'-'
+ pad(d.getUTCMonth()+1)+'-'
+ pad(d.getUTCDate())+'T'
+ pad(d.getUTCHours())+':'
+ pad(d.getUTCMinutes())+':'
+ pad(d.getUTCSeconds())+'Z'
}
var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z
Use JSON classes for parsing e.g
JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");
JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....
You need to include iostream
#include <iostream>
using namespace std;
I stumbled upon this error while updating my Android studio to 3.0.1 from 2.3. After trying all the solutions above, i found that the issue was with the Build tools version. I was using an unsupported version of build tools. I changed mine as below and it worked.
buildToolsVersion '26.0.2'
As a rule of thumb always try to use the latest version of Build tools supported by your Gradle version. From version 3.0.0 of Gradle, you don't need to specify the build tools version as this is picked up automatically.
3.0.0 (October 2017) : Android plugin for Gradle 3.0.0
With this update, you no longer need to specify a version for the build tools—the plugin uses the minimum required version by default. So, you can now remove the android.buildToolsVersion property.
https://developer.android.com/studio/releases/gradle-plugin.html#3-0-0
By using this on bootstrap 3:
#carousel-example-generic{
margin:auto;
}
I know this is quite an old post, but I would like to point out the following for people who will read it in the future: As per MS:
Do not use the IISReset.exe tool to restart the IIS services. Instead, use the NET STOP and NET START commands. For example, to stop and start the World Wide Web Publishing Service, run the following commands:
- NET STOP iisadmin /y
- NET START w3svc
There are two benefits to using the NET STOP/NET START commands to restart the IIS Services as opposed to using the IISReset.exe tool. First, it is possible for IIS configuration changes that are in the process of being saved when the IISReset.exe command is run to be lost. Second, using IISReset.exe can make it difficult to identify which dependent service or services failed to stop when this problem occurs. Using the NET STOP commands to stop each individual dependent service will allow you to identify which service fails to stop, so you can then troubleshoot its failure accordingly.
The short answer: seems like a totally reasonable approach to the asynchrony problem to me. With a couple caveats.
I had a very similar line of thought when working on a new project we just started at my job. I was a big fan of vanilla Redux's elegant system for updating the store and rerendering components in a way that stays out of the guts of a React component tree. It seemed weird to me to hook into that elegant dispatch
mechanism to handle asynchrony.
I ended up going with a really similar approach to what you have there in a library I factored out of our project, which we called react-redux-controller.
I ended up not going with the exact approach you have above for a couple reasons:
dispatch
itself via lexical scope. This limits the options for refactoring once that connect
statement gets out of hand -- and it's looking pretty unwieldy with just that one update
method. So you need some system for letting you compose those dispatcher functions if you break them up into separate modules.Take together, you have to rig up some system to allow dispatch
and the store to be injected into your dispatching functions, along with the parameters of the event. I know of three reasonable approaches to this dependency injection:
dispatch
middleware approaches, but I assume they're basically the same.connect
, rather than having to work directly with the raw, normalized store.this
context, through a variety of possible mechanisms.Update
It occurs to me that part of this conundrum is a limitation of react-redux. The first argument to connect
gets a state snapshot, but not dispatch. The second argument gets dispatch but not the state. Neither argument gets a thunk that closes over the current state, for being able to see updated state at the time of a continuation/callback.
BigInteger.valueOf(1695609641).toByteArray()
http://msdn.microsoft.com/en-us/library/system.io.directory.getfiles.aspx
The System.IO namespace has loads of methods to help you with file operations. The
Directory.GetFiles()
method returns an array of strings which represent the files in the target directory.
Just found your question whilst trying to solve another problem I'm having, you will find that currently Google isn't able to perform a temporary download so therefore you have to download instead.
See: http://productforums.google.com/forum/#!topic/chrome/Drge_Zrwg-c
I would consider using java.util.concurrent.PriorityBlockingQueue, with priority determined by a "numberOfUses" counter in each element. I would be very, very careful to get all my synchronisation correct, as the "numberOfUses" counter implies that the element can't be immutable.
The element object would be a wrapper for the objects in the cache:
class CacheElement {
private final Object obj;
private int numberOfUsers = 0;
CacheElement(Object obj) {
this.obj = obj;
}
... etc.
}
Forgive the flippancy, but if you are doing REST over HTTP then RFC7231 describes exactly what behaviour is expected from GET, PUT, POST and DELETE.
Update (Jul 3 '14):
The HTTP spec intentionally does not define what is returned from POST or DELETE. The spec only defines what needs to be defined. The rest is left up to the implementer to choose.
You can define the drawables that are used for the background, and the switcher part like this:
<Switch
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:thumb="@drawable/switch_thumb"
android:track="@drawable/switch_bg" />
Now you need to create a selector that defines the different states for the switcher drawable. Here the copies from the Android sources:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_thumb_disabled_holo_light" />
<item android:state_pressed="true" android:drawable="@drawable/switch_thumb_pressed_holo_light" />
<item android:state_checked="true" android:drawable="@drawable/switch_thumb_activated_holo_light" />
<item android:drawable="@drawable/switch_thumb_holo_light" />
</selector>
This defines the thumb drawable, the image that is moved over the background. There are four ninepatch images used for the slider:
The deactivated version (xhdpi version that Android is using)
The pressed slider:
The activated slider (on state):
The default version (off state):
There are also three different states for the background that are defined in the following selector:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_enabled="false" android:drawable="@drawable/switch_bg_disabled_holo_dark" />
<item android:state_focused="true" android:drawable="@drawable/switch_bg_focused_holo_dark" />
<item android:drawable="@drawable/switch_bg_holo_dark" />
</selector>
The deactivated version:
The focused version:
And the default version:
To have a styled switch just create this two selectors, set them to your Switch View and then change the seven images to your desired style.
Goodrich and Tamassia computed from over 50,000 English words (formed as the union of the word lists provided in two variants of Unix) that using the constants 31, 33, 37, 39, and 41 will produce fewer than 7 collisions in each case. This may be the reason that so many Java implementations choose such constants.
See section 9.2 Hash Tables (page 522) of Data Structures and Algorithms in Java.
How about
SELECT EmailAddress, CustomerName FROM Customers a
WHERE Exists ( SELECT emailAddress FROM customers c WHERE a.customerName != c.customerName AND a.EmailAddress = c.EmailAddress)
Hit the F1 button, then type "Toggle Render Whitespace" or the parts of it you can remember :)
I use vscode version 1.22.2 so this could be a feature that did not exist back in 2015.
Okay so you are trying to get a bitmap from a file? Title says URL. Anyways, when you are getting files from external storage in Android you should never use a direct path. Instead call getExternalStorageDirectory() like so:
File bitmapFile = new File(Environment.getExternalStorageDirectory() + "/" + PATH_TO_IMAGE);
Bitmap bitmap = BitmapFactory.decodeFile(bitmapFile);
getExternalStorageDirectory() gives you the path to the SD card. Also you need to declare the WRITE_EXTERNAL_STORAGE permission in the Manifest.
The main answer is to use File objects. However Commons IO does have a class FilenameUtils that can do this kind of thing, such as the concat() method.
dancavallaro has it right, %*
for all command line parameters (excluding the script name itself). You might also find these useful:
%0
- the command used to call the batch file (could be foo
, ..\foo
, c:\bats\foo.bat
, etc.)
%1
is the first command line parameter,
%2
is the second command line parameter,
and so on till %9
(and SHIFT
can be used for those after the 9th).
%~nx0
- the actual name of the batch file, regardless of calling method (some-batch.bat)
%~dp0
- drive and path to the script (d:\scripts)
%~dpnx0
- is the fully qualified path name of the script (d:\scripts\some-batch.bat)
More info examples at https://www.ss64.com/nt/syntax-args.html and https://www.robvanderwoude.com/parameters.html
Use innerText
/textContent
:
var el = document.getElementById('*spaM4');
console.log(el.innerText || el.textContent);
Fiddle: http://jsfiddle.net/NeTgC/2/
Easy:
$imagedata = file_get_contents("/path/to/image.jpg");
// alternatively specify an URL, if PHP settings allow
$base64 = base64_encode($imagedata);
bear in mind that this will enlarge the data by 33%, and you'll have problems with files whose size exceed your memory_limit
.
URL url = new URL("http://image10.bizrate-images.com/resize?sq=60&uid=2216744464");
Bitmap bmp = BitmapFactory.decodeStream(url.openConnection().getInputStream());
imageView.setImageBitmap(bmp);
Here is something I did which open Facebook App with Link
shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setComponent(new ComponentName("com.facebook.katana",
"com.facebook.katana.activity.composer.ImplicitShareIntentHandler"));
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, videoUrl);
You cannot directly use a SQL statement in a PL/SQL expression:
SQL> begin
2 if (select count(*) from dual) >= 1 then
3 null;
4 end if;
5 end;
6 /
if (select count(*) from dual) >= 1 then
*
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...
You must use a variable instead:
SQL> set serveroutput on
SQL>
SQL> declare
2 v_count number;
3 begin
4 select count(*) into v_count from dual;
5
6 if v_count >= 1 then
7 dbms_output.put_line('Pass');
8 end if;
9 end;
10 /
Pass
PL/SQL procedure successfully completed.
Of course, you may be able to do the whole thing in SQL:
update my_table
set x = y
where (select count(*) from other_table) >= 1;
It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF
statement; you won't see a SELECT
statement in any of the branches.
There are already useful answers to this question above, however there is one more possibility which I don't see being addressed here.
We should consider that the java is installed correctly (that's why eclipse could have been launched in the first place), and the JDK is also added correctly to the eclipse. So the issue might be for some reason (e.g. migration of eclipse to another OS) the path for javadoc is not right which you can easily check and modify in the javadoc wizard page. Here is detailed instructions:
Project->Generate Javadoc...
javadoc command
path is correct as illustrated in below screenshot:Nowadays the most common thing is to see retina-screen devices, in other words: devices with high resolutions and a very high pixel density (but usually smaller than 6 inches physical size). That's why you will need retina display specialized media-queries on your CSS. This is the most complete example I could find:
@media only screen and (min-width: 320px) {
/* Small screen, non-retina */
}
@media
only screen and (-webkit-min-device-pixel-ratio: 2) and (min-width: 320px),
only screen and ( min--moz-device-pixel-ratio: 2) and (min-width: 320px),
only screen and ( -o-min-device-pixel-ratio: 2/1) and (min-width: 320px),
only screen and ( min-device-pixel-ratio: 2) and (min-width: 320px),
only screen and ( min-resolution: 192dpi) and (min-width: 320px),
only screen and ( min-resolution: 2dppx) and (min-width: 320px) {
/* Small screen, retina, stuff to override above media query */
}
@media only screen and (min-width: 700px) {
/* Medium screen, non-retina */
}
@media
only screen and (-webkit-min-device-pixel-ratio: 2) and (min-width: 700px),
only screen and ( min--moz-device-pixel-ratio: 2) and (min-width: 700px),
only screen and ( -o-min-device-pixel-ratio: 2/1) and (min-width: 700px),
only screen and ( min-device-pixel-ratio: 2) and (min-width: 700px),
only screen and ( min-resolution: 192dpi) and (min-width: 700px),
only screen and ( min-resolution: 2dppx) and (min-width: 700px) {
/* Medium screen, retina, stuff to override above media query */
}
@media only screen and (min-width: 1300px) {
/* Large screen, non-retina */
}
@media
only screen and (-webkit-min-device-pixel-ratio: 2) and (min-width: 1300px),
only screen and ( min--moz-device-pixel-ratio: 2) and (min-width: 1300px),
only screen and ( -o-min-device-pixel-ratio: 2/1) and (min-width: 1300px),
only screen and ( min-device-pixel-ratio: 2) and (min-width: 1300px),
only screen and ( min-resolution: 192dpi) and (min-width: 1300px),
only screen and ( min-resolution: 2dppx) and (min-width: 1300px) {
/* Large screen, retina, stuff to override above media query */
}
Source: CSS-Tricks Website
You can try Marvin Framework. It provides an interface to work with cameras. Moreover, it also provides a set of real-time video processing features, like object tracking and filtering.
Take a look!
Real-time Video Processing Demo:
http://www.youtube.com/watch?v=D5mBt0kRYvk
You can use the source below. Just save a frame using MarvinImageIO.saveImage() every 5 second.
Webcam video demo:
public class SimpleVideoTest extends JFrame implements Runnable{
private MarvinVideoInterface videoAdapter;
private MarvinImage image;
private MarvinImagePanel videoPanel;
public SimpleVideoTest(){
super("Simple Video Test");
videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
videoPanel = new MarvinImagePanel();
add(videoPanel);
new Thread(this).start();
setSize(800,600);
setVisible(true);
}
@Override
public void run() {
while(true){
// Request a video frame and set into the VideoPanel
image = videoAdapter.getFrame();
videoPanel.setImage(image);
}
}
public static void main(String[] args) {
SimpleVideoTest t = new SimpleVideoTest();
t.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
For those who just want to take a single picture:
WebcamPicture.java
public class WebcamPicture {
public static void main(String[] args) {
try{
MarvinVideoInterface videoAdapter = new MarvinJavaCVAdapter();
videoAdapter.connect(0);
MarvinImage image = videoAdapter.getFrame();
MarvinImageIO.saveImage(image, "./res/webcam_picture.jpg");
} catch(MarvinVideoInterfaceException e){
e.printStackTrace();
}
}
}
For updating a record:
UPDATE Employees SET [Photo] = (SELECT
MyImage.* from Openrowset(Bulk
'C:\photo.bmp', Single_Blob) MyImage)
where Id = 10
Notes:
Here, I summarize a few ways which may return different results to your question, so be careful:
# First assign your "id"s to an R object.
# Here's a hypothetical example:
id <- c("a","b","b","c","c","c","d","d","d","d")
#To return ALL MINUS ONE duplicated values:
id[duplicated(id)]
## [1] "b" "c" "c" "d" "d" "d"
#To return ALL duplicated values by specifying fromLast argument:
id[duplicated(id) | duplicated(id, fromLast=TRUE)]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
#Yet another way to return ALL duplicated values, using %in% operator:
id[ id %in% id[duplicated(id)] ]
## [1] "b" "b" "c" "c" "c" "d" "d" "d" "d"
Hope these help. Good luck.
Simply instantiate an anonymous function:
var foo = new function () {
this.a = 5;
this.b = 6;
this.c = this.a + this.b;
};
I normally run sites on Linux, but I also develop on a local Windows machine. I've run into this problem many times and just fixed the tables when I encountered the problems. I installed an app yesterday to help someone out and of course ran into the problem again. So, I decided it was time to figure out what was going on - and found this thread. I really don't like the idea of changing the sql_mode of the server to an earlier mode (by default), so I came up with a simple (me thinks) solution.
This solution would of course require developers to wrap their table creation scripts to compensate for the MySQL issue running on Windows. You'll see similar concepts in dump files. One BIG caveat is that this could/will cause problems if partitioning is used.
// Store the current sql_mode
mysql_query("set @orig_mode = @@global.sql_mode");
// Set sql_mode to one that won't trigger errors...
mysql_query('set @@global.sql_mode = "MYSQL40"');
/**
* Do table creations here...
*/
// Change it back to original sql_mode
mysql_query('set @@global.sql_mode = @orig_mode');
That's about it.
This is because you're using getActivity()
inside an inner class. Try using:
SherlockFragmentActivity.this.getActivity()
instead, though there's really no need for the getActivity()
part. In your case,
SherlockFragmentActivity .this
should suffice.
SELECT *
FROM people
WHERE names ='SMITH'
ORDER BY names asc
limit 10
If you need add group by clause. If you search Smith you would have to sort on something else.
<div id="scroll">
<p>Try to add more text</p>
</div>
here's the css code
#scroll {
overflow-y:auto;
height:auto;
max-height:200px;
border:1px solid black;
width:300px;
}
here's the demo JSFIDDLE
Sounds like a homework problem. scanf() is the wrong function to use for the problem. I'd recommend getchar() or getch().
Note: I'm purposefully not solving the problem since this seems like homework, instead just pointing you in the right direction.
There is a generic solution (for any type). Usability is good, but implementation should be improved: http://cleansharp.de/wordpress/2011/05/generischer-typeconverter/
This allows you to write very clean code like this:
string value = null;
int? x = value.ConvertOrDefault<int?>();
and also:
object obj = 1;
string value = null;
int x = 5;
if (value.TryConvert(out x))
Console.WriteLine("TryConvert example: " + x);
bool boolean = "false".ConvertOrDefault<bool>();
bool? nullableBoolean = "".ConvertOrDefault<bool?>();
int integer = obj.ConvertOrDefault<int>();
int negativeInteger = "-12123".ConvertOrDefault<int>();
int? nullableInteger = value.ConvertOrDefault<int?>();
MyEnum enumValue = "SecondValue".ConvertOrDefault<MyEnum>();
MyObjectBase myObject = new MyObjectClassA();
MyObjectClassA myObjectClassA = myObject.ConvertOrDefault<MyObjectClassA>();
Similar problem: Find <button>Advanced...</button>
Maybe this will give you some ideas (please transfer the concept from Java to Python):
wait.until(ExpectedConditions.elementToBeClickable(//
driver.findElements(By.tagName("button")).stream().filter(i -> i.getText().equals("Advanced...")).findFirst().get())).click();
async function (request, response, next) {
const url = request.rawHeaders[9] + request.originalUrl;
//or
const url = request.headers.host + request.originalUrl;
}
When methods or functions take a format string argument, you should make sure that you have control over the content of the format string.
For example, when logging strings, it is tempting to pass the string variable as the sole argument to NSLog
:
NSString *aString = // get a string from somewhere;
NSLog(aString);
The problem with this is that the string may contain characters that are interpreted as format strings. This can lead to erroneous output, crashes, and security problems. Instead, you should substitute the string variable into a format string:
NSLog(@"%@", aString);
Try this script to create a temporary table TESTTEST and watch the order of precedence as the triggers are called in this order: 1) INSTEAD OF, 2) FOR, 3) AFTER
All of the logic is placed in INSTEAD OF trigger and I have 2 examples of how you might code some scenarios...
Good luck...
CREATE TABLE TESTTEST
(
ID INT,
Modified0 DATETIME,
Modified1 DATETIME
)
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_0] ON [dbo].TESTTEST
INSTEAD OF INSERT,UPDATE,DELETE
AS
BEGIN
SELECT 'INSTEAD OF'
SELECT 'TT0.0'
SELECT * FROM TESTTEST
SELECT *, 'I' Mode
INTO #work
FROM INSERTED
UPDATE #work SET Mode='U' WHERE ID IN (SELECT ID FROM DELETED)
INSERT INTO #work (ID, Modified0, Modified1, Mode)
SELECT ID, Modified0, Modified1, 'D'
FROM DELETED WHERE ID NOT IN (SELECT ID FROM INSERTED)
--Check Security or any other logic to add and remove from #work before processing
DELETE FROM #work WHERE ID=9 -- because you don't want anyone to edit this id?!?!
DELETE FROM #work WHERE Mode='D' -- because you don't want anyone to delete any records
SELECT 'EV'
SELECT * FROM #work
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='I'))
BEGIN
SELECT 'I0.0'
INSERT INTO dbo.TESTTEST (ID, Modified0, Modified1)
SELECT ID, Modified0, Modified1
FROM #work
WHERE Mode='I'
SELECT 'Cool stuff would happen here if you had FOR INSERT or AFTER INSERT triggers.'
SELECT 'I0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='D'))
BEGIN
SELECT 'D0.0'
DELETE FROM TESTTEST WHERE ID IN (SELECT ID FROM #work WHERE Mode='D')
SELECT 'Cool stuff would happen here if you had FOR DELETE or AFTER DELETE triggers.'
SELECT 'D0.1'
END
IF(EXISTS(SELECT TOP 1 * FROM #work WHERE Mode='U'))
BEGIN
SELECT 'U0.0'
UPDATE t SET t.Modified0=e.Modified0, t.Modified1=e.Modified1
FROM dbo.TESTTEST t
INNER JOIN #work e ON e.ID = t.ID
WHERE e.Mode='U'
SELECT 'U0.1'
END
DROP TABLE #work
SELECT 'TT0.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_1] ON [dbo].TESTTEST
FOR UPDATE
AS
BEGIN
SELECT 'FOR UPDATE'
SELECT 'TT1.0'
SELECT * FROM TESTTEST
SELECT 'I1'
SELECT * FROM INSERTED
SELECT 'D1'
SELECT * FROM DELETED
SELECT 'TT1.1'
SELECT * FROM TESTTEST
END
GO
CREATE TRIGGER [dbo].[tr_TESTTEST_2] ON [dbo].TESTTEST
AFTER UPDATE
AS
BEGIN
SELECT 'AFTER UPDATE'
SELECT 'TT2.0'
SELECT * FROM TESTTEST
SELECT 'I2'
SELECT * FROM INSERTED
SELECT 'D2'
SELECT * FROM DELETED
SELECT 'TT2.1'
SELECT * FROM TESTTEST
END
GO
SELECT 'Start'
INSERT INTO TESTTEST (ID, Modified0) VALUES (9, GETDATE())-- not going to insert
SELECT 'RESTART'
INSERT INTO TESTTEST (ID, Modified0) VALUES (10, GETDATE())--going to insert
SELECT 'RESTART'
UPDATE TESTTEST SET Modified1=GETDATE() WHERE ID=10-- gointo to update
SELECT 'RESTART'
DELETE FROM TESTTEST WHERE ID=10-- not going to DELETE
SELECT 'FINISHED'
SELECT * FROM TESTTEST
DROP TABLE TESTTEST
Simply
==
means comparison between operands with type conversion
&
===
means comparison between operands without type conversion
Type conversion in javaScript means javaScript automatically convert any other data types to string data types.
For example:
123=='123' //will return true, because JS convert integer 123 to string '123'
//as we used '==' operator
123==='123' //will return false, because JS do not convert integer 123 to string
//'123' as we used '===' operator
You can disable DHE completely in your jdk, edit jre/lib/security/java.security and make sure DHE is disabled, eg. like
jdk.tls.disabledAlgorithms=SSLv3, DHE
.
PERMISSIONS: I want to stress the importance of permissions for "sqlplus".
For any "Other" UNIX user other than the Owner/Group to be able to run sqlplus and access an ORACLE database , read/execute permissions are required (rx) for these 4 directories :
$ORACLE_HOME/bin , $ORACLE_HOME/lib, $ORACLE_HOME/oracore, $ORACLE_HOME/sqlplus
Environment. Set those properly:
A. ORACLE_HOME
(example: ORACLE_HOME=/u01/app/oranpgm/product/12.1.0/PRMNRDEV/
)
B. LD_LIBRARY_PATH
(example: ORACLE_HOME=/u01/app/oranpgm/product/12.1.0/PRMNRDEV/lib
)
C. ORACLE_SID
D. PATH
export PATH="$ORACLE_HOME/bin:$PATH"
In Sql Server "Ad Hoc Query" is also used for Ad Hoc Distributed Queries. These are ad hoc queries on an other server via OpenRowset or OpenDatasource. Ad Hoc Distributed Queries are only allowed after configuring so. This is a Server configuration option.
The reason your code isn't working the way you would expect is because this line:
<button type="button" value="submit" onClick="document.getElementById("datepicker").click()">submit </button>
should be changed to:
<button type="button" value="submit" onClick="document.getElementById('datepicker').focus()">submit </button>
There are two things to notice here:
1: The "
s around datepicker
have been changed to '
s so that they do not interfere with the quotes surrounding the onclick
event.
2: The click()
has been changed to focus()
to activate the datepicker calendar. When the button is pressed.
Now, this fixes your issue...but I do agree with the other posts that using jQuery to access the DOM element and trigger the event is the better way to go. Since you're already doing this for the jQuery datapicker plugin via <script src="http://code.jquery.com/jquery-1.8.3.js"></script>
, this should not be a problem.
Inline events are not recommended.
You need to reference the cout's namespace std
somehow. For instance, insert
using std::cout;
using std::endl;
on top of your function definition, or the file.
The only thing you have to do is to add in the cshtml file, in the head, the following line:
@Styles.Render("~/Content/Main.css")
The entire head will look somethink like that:
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>HTML Page</title>
@Styles.Render("~/Content/main.css")
</head>
Hope it helps!!
Copying Grid to datatable
if (GridView.Rows.Count != 0)
{
//Forloop for header
for (int i = 0; i < GridView.HeaderRow.Cells.Count; i++)
{
dt.Columns.Add(GridView.HeaderRow.Cells[i].Text);
}
//foreach for datarow
foreach (GridViewRow row in GridView.Rows)
{
DataRow dr = dt.NewRow();
for (int j = 0; j < row.Cells.Count; j++)
{
dr[GridView.HeaderRow.Cells[j].Text] = row.Cells[j].Text;
}
dt.Rows.Add(dr);
}
//Loop for footer
if (GridView.FooterRow.Cells.Count != 0)
{
DataRow dr = dt.NewRow();
for (int i = 0; i < GridView.FooterRow.Cells.Count; i++)
{
//You have to re-do the work if you did anything in databound for footer.
}
dt.Rows.Add(dr);
}
dt.TableName = "tb";
}
I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.
You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.
You can also use the statement debugger;
in your JavaScript code the set a breakpoint.
Here's a Perl script which will edit the files in-place:
perl -i.bak -lpe 's/\s+/,/g' files*
Consecutive whitespace is converted to a single comma.
Each input file is moved to .bak
These command-line options are used:
-i.bak
edit in-place and make .bak copies
-p
loop around every line of the input file, automatically print the line
-l
removes newlines before processing, and adds them back in afterwards
-e
execute the perl code
This Problem is because of Path so you need to build the path using following Steps
Goto project ----->Right Click on Project Name ---->properties ---->click on Than Java Build Path option than ---> click Android 4.2.2---->Ok
If the children have FKs linking them to the parent, then you can use DELETE CASCADE on the parent.
e.g.
CREATE TABLE supplier
( supplier_id numeric(10) not null,
supplier_name varchar2(50) not null,
contact_name varchar2(50),
CONSTRAINT supplier_pk PRIMARY KEY (supplier_id)
);
CREATE TABLE products
( product_id numeric(10) not null,
supplier_id numeric(10) not null,
CONSTRAINT fk_supplier
FOREIGN KEY (supplier_id)
REFERENCES supplier(supplier_id)
ON DELETE CASCADE
);
Delete the supplier, and it will delate all products for that supplier
Implementing Comparable
means "I can compare myself with another object." This is typically useful when there's a single natural default comparison.
Implementing Comparator
means "I can compare two other objects." This is typically useful when there are multiple ways of comparing two instances of a type - e.g. you could compare people by age, name etc.
If you are looking for an alert that dissapears after an interval you could try the jQuery UI Dialog widget.
Params contains the following three groups of parameters:
match '/user/:id'
in routes.rb will set params[:id]params[:controller]
and params[:action]
is always available and contains the current controller and actionAnother solution if you want to keep this column as index.
pd.read_csv('filename.csv', index_col='Unnamed: 0')
Slight modification to what was stated above. My Json format, which validates was
{
mycollection:{[
{
property0:value,
property1:value,
},
{
property0:value,
property1:value,
}
]
}
}
Using AlexDev's response, I did this Looping each child, creating reader from it
public partial class myModel
{
public static List<myModel> FromJson(string json) => JsonConvert.DeserializeObject<myModelList>(json, Converter.Settings).model;
}
public class myModelList {
[JsonConverter(typeof(myModelConverter))]
public List<myModel> model { get; set; }
}
class myModelConverter : JsonConverter
{
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var token = JToken.Load(reader);
var list = Activator.CreateInstance(objectType) as System.Collections.IList;
var itemType = objectType.GenericTypeArguments[0];
foreach (var child in token.Children()) //mod here
{
var newObject = Activator.CreateInstance(itemType);
serializer.Populate(child.CreateReader(), newObject); //mod here
list.Add(newObject);
}
return list;
}
public override bool CanConvert(Type objectType)
{
return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}
Thanks to everyone that posted solutions, I combined multiple approaches to provide some more advanced disabled
functionality. Here is a gist, and the code is below.
This provides for multiple levels of defense so that Anchors marked as disable actually behave as such.
Using this approach, you get an anchor that you cannot:
- click
- tab to and hit return
- tabbing to it will move focus to the next focusable element
- it is aware if the anchor is subsequently enabled
1. Include this css, as it is the first line of defense. This assumes the selector you use is 'a.disabled'
a.disabled {
pointer-events: none;
cursor: default;
}
2. Next, instantiate this class such as (with optional selector):
$ ->
new AnchorDisabler()
Here is the coffescript class:
class AnchorDisabler
constructor: (selector = 'a.disabled') ->
$(selector).click(@onClick).keyup(@onKeyup).focus(@onFocus)
isStillDisabled: (ev) =>
### since disabled can be a class or an attribute, and it can be dynamically removed, always recheck on a watched event ###
target = $(ev.target)
return true if target.hasClass('disabled')
return true if target.attr('disabled') is 'disabled'
return false
onFocus: (ev) =>
### if an attempt is made to focus on a disabled element, just move it along to the next focusable one. ###
return unless @isStillDisabled(ev)
focusables = $(':focusable')
return unless focusables
current = focusables.index(ev.target)
next = (if focusables.eq(current + 1).length then focusables.eq(current + 1) else focusables.eq(0))
next.focus() if next
onClick: (ev) =>
# disabled could be dynamically removed
return unless @isStillDisabled(ev)
ev.preventDefault()
return false
onKeyup: (ev) =>
# 13 is the js key code for Enter, we are only interested in disabling that so get out fast
code = ev.keyCode or ev.which
return unless code is 13
# disabled could be dynamically removed
return unless @isStillDisabled(ev)
ev.preventDefault()
return false
what about this?
$(this).mouseleave(function(){
var thisUI = $(this);
$('html').click(function(){
thisUI.hide();
$('html').unbind('click');
});
});
You can do it like this:
In your main view controller:
func showModal() {
let modalViewController = ModalViewController()
modalViewController.modalPresentationStyle = .overCurrentContext
presentViewController(modalViewController, animated: true, completion: nil)
}
In your modal view controller:
class ModalViewController: UIViewController {
override func viewDidLoad() {
view.backgroundColor = UIColor.clearColor()
view.opaque = false
}
}
If you are working with a storyboard:
Just add a Storyboard Segue with Kind
set to Present Modally
to your modal view controller and on this view controller set the following values:
As Crashalot pointed out in his comment: Make sure the segue only uses Default
for both Presentation
and Transition
. Using Current Context
for Presentation
makes the modal turn black instead of remaining transparent.
I am using this function:
public static int[][] copy(final int[][] array) {
if (array != null) {
final int[][] copy = new int[array.length][];
for (int i = 0; i < array.length; i++) {
final int[] row = array[i];
copy[i] = new int[row.length];
System.arraycopy(row, 0, copy[i], 0, row.length);
}
return copy;
}
return null;
}
The big advantage of this approach is that it can also copy arrays that don't have the same row count such as:
final int[][] array = new int[][] { { 5, 3, 6 }, { 1 } };
I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.
The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).
New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/
(eg /opt/firefox31/
). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.
Courtesy of this page, I found this worked when the suggestions above didn't:
import PIL.Image
from cStringIO import StringIO
import IPython.display
import numpy as np
def showarray(a, fmt='png'):
a = np.uint8(a)
f = StringIO()
PIL.Image.fromarray(a).save(f, fmt)
IPython.display.display(IPython.display.Image(data=f.getvalue()))
Maybe you can use this properties:
ActiveCell.Interior.ColorIndex - one of 56 preset colors
and
ActiveCell.Interior.Color - RGB color, used like that:
ActiveCell.Interior.Color = RGB(255,255,255)
Throwing in another solution.
In my module's init.py I have something like:
# mymodule/__init__.py
import logging
def get_module_logger(mod_name):
logger = logging.getLogger(mod_name)
handler = logging.StreamHandler()
formatter = logging.Formatter(
'%(asctime)s %(name)-12s %(levelname)-8s %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.DEBUG)
return logger
Then in each module I need a logger, I do:
# mymodule/foo.py
from [modname] import get_module_logger
logger = get_module_logger(__name__)
When the logs are missed, you can differentiate their source by the module they came from.
as per docs:
"json"
: Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)"text"
: A plain text string.FYI the available version for raring in Chris Lea's repo is currently 0.8.25
sudo apt-get install nodejs=0.8.25-2chl1~raring1
I believe however if you combine all of your statements and run it in Java 8.1 you will get a different answer, at least that's what my experience says.
The code will work like this:
int a=5,i;
i=++a + ++a + a++; /*a = 5;
i=++a + ++a + a++; =>
i=6 + 7 + 7; (a=8); i=20;*/
i=a++ + ++a + ++a; /*a = 5;
i=a++ + ++a + ++a; =>
i=8 + 10 + 11; (a=11); i=29;*/
a=++a + ++a + a++; /*a=5;
a=++a + ++a + a++; =>
a=12 + 13 + 13; a=38;*/
System.out.println(a); //output: 38
System.out.println(i); //output: 29
The quotes you use are the issue:
<meta http-equiv=”refresh” content=”5" >
You should use the "
<meta http-equiv="refresh" content="5">
This issue is far too common to still be persistent. And most answers and instructions fail to address it. Here's what to do on Windows 10:
Type environment variables
in the start search bar, and open Edit the System Environment Variables.
Click Environment Variables...
In the System Variables section, locate the variable with the key Path
and double click it.
Look for paths pointing to python files. Likely there are none. If there are, select and delete them.
Create a new variable set to the path to your python executable. Normally this is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Python38
. Ensure this by checking via your File Explorer.
Note: If you can't see AppData
, it's because you've not enabled viewing of hidden items: click the View tab and tick the Hidden Items checkbox.
Create another variable pointing to the Scripts
directory. Typically it is C:\Users\[YOUR USERNAME HERE]\AppData\Local\Programs\Python\Scripts
.
Restart your terminal and try typing py
, python
, python3
, or python.exe
.
According to the error message, you declared myLoc
as a pointer to an NSInteger (NSInteger *myLoc
) rather than an actual NSInteger (NSInteger myLoc
). It needs to be the latter.
Originally there was just 302
Response | What browsers should do |
---|---|
302 Found |
Redo request with new url |
The idea is that:
GET
at some location, you would redo your GET
to the new URLPOST
at some location, you would redo your POST
to the new URLPUT
at some location, you would redo your PUT
to the new URLDELETE
at some location, you would redo your DELETE
to the new URLUnfortunately every browser did it wrong. When getting a 302
, they would always switch to GET
at the new URL, rather than retrying the request with the same verb (e.g., POST
):
It became de-facto wrong.
All browsers got 302
wrong. So 303
and 307
were created.
Response | What browsers should do | What browsers actually do |
---|---|---|
302 Found |
Redo request with new url | GET with new url |
303 See Other |
GET with new url | GET with new url |
307 Temporary Redirect |
Redo request with new url | Redo request with new url |
The 5 different kinds of redirects:
+------------------------------------------------------------+
¦ ¦ Switch to GET? ¦
¦ ¦------------------------------------------------¦
¦ Temporary ¦ No ¦ Yes ¦
¦-----------+------------------------+-----------------------¦
¦ No ¦ 308 Permanent Redirect ¦ 301 Moved Permanently ¦
¦-----------+------------------------+-----------------------¦
¦ Yes ¦ 307 Temporary Redirect ¦ 303 See Other ¦
¦ ¦ 302 Found (intended) ¦ 302 Found (actual) ¦
+------------------------------------------------------------+
Alternatively:
Response | Switch to get? | Temporary? |
---|---|---|
301 Moved Permanently |
No | No |
302 Found (intended) |
No | Yes |
302 Found (actual) |
Yes | Yes |
303 See Other |
Yes | Yes |
307 Temporary Redirect |
No | Yes |
308 Permanent Redirect |
No | No |
For integers:
Use arithmetic expansion: $((EXPR))
num=$((num1 + num2))
num=$(($num1 + $num2)) # Also works
num=$((num1 + 2 + 3)) # ...
num=$[num1+num2] # Old, deprecated arithmetic expression syntax
Using the external expr
utility. Note that this is only needed for really old systems.
num=`expr $num1 + $num2` # Whitespace for expr is important
For floating point:
Bash doesn't directly support this, but there are a couple of external tools you can use:
num=$(awk "BEGIN {print $num1+$num2; exit}")
num=$(python -c "print $num1+$num2")
num=$(perl -e "print $num1+$num2")
num=$(echo $num1 + $num2 | bc) # Whitespace for echo is important
You can also use scientific notation (for example, 2.5e+2
).
Common pitfalls:
When setting a variable, you cannot have whitespace on either side of =
, otherwise it will force the shell to interpret the first word as the name of the application to run (for example, num=
or num
)
num= 1
num =2
bc
and expr
expect each number and operator as a separate argument, so whitespace is important. They cannot process arguments like 3+
+4
.
num=`expr $num1+ $num2`
The -R, --relative
option will do this.
For example: if you want to backup /var/named/chroot
and create the same directory structure on the remote server then -R
will do just that.
Correcting gradle settings is quite difficult. If you don't know much about Gradle it requires you to learn alot. Instead you can do the following:
1) Start a new project in a new folder. Choose the same settings with your project with gradle problem but keep it simple: Choose an empty main activity. 2) Delete all the files in ...\NewProjectName\app\src\main folder 3) Copy all the files in ...\ProjectWithGradleProblem\app\src\main folder to ...\NewProjectName\app\src\main folder. 4) If you are using the Test project (\ProjectWithGradleProblem\app\src\AndroidTest) you can do the same for that too.
this method works fine if your Gradle installation is healthy. If you just installed Android studio and did not modify it, the Gradle installation should be fine.
sass --watch a.scss:a.css --style compressed
Consult the documentation for updates:
Since pip 20.1b1, which was released on 21 April 2020 and "added pip cache
command for inspecting/managing pip’s wheel cache", it is possible to issue this command:
pip cache purge
The reference guide is here:
https://pip.pypa.io/en/stable/reference/pip_cache/
The corresponding pull request is here.
from subprocess import Popen
Popen('python filename.py')
Very easy ... outside "span" element with small font and underline, and inside "font" element with bigger font size.
<span style="font-size:1em;text-decoration:underline;">_x000D_
<span style="font-size:1.5em;">_x000D_
Text with big font size and thin underline_x000D_
</span>_x000D_
</span>
_x000D_
The best that I've been able to do is
$(this).closest('.modal').modal('toggle');
This gets the modal holding the DOM object you triggered the event on (guessing you're clicking a button). Gets the closest parent '.modal' and toggles it. Obviously only works because it's inside the modal you clicked.
You can however do this:
$(".modal:visible").modal('toggle');
This gets the modal that is displaying (since you can only have one open at a time), and triggers the 'toggle' This would not work without ":visible"
Lots of work toward uniform versioning and in support of conventions has been completed since this question was first asked. Palatable options are now detailed in the Python Packaging User Guide. Also noteworthy is that version number schemes are relatively strict in Python per PEP 440, and so keeping things sane is critical if your package will be released to the Cheese Shop.
Here's a shortened breakdown of versioning options:
setup.py
(setuptools) and get the version.__init__.py
as well as source control), e.g. bump2version, changes or zest.releaser.__version__
global variable in a specific module.setup.py
release, and use importlib.metadata to pick it up at runtime. (Warning, there are pre-3.8 and post-3.8 versions.)__version__
in sample/__init__.py
and import sample in setup.py
.NOTE that (7) might be the most modern approach (build metadata is independent of code, published by automation). Also NOTE that if setup is used for package release that a simple python3 setup.py --version
will report the version directly.
Way later but still worth mentioning is that you can also use variables to output values in the SET clause of an UPDATE or in the fields of a SELECT;
DECLARE @val1 int;
DECLARE @val2 int;
UPDATE [dbo].[PortalCounters_TEST]
SET @val1 = NextNum, @val2 = NextNum = NextNum + 1
WHERE [Condition] = 'unique value'
SELECT @val1, @val2
In the example above @val1 has the before value and @val2 has the after value although I suspect any changes from a trigger would not be in val2 so you'd have to go with the output table in that case. For anything but the simplest case, I think the output table will be more readable in your code as well.
One place this is very helpful is if you want to turn a column into a comma-separated list;
DECLARE @list varchar(max) = '';
DECLARE @comma varchar(2) = '';
SELECT @list = @list + @comma + County, @comma = ', ' FROM County
print @list
Simple Way
if ($('#text-field > p.filled-text').length != 0)
You can use:
print(df[df['Value']==df['Value'].max()])
Memory management in Linux is a bit tricky to understand, and I can't say I fully understand it yet, but I'll try to share a little bit of my experience and knowledge.
Short answer to your question: Yes there are other stuff included than whats in the list.
What's being shown in your list is applications run in userspace. The kernel uses memory for itself and modules, on top of that it also has a lower limit of free memory that you can't go under. When you've reached that level it will try to free up resources, and when it can't do that anymore, you end up with an OOM problem.
From the last line of your list you can read that the kernel reports a total-vm usage of: 1498536kB (1,5GB), where the total-vm includes both your physical RAM and swap space. You stated you don't have any swap but the kernel seems to think otherwise since your swap space is reported to be full (Total swap = 524284kB, Free swap = 0kB) and it reports a total vmem size of 1,5GB.
Another thing that can complicate things further is memory fragmentation. You can hit the OOM killer when the kernel tries to allocate lets say 4096kB of continous memory, but there are no free ones availible.
Now that alone probably won't help you solve the actual problem. I don't know if it's normal for your program to require that amount of memory, but I would recommend to try a static code analyzer like cppcheck to check for memory leaks or file descriptor leaks. You could also try to run it through Valgrind to get a bit more information out about memory usage.
Use the following command from Linux
find $JBOSS_HOME -name run.sh -exec {} -V \; | grep '^JBoss'
No, there's no built-in way to convert a class like you say. The simplest way to do this would be to do what you suggested: create a DerivedClass(BaseClass)
constructor. Other options would basically come out to automate the copying of properties from the base to the derived instance, e.g. using reflection.
The code you posted using as
will compile, as I'm sure you've seen, but will throw a null reference exception when you run it, because myBaseObject as DerivedClass
will evaluate to null
, since it's not an instance of DerivedClass
.
You can use np.where
to get indices and np.logical_and
to set two conditions:
import numpy as np
a = np.array([1, 3, 5, 6, 9, 10, 14, 15, 56])
np.where(np.logical_and(a>=6, a<=10))
# returns (array([3, 4, 5]),)
Closest you'd get to a struct is an object with all members public.
class MyStruct {
public $foo;
public $bar;
}
$obj = new MyStruct();
$obj->foo = 'Hello';
$obj->bar = 'World';
I'd say looking at the PHP Class Documentation would be worth it. If you need a one-off struct, use the StdObject as mentioned in alex's answer.
Yes. Please see the man page of bash ( the first thing you go to ) under Special Parameters
Special Parameters
The shell treats several parameters specially. These parameters may only be referenced; assignment to them is not allowed.
*
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is,"$*"
is equivalent to"$1c$2c..."
, wherec
is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.
@
Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is,"$@"
is equivalent to"$1"
"$2"
... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters,"$@"
and$@
expand to nothing (i.e., they are removed).
This probably harks from the old VB NOT .Net days when bool.ToString produced True or False.
Here's the signature.
public static string ActionLink(this HtmlHelper htmlHelper,
string linkText,
string actionName,
string controllerName,
object values,
object htmlAttributes)
What you are doing is mixing the values
and the htmlAttributes
together. values
are for URL routing.
You might want to do this.
@Html.ActionLink(Context.User.Identity.Name, "Index", "Account", null,
new { @style="text-transform:capitalize;" });
XML
android:maxLength="10"
Programmatically:
int maxLength = 10;
InputFilter[] filters = new InputFilter[1];
filters[0] = new InputFilter.LengthFilter(maxLength);
yourEditText.setFilters(filters);
Note: internally, EditText & TextView parse the value of android:maxLength
in XML and use InputFilter.LengthFilter()
to apply it.
See: TextView.java#L1564
Tag helpers:
<a asp-controller="OtherController" asp-action="Index" class="btn btn-primary"> Back to Other Controller View </a>
In the controller.cs have a method:
public async Task<IActionResult> Index()
{
ViewBag.Title = "Titles";
return View(await Your_Model or Service method);
}
partition by
doesn't actually roll up the data. It allows you to reset something on a per group basis. For example, you can get an ordinal column within a group by partitioning on the grouping field and using rownum()
over the rows within that group. This gives you something that behaves a bit like an identity column that resets at the beginning of each group.
I just had this issue, but needed to handle multiple tab levels. The code is rather ugly (see comments), but does its job: https://gist.github.com/JensRantil/4721860 Hopefully someone else will find it useful (and feel free to propose better solutions!).
Simply ...........
As 2's complement of any number we can calculate by inverting all 1s to 0's and vice-versa than we add 1 to it..
Here N= ~N produce results -(N+1) always. Because system store data in form of 2's complement which means it stores ~N like this.
~N = -(~(~N)+1) =-(N+1).
For example::
N = 10 = 1010
Than ~N = 0101
so ~(~N) = 1010
so ~(~N) +1 = 1011
Now point is from where Minus comes. My opinion is suppose we have 32 bit register which means 2^31 -1 bit involved in operation and to rest one bit which change in earlier computation(complement) stored as sign bit which is 1 usually. And we get result as ~10 = -11.
~(-11) =10 ;
The above is true if printf("%d",~0); we get result: -1;
But printf("%u",~0) than result: 4294967295 on 32 bit machine.
Note: Not in boolean
WebDriver driver=new FirefoxDriver();
driver.get("http://www.gmail.com");
if(driver.getPageSource().contains("Ur message"))
{
System.out.println("Pass");
}
else
{
System.out.println("Fail");
}
Unblock multi-line comment
Ctrl+5
Multi-line comment
Ctrl+4
NOTE: For my version of Spyder (3.1.4) if I highlighted the entire multi-line comment and used Ctrl+5 the block remained commented out. Only after highlighting a small portion of the multi-line comment did Ctrl+5 work.
Answer for this question is good if you want to overwrite your file everytime you rerun your program, but if you want your records to not be lost at rerunning your program, you may want to try this
public void writeAudit(String actionName) {
String whereWrite = "./csvFiles/audit.csv";
try {
FileWriter fw = new FileWriter(whereWrite, true);
BufferedWriter bw = new BufferedWriter(fw);
PrintWriter pw = new PrintWriter(bw);
Date date = new Date();
pw.println(actionName + "," + date.toString());
pw.flush();
pw.close();
} catch (FileNotFoundException e) {
System.out.println(e.getMessage());
} catch (IOException e) {
e.printStackTrace();
}
}
Java documentation is helpful to know the root cause of a particular IOException.
Just have a look at the direct known sub-interfaces of IOException
from the documentation page:
ChangedCharSetException, CharacterCodingException, CharConversionException, ClosedChannelException, EOFException, FileLockInterruptionException, FileNotFoundException, FilerException, FileSystemException, HttpRetryException, IIOException, InterruptedByTimeoutException, InterruptedIOException, InvalidPropertiesFormatException, JMXProviderException, JMXServerErrorException, MalformedURLException, ObjectStreamException, ProtocolException, RemoteException, SaslException, SocketException, SSLException, SyncFailedException, UnknownHostException, UnknownServiceException, UnsupportedDataTypeException, UnsupportedEncodingException, UserPrincipalNotFoundException, UTFDataFormatException, ZipException
Most of these exceptions are self-explanatory.
A few IOExceptions
with root causes:
EOFException: Signals that an end of file or end of stream has been reached unexpectedly during input. This exception is mainly used by data input streams to signal the end of the stream.
SocketException: Thrown to indicate that there is an error creating or accessing a Socket.
RemoteException: A RemoteException is the common superclass for a number of communication-related exceptions that may occur during the execution of a remote method call. Each method of a remote interface, an interface that extends java.rmi.Remote, must list RemoteException in its throws clause.
UnknownHostException: Thrown to indicate that the IP address of a host could not be determined (you may not be connected to Internet).
MalformedURLException: Thrown to indicate that a malformed URL has occurred. Either no legal protocol could be found in a specification string or the string could not be parsed.
You can use the include?
method:
my_string = "abcdefg"
if my_string.include? "cde"
puts "String includes 'cde'"
end
For those using asyncio, an easy way is to use asyncio.wait_for()
:
async def my_loop():
res = False
while not res:
res = await do_something()
await asyncio.wait_for(my_loop(), 10)
I use this method:
{% if quote.myfile %}
<div class="">
<a role="button"
href="{{ quote.myfile.url }}"
download="{{ quote.myfile.url }}"
class="btn btn-light text-dark ml-0">
Download attachment
</a>
</div>
{% endif %}
Thought this might help to someone, it happens because "When the number of data queries is greater than 1".reference
The init func runs first and then main. It's used for setting something first before your program runs, for example:
Accessing a template, Running the program using all cores, Checking the Goos and arch etc...
<TABLE COLS="3" border="0" cellspacing="0" cellpadding="0">
<TR style="vertical-align:top">
<TD>
<!-- The log text-box -->
<div style="height:800px; width:240px; border:1px solid #ccc; font:16px/26px Georgia, Garamond, Serif; overflow:auto;">
Log:
</div>
</TD>
<TD>
<!-- The 2nd column -->
</TD>
<TD>
<!-- The 3rd column -->
</TD>
</TR>
</TABLE>
LoadLibrary
does not do what you think it does. It loads the DLL into the memory of the current process, but it does not magically import functions defined in it! This wouldn't be possible, as function calls are resolved by the linker at compile time while LoadLibrary
is called at runtime (remember that C++ is a statically typed language).
You need a separate WinAPI function to get the address of dynamically loaded functions: GetProcAddress
.
Example
#include <windows.h>
#include <iostream>
/* Define a function pointer for our imported
* function.
* This reads as "introduce the new type f_funci as the type:
* pointer to a function returning an int and
* taking no arguments.
*
* Make sure to use matching calling convention (__cdecl, __stdcall, ...)
* with the exported function. __stdcall is the convention used by the WinAPI
*/
typedef int (__stdcall *f_funci)();
int main()
{
HINSTANCE hGetProcIDDLL = LoadLibrary("C:\\Documents and Settings\\User\\Desktop\\test.dll");
if (!hGetProcIDDLL) {
std::cout << "could not load the dynamic library" << std::endl;
return EXIT_FAILURE;
}
// resolve function address here
f_funci funci = (f_funci)GetProcAddress(hGetProcIDDLL, "funci");
if (!funci) {
std::cout << "could not locate the function" << std::endl;
return EXIT_FAILURE;
}
std::cout << "funci() returned " << funci() << std::endl;
return EXIT_SUCCESS;
}
Also, you should export your function from the DLL correctly. This can be done like this:
int __declspec(dllexport) __stdcall funci() {
// ...
}
As Lundin notes, it's good practice to free the handle to the library if you don't need them it longer. This will cause it to get unloaded if no other process still holds a handle to the same DLL.
Dockerfile is a file that contains text commands to assemble an image.
Docker compose is used to run a multi-container environment.
In your specific scenario, if you have multiple services for each technology you mentioned (service 1 using reddis, service 2 using rabbit mq etc), then you can have a Dockerfile for each of the services and a common docker-compose.yml to run all the "Dockerfile" as containers.
If you want them all in a single service, docker-compose will be a viable option.
If you are planning to hide show some span based on click event which is initially hidden with style="display:none" then .toggle() is best option to go with.
$("span").toggle();
Reasons : Each time you don't need to check whether the style is already there or not. .toggle() will take care of that automatically and hide/show span based on current state.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<input type="button" value="Toggle" onclick="$('#hiddenSpan').toggle();"/>_x000D_
<br/>_x000D_
<br/>_x000D_
<span id="hiddenSpan" style="display:none">Just toggle me</span>
_x000D_