Here's another option for those not using heatmap.2
(aheatmap
is good!)
Make a sequential vector of 100 values from min to max of your input matrix, find value closest to 0 in that, make two vector of colours to and from desired midpoint, combine and use them:
breaks <- seq(from=min(range(inputMatrix)), to=max(range(inputMatrix)), length.out=100)
midpoint <- which.min(abs(breaks - 0))
rampCol1 <- colorRampPalette(c("forestgreen", "darkgreen", "black"))(midpoint)
rampCol2 <- colorRampPalette(c("black", "darkred", "red"))(100-(midpoint+1))
rampCols <- c(rampCol1,rampCol2)
It may be relevant to see if it's running in PHP via command line as well-
<path-to-php-binary>php -i | grep memcache
Minor changes required for Kafka 0.10 and the new consumer compared to laughing_man's answer:
message.max.bytes
and replica.fetch.max.bytes
. message.max.bytes
has to be equal or smaller(*) than replica.fetch.max.bytes
.max.request.size
to send the larger message.max.partition.fetch.bytes
to receive larger messages.(*) Read the comments to learn more about message.max.bytes
<=replica.fetch.max.bytes
Maybe this is what you want?
echo foo > test.txt
echo. >> test.txt
echo bar >> test.txt
results in the following within test.txt:
foo
bar
Oracle 12c; Quick but limited:
select rownum+1000 from all_objects fetch first 50 rows only;
Note: limited to row count of all_objects view;
You can check the schema at http://schemas.microsoft.com/sqlserver/reporting/2005/01/reportdefinition/ReportDefinition.xsd
Search for xsd:complexType name="StyleType"
This will list out all the possible Styles you can use.
Specific to your question however, you can use the Format style.
Format
Specify the data format to use for values that appear in the textbox.
Valid values include Default, Number, Date, Time, Percentage, and Currency.
Link to MSDN: http://msdn.microsoft.com/en-us/library/ms251684(VS.80).aspx
In PHPMyAdmin you can:
You can apply that on many rows at once if you select them and click copy from the bottom of the table and then Preview SQl
In MS Windows, the mongoimport command has to be run in a normal Windows command prompt, not from the mongodb command prompt.
An anonymous class usually implements an interface:
new Runnable() { // implements Runnable!
public void run() {}
}
JFrame.addWindowListener( new WindowAdapter() { // extends class
} );
If you mean whether you can implement 2 or more interfaces, than I think that's not possible. You can then make a private interface which combines the two. Though I cannot easily imagine why you would want an anonymous class to have that:
public class MyClass {
private interface MyInterface extends Runnable, WindowListener {
}
Runnable r = new MyInterface() {
// your anonymous class which implements 2 interaces
}
}
Could the Barcode Rendering Framework at Codeplex GitHub be of help?
To set the value of a Boolean attribute, such as disabled, you can specify any value. An empty string or the name of the attribute are recommended values. All that matters is that if the attribute is present at all, regardless of its actual value, its value is considered to be true. The absence of the attribute means its value is false. By setting the value of the disabled attribute to the empty string (""), we are setting disabled to true, which results in the button being disabled.
var f = document.querySelectorAll( "label.disabled input" );
for( var i = 0; i < f.length; i++ )
{
// Reference
var e = f[ i ];
// Actions
e.setAttribute( "disabled", false|null|undefined|""|0|"disabled" );
/*
<input disabled="false"|"null"|"undefined"|empty|"0"|"disabled">
e.getAttribute( "disabled" ) === "false"|"null"|"undefined"|""|"0"|"disabled"
e.disabled === true
*/
e.removeAttribute( "disabled" );
/*
<input>
e.getAttribute( "disabled" ) === null
e.disabled === false
*/
e.disabled = false|null|undefined|""|0;
/*
<input>
e.getAttribute( "disabled" ) === null|null|null|null|null
e.disabled === false
*/
e.disabled = true|" "|"disabled"|1;
/*
<input disabled>
e.getAttribute( "disabled" ) === ""|""|""|""
e.disabled === true
*/
}
Have you tried using the dollar sign and brackets like this:
SELECT *
FROM foo
WHERE day >= '${CURRENT_DATE}';
The better practice is to use for-each
. Besides violating the Keep It Simple, Stupid principle, the new-fangled forEach()
has at least the following deficiencies:
Object prev = null; for(Object curr : list) { if( prev != null ) foo(prev, curr); prev = curr; }
Can't handle checked exceptions. Lambdas aren't actually forbidden from throwing checked exceptions, but common functional interfaces like Consumer
don't declare any. Therefore, any code that throws checked exceptions must wrap them in try-catch
or Throwables.propagate()
. But even if you do that, it's not always clear what happens to the thrown exception. It could get swallowed somewhere in the guts of forEach()
Limited flow-control. A return
in a lambda equals a continue
in a for-each, but there is no equivalent to a break
. It's also difficult to do things like return values, short circuit, or set flags (which would have alleviated things a bit, if it wasn't a violation of the no non-final variables rule). "This is not just an optimization, but critical when you consider that some sequences (like reading the lines in a file) may have side-effects, or you may have an infinite sequence."
Might execute in parallel, which is a horrible, horrible thing for all but the 0.1% of your code that needs to be optimized. Any parallel code has to be thought through (even if it doesn't use locks, volatiles, and other particularly nasty aspects of traditional multi-threaded execution). Any bug will be tough to find.
Might hurt performance, because the JIT can't optimize forEach()+lambda to the same extent as plain loops, especially now that lambdas are new. By "optimization" I do not mean the overhead of calling lambdas (which is small), but to the sophisticated analysis and transformation that the modern JIT compiler performs on running code.
If you do need parallelism, it is probably much faster and not much more difficult to use an ExecutorService. Streams are both automagical (read: don't know much about your problem) and use a specialized (read: inefficient for the general case) parallelization strategy (fork-join recursive decomposition).
Makes debugging more confusing, because of the nested call hierarchy and, god forbid, parallel execution. The debugger may have issues displaying variables from the surrounding code, and things like step-through may not work as expected.
Streams in general are more difficult to code, read, and debug. Actually, this is true of complex "fluent" APIs in general. The combination of complex single statements, heavy use of generics, and lack of intermediate variables conspire to produce confusing error messages and frustrate debugging. Instead of "this method doesn't have an overload for type X" you get an error message closer to "somewhere you messed up the types, but we don't know where or how." Similarly, you can't step through and examine things in a debugger as easily as when the code is broken into multiple statements, and intermediate values are saved to variables. Finally, reading the code and understanding the types and behavior at each stage of execution may be non-trivial.
Sticks out like a sore thumb. The Java language already has the for-each statement. Why replace it with a function call? Why encourage hiding side-effects somewhere in expressions? Why encourage unwieldy one-liners? Mixing regular for-each and new forEach willy-nilly is bad style. Code should speak in idioms (patterns that are quick to comprehend due to their repetition), and the fewer idioms are used the clearer the code is and less time is spent deciding which idiom to use (a big time-drain for perfectionists like myself!).
As you can see, I'm not a big fan of the forEach() except in cases when it makes sense.
Particularly offensive to me is the fact that Stream
does not implement Iterable
(despite actually having method iterator
) and cannot be used in a for-each, only with a forEach(). I recommend casting Streams into Iterables with (Iterable<T>)stream::iterator
. A better alternative is to use StreamEx which fixes a number of Stream API problems, including implementing Iterable
.
That said, forEach()
is useful for the following:
Atomically iterating over a synchronized list. Prior to this, a list generated with Collections.synchronizedList()
was atomic with respect to things like get or set, but was not thread-safe when iterating.
Parallel execution (using an appropriate parallel stream). This saves you a few lines of code vs using an ExecutorService, if your problem matches the performance assumptions built into Streams and Spliterators.
Specific containers which, like the synchronized list, benefit from being in control of iteration (although this is largely theoretical unless people can bring up more examples)
Calling a single function more cleanly by using forEach()
and a method reference argument (ie, list.forEach (obj::someMethod)
). However, keep in mind the points on checked exceptions, more difficult debugging, and reducing the number of idioms you use when writing code.
Articles I used for reference:
EDIT: Looks like some of the original proposals for lambdas (such as http://www.javac.info/closures-v06a.html Google Cache) solved some of the issues I mentioned (while adding their own complications, of course).
As far as I know it's not possible... but you can try something like this:
.underline _x000D_
{_x000D_
color: blue;_x000D_
border-bottom: 1px solid red;_x000D_
}
_x000D_
<div>_x000D_
<span class="underline">hello world</span>_x000D_
</div>
_x000D_
For web service testing, soap rest or WCF (including WebHttpBinding), try out SOA Cleaner. Can be downloded from:http://xyrow.com. There is a free version, and it doesn't require any installation. It can also perform load tests.
Bash job control involves multiple processes, not multiple threads.
You can execute a command in background with the &
suffix.
You can wait for completion of a background command with the wait
command.
You can execute multiple commands in parallel by separating them with |
. This provides also a synchronization mechanism, since stdout of a command at left of |
is connected to stdin of command at right.
[Range(0.01,100000000,ErrorMessage = "Price must be greter than zero !")]
SOLVED: Always be sure to update your Xcode folks!
Protip: And don't do it from the apple store (but always do it from an official apple website of course)
tip from: http://ericasadun.com/2016/03/22/xcode-upgrades-lessons-learned/
official apple download page: https://developer.apple.com/download/more/
For those who are unable to resolve with above method
Go to project settings in Xcode. Menu File->Project Settings
Go to per-User Project Settings section.
Click on advanced.
Select Xcode Default option. previously this used to be Legacy for my project.
I have analysed on similar lines and concluded that clean is causing the archive to fail. So, the new build system is not clearing the custom/legacy build directory.
delete the build/ folder in ios/ and rerun if that doesn't do any change then
File -> Project Settings (or WorkSpace Settings) -> Build System -> Legacy Build System
Rerun and voilà!
If it still Fails you need to clean full project
Do the following:
npm cache clean --force
react-native eject
npm install
react-native link
react-native run-ios
Yes, that's the intuitive answer. Nothing in Spyder is intuitive. Go to Preferences/Editor and select the scheme you want. Then go to Preferences/Syntax Coloring and adjust the colors if you want to. tcebob
index.php
$url = 'http://[host]/test.php';
$json = json_encode(['name' => 'Jhonn', 'phone' => '128000000000']);
$options = ['http' => [
'method' => 'POST',
'header' => 'Content-type:application/json',
'content' => $json
]];
$context = stream_context_create($options);
$response = file_get_contents($url, false, $context);
test.php
$raw = file_get_contents('php://input');
$data = json_decode($raw, true);
echo $data['name']; // Jhonn
Solution checked and work in Swift 5
Below I put few solutions for different cases:
The best solution to remove text from back button is to add in viewDidLoad():
navigationItem.backBarButtonItem = UIBarButtonItem()
In case you want to set your own title, do it by setting title of backButton:
let backButton = UIBarButtonItem()
backButton.title = "My Title"
navigationItem.backBarButtonItem = backItem
If you want to create common style in entire app - to have just arrow back without text, create base VC for all your View Controllers:
class BaseViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
navigationItem.backBarButtonItem = UIBarButtonItem()
}
}
Solution presented above let you customize back button in the future if you want to make some exception later, by adding additional variable and overriding it in specific ViewController, f.ex:
class BaseViewController: UIViewController {
var customBackButtonTitle: String?
override func viewDidLoad() {
super.viewDidLoad()
var backButton = UIBarButtonItem()
if let text = customBackButtonTitle {
backButton.title = text
}
navigationItem.backBarButtonItem = backButton
}
}
There is no need to use :checkbox
, also replace #activelist
with #inactivelist
:
$('#inactivelist').change(function () {
alert('changed');
});
The corner radius of the 57 x 57 pixel icon is 9 pixels.
As explained in this thread on the cxf-user mailing list, rather than having the CXFServlet load its own spring context from user-webservice-servlet.xml
, you can just load the whole lot into the root context. Rename your existing user-webservice-servlet.xml
to some other name (e.g. user-webservice-beans.xml
) then change your contextConfigLocation
parameter to something like:
<servlet>
<servlet-name>myservlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>myservlet</servlet-name>
<url-pattern>*.htm</url-pattern>
</servlet-mapping>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
/WEB-INF/applicationContext.xml
/WEB-INF/user-webservice-beans.xml
</param-value>
</context-param>
<servlet>
<servlet-name>user-webservice</servlet-name>
<servlet-class>org.apache.cxf.transport.servlet.CXFServlet</servlet-class>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>user-webservice</servlet-name>
<url-pattern>/UserService/*</url-pattern>
</servlet-mapping>
To add to these answers, if you have an R script containing calls that generate plots to screen (the native device), then these can all be saved to a pdf file (the default device for a non-interactive shell) "Rplots.pdf" (the default name) by redirecting the script into R from the terminal (assuming you are running linux or OS X), e.g.:
R < myscript.R --no-save
This could be converted to jpg/png as necessary
Try using WSDL.exe and then including the generated file (.cs) into your project.
Fire up the Visual Studio Command prompt (under visual studio/tools in the start menu) then type
>wsdl.exe [path To Your WSDL File]
That'll spit out a file, which you copy/move and include in your project. That file contains a class which is a proxy to your sevice, Fire up an instance of that class, and it'll have a URL property you can set on the fly, and a bunch of methods that you can call. It'll also generate classes for all/any complex objects passed across the service interface.
Just a precision to Ellis Whitehead's answer. $locationProvider.html5Mode(true);
won't work with new version of angularjs without specifying the base URL for the application with a <base href="">
tag or setting the parameter requireBase
to false
If you configure $location to use html5Mode (history.pushState), you need to specify the base URL for the application with a tag or configure $locationProvider to not require a base tag by passing a definition object with requireBase:false to $locationProvider.html5Mode():
$locationProvider.html5Mode({
enabled: true,
requireBase: false
});
Try this one, it worked for me in Athena:
cast(MyVarcharCol as integer)
A very portable way is to parse the output of this command.
ifconfig | awk '$0 ~ /HWaddr/ { print $5 }'
Provided ifconfig can be run as the current user (usually can) and awk is installed (it often is). This will give you the mac address of the machine.
If you're after the 'name', why does your code snippet look like an attempt to get the 'characters'?
Anyways, this is no different from any other list- or array-like operation: you just need to iterate over the dataset and grab the information you're interested in. Retrieving all the names should look somewhat like this:
List<String> allNames = new ArrayList<String>();
JSONArray cast = jsonResponse.getJSONArray("abridged_cast");
for (int i=0; i<cast.length(); i++) {
JSONObject actor = cast.getJSONObject(i);
String name = actor.getString("name");
allNames.add(name);
}
(typed straight into the browser, so not tested).
You can use custom ActionFilter in Web Api to validate model:
public class DRFValidationFilters : ActionFilterAttribute
{
public override void OnActionExecuting(HttpActionContext actionContext)
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
//BadRequest(actionContext.ModelState);
}
}
public override Task OnActionExecutingAsync(HttpActionContext actionContext,
CancellationToken cancellationToken)
{
return Task.Factory.StartNew(() =>
{
if (!actionContext.ModelState.IsValid)
{
actionContext.Response = actionContext.Request
.CreateErrorResponse(HttpStatusCode.BadRequest, actionContext.ModelState);
}
});
}
public class AspirantModel
{
public int AspirantId { get; set; }
public string FirstName { get; set; }
public string MiddleName { get; set; }
public string LastName { get; set; }
public string AspirantType { get; set; }
[RegularExpression(@"^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$",
ErrorMessage = "Not a valid Phone number")]
public string MobileNumber { get; set; }
public int StateId { get; set; }
public int CityId { get; set; }
public int CenterId { get; set; }
[HttpPost]
[Route("AspirantCreate")]
[DRFValidationFilters]
public IHttpActionResult Create(AspirantModel aspirant)
{
if (aspirant != null)
{
}
else
{
return Conflict();
}
return Ok();
}
}
}
Register CustomAttribute class in webApiConfig.cs config.Filters.Add(new DRFValidationFilters());
For me it worked:
function changeA2 () { $global:A="0"}
changeA2
$A
For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services
From the above referenced site:
Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.
Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.
Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.
You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.
Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx
If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx
If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx
If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx
If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx
Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx
Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx
You should use HTML5 data attributes. You can create your own attributes and save different values in them.
<td align="center" valign="center">textgoeshere</td>
Is the only correct answer imho, since your working with tables which is old functionality most common used for e-mail formatting. So your best bet is to not use just style but inline style and known table tags.
All variables are cached so the loop and keyup event doesn't have to create a jQuery object everytime it runs.
var $input = $('input:text'),
$register = $('#register');
$register.attr('disabled', true);
$input.keyup(function() {
var trigger = false;
$input.each(function() {
if (!$(this).val()) {
trigger = true;
}
});
trigger ? $register.attr('disabled', true) : $register.removeAttr('disabled');
});
Check working example at http://jsfiddle.net/DKNhx/3/
I have encountered such error but after modifying my response before sending it to the client it worked fine.
//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response); // Sending to client
//Client side
success: function(res, status) {
response = JSON.parse(res); // Getting as expected
//Do something
}
Here's the quick fix:
If you're using capistrano do this add this to your deploy.rb:
after 'deploy:update_code' do
run "cd #{release_path}; RAILS_ENV=production rake assets:precompile"
end
cap deploy
Enjoy ;-)
Function Is64Bit() As Boolean
Return My.Computer.FileSystem.SpecialDirectories.ProgramFiles.Contains("Program Files (x86)")
End Function
If you are passing (like me) all the parameters like port, username, password through a system and you are not allow to modify the code, then you can do that easy change on the web.config
:
<system.net>
<mailSettings>
<smtp>
<network enableSsl="true"/>
</smtp>
</mailSettings>
</system.net>
There are many differences as specified above. Apart from above all, there is one more difference. Response.Redirect()
can be used to redirect user to any page which is not part of the application but Server.Transfer()
can only be used to redirect user within the application.
//This will work.
Response.Redirect("http://www.google.com");
//This will not work.
Server.Transfer("http://www.google.com");
public class DayFlipper extends ViewPager {
private Flipperadapter adapter;
public class FlipperAdapter extends PagerAdapter {
@Override
public int getCount() {
return DayFlipper.DAY_HISTORY;
}
@Override
public void startUpdate(View container) {
}
@Override
public Object instantiateItem(View container, int position) {
Log.d(TAG, "instantiateItem(): " + position);
Date d = DateHelper.getBot();
for (int i = 0; i < position; i++) {
d = DateHelper.getTomorrow(d);
}
d = DateHelper.normalize(d);
CubbiesView cv = new CubbiesView(mContext);
cv.setLifeDate(d);
((ViewPager) container).addView(cv, 0);
// add map
cv.setCubbieMap(mMap);
cv.initEntries(d);
adpter = FlipperAdapter.this;
return cv;
}
@Override
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((CubbiesView) object);
}
@Override
public void finishUpdate(View container) {
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == ((CubbiesView) object);
}
@Override
public Parcelable saveState() {
return null;
}
@Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
}
...
public void refresh() {
adapter().notifyDataSetChanged();
}
}
try this.
Consider both at the same time:
Furthermore, I suggest that you expand your Context to include not only access to singleton objects but some functionalities that need to be accessed globally, like for example: context.logOffUser(), context.readSavedData(), etc. Probably renaming the Context to Facade would make sense then.
Although Chang's answer explains how to plot multiple times on the same figure, in this case you might be better off in this case using a groupby
and unstack
ing:
(Assuming you have this in dataframe, with datetime index already)
In [1]: df
Out[1]:
value
datetime
2010-01-01 1
2010-02-01 1
2009-01-01 1
# create additional month and year columns for convenience
df['Month'] = map(lambda x: x.month, df.index)
df['Year'] = map(lambda x: x.year, df.index)
In [5]: df.groupby(['Month','Year']).mean().unstack()
Out[5]:
value
Year 2009 2010
Month
1 1 1
2 NaN 1
Now it's easy to plot (each year as a separate line):
df.groupby(['Month','Year']).mean().unstack().plot()
Use following code for view Up on UITextField Clicked
func textFieldDidBeginEditing(textField: UITextField) {
ViewUpanimateMoving(true, upValue: 100)
}
func textFieldDidEndEditing(textField: UITextField) {
ViewUpanimateMoving(false, upValue: 100)
}
func ViewUpanimateMoving (up:Bool, upValue :CGFloat){
var durationMovement:NSTimeInterval = 0.3
var movement:CGFloat = ( up ? -upValue : upValue)
UIView.beginAnimations( "animateView", context: nil)
UIView.setAnimationBeginsFromCurrentState(true)
UIView.setAnimationDuration(durationMovement)
self.view.frame = CGRectOffset(self.view.frame, 0, movement)
UIView.commitAnimations()
}
Late answer here, but if you search /etc/init.d/apache2
for 'reload', you'll find something like this:
do_reload() {
if apache_conftest; then
if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
APACHE2_INIT_MESSAGE="Apache2 is not running"
return 2
fi
$APACHE2CTL graceful > /dev/null 2>&1
return $?
else
APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
return 2
fi
}
Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:
apachectl graceful
(swallowing the output, and forwarding the exit code)This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest
manually.
The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful
), and some more color on the behavior thereof.
You should use it for times when you don't want to have to breakpoint every little line of code to check variables, but you do want to get some sort of feedback if certain situations are present, for example:
Debug.Assert(someObject != null, "someObject is null! this could totally be a bug!");
You are using jQuery(document).ready(function($) {}
means here you are using jQuery
instead of $
. So to resolve your issue use following code.
jQuery("#submittername").text(submitter_name);
This will resolve your problem.
Simply run sudo xcode-select -r
which should automatically reset the path.
-r, --reset
Unsets any user-specified developer directory, so that the developer directory will be found via the default search mechanism. This command must be
run with superuser permissions (see sudo(8)), and will affect all users on the system.
Using jQuery it is very simple assuming the URL you wish to post to is on the same server or has implemented CORS
$(function() {
$("#employeeLink").on("click",function(e) {
e.preventDefault(); // cancel the link itself
$.post(this.href,function(data) {
$("#someContainer").html(data);
});
});
});
If you insist on using frames which I strongly discourage, have a form and submit it with the link
<form action="employee.action" method="post" target="myFrame" id="myForm"></form>
and use (in plain JS)
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the link
document.getElementById("myForm").submit(); // but make sure nothing has name or ID="submit"
});
});
Without a form we need to make one
window.addEventListener("load",function() {
document.getElementById("employeeLink").addEventListener("click",function(e) {
e.preventDefault(); // cancel the actual link
var myForm = document.createElement("form");
myForm.action=this.href;// the href of the link
myForm.target="myFrame";
myForm.method="POST";
myForm.submit();
});
});
Sometimes it is possible to have most of implementation hidden in cpp file, if you can extract common functionality foo all template parameters into non-template class (possibly type-unsafe). Then header will contain redirection calls to that class. Similar approach is used, when fighting with "template bloat" problem.
In my case an unexpected error notice in the source code stopped the facebook crawler from parsing the (correctly set) og-meta tags.
I was using the HTTP_ACCEPT_LANGUAGE
header, which worked fine for regular browser requests but not for the crawler, as it obviously won't use/set it.
Therefore, it was crucial for me to use the facebook's debugger feature See exactly what our scraper sees for your URL
, as the error notice only could only be seen there (but not through the regular 'view source code'-browser feature).
Jürgen Weigert has the best answer that worked for me on Ubuntu, however on OSX, docker runs inside of VirtualBox and so the solution doesn't work without some more work.
I've got it working with these additional ingredients:
I'd appreciate user comments to improve this answer for OSX, I'm not sure if socket forwarding for X is secure, but my intended use is for running the docker container locally only.
Also, the script is a bit fragile in that it's not easy to get the IP address of the machine since it's on our local wireless so it's always some random IP.
The BASH script I use to launch the container:
#!/usr/bin/env bash
CONTAINER=py3:2016-03-23-rc3
COMMAND=/bin/bash
NIC=en0
# Grab the ip address of this box
IPADDR=$(ifconfig $NIC | grep "inet " | awk '{print $2}')
DISP_NUM=$(jot -r 1 100 200) # random display number between 100 and 200
PORT_NUM=$((6000 + DISP_NUM)) # so multiple instances of the container won't interfer with eachother
socat TCP-LISTEN:${PORT_NUM},reuseaddr,fork UNIX-CLIENT:\"$DISPLAY\" 2>&1 > /dev/null &
XSOCK=/tmp/.X11-unix
XAUTH=/tmp/.docker.xauth.$USER.$$
touch $XAUTH
xauth nlist $DISPLAY | sed -e 's/^..../ffff/' | xauth -f $XAUTH nmerge -
docker run \
-it \
--rm \
--user=$USER \
--workdir="/Users/$USER" \
-v "/Users/$USER:/home/$USER:rw" \
-v $XSOCK:$XSOCK:rw \
-v $XAUTH:$XAUTH:rw \
-e DISPLAY=$IPADDR:$DISP_NUM \
-e XAUTHORITY=$XAUTH \
$CONTAINER \
$COMMAND
rm -f $XAUTH
kill %1 # kill the socat job launched above
I'm able to get xeyes and matplotlib working with this approach.
It's a bit easier on Windows 7+ with MobaXterm:
run_docker.bash
:
#!/usr/bin/env bash
CONTAINER=py3:2016-03-23-rc3
COMMAND=/bin/bash
DISPLAY="$(hostname):0"
USER=$(whoami)
docker run \
-it \
--rm \
--user=$USER \
--workdir="/home/$USER" \
-v "/c/Users/$USER:/home/$USER:rw" \
-e DISPLAY \
$CONTAINER \
$COMMAND
if the database is InnoDB you dont need to do joins in deletion. only
DELETE FROM spawnlist WHERE spawnlist.type = "monster";
can be used to delete the all the records that linked with foreign keys in other tables, to do that you have to first linked your tables in design time.
CREATE TABLE IF NOT EXIST spawnlist (
npc_templateid VARCHAR(20) NOT NULL PRIMARY KEY
)ENGINE=InnoDB;
CREATE TABLE IF NOT EXIST npc (
idTemplate VARCHAR(20) NOT NULL,
FOREIGN KEY (idTemplate) REFERENCES spawnlist(npc_templateid) ON DELETE CASCADE
)ENGINE=InnoDB;
if you uses MyISAM you can delete records joining like this
DELETE a,b
FROM `spawnlist` a
JOIN `npc` b
ON a.`npc_templateid` = b.`idTemplate`
WHERE a.`type` = 'monster';
in first line i have initialized the two temp tables for delet the record, in second line i have assigned the existance table to both a and b but here i have linked both tables together with join keyword, and i have matched the primary and foreign key for both tables that make link, in last line i have filtered the record by field to delete.
The above answers unfortunately don't quite work. In particular, the compile stage does not have access to scope, so you can't customize the field based on dynamic attributes. Using the linking stage seems to offer the most flexibility (in terms of asynchronously creating dom, etc.) The below approach addresses that:
<!-- Usage: -->
<form>
<form-field ng-model="formModel[field.attr]" field="field" ng-repeat="field in fields">
</form>
// directive
angular.module('app')
.directive('formField', function($compile, $parse) {
return {
restrict: 'E',
compile: function(element, attrs) {
var fieldGetter = $parse(attrs.field);
return function (scope, element, attrs) {
var template, field, id;
field = fieldGetter(scope);
template = '..your dom structure here...'
element.replaceWith($compile(template)(scope));
}
}
}
})
I've created a gist with more complete code and a writeup of the approach.
You can use any of:
cd ~/"My Code"
cd ~/M"y Code"
cd ~/My" Code"
You cannot use:
cd ~"/My Code"
The first works because the shell expands ~/ into $HOME/, and then tacks on My Code without the double quotes. The second fails because there isn't a user called '"
' (double quote) for ~"
to map to.
if you are using matplotlib version 3.1.1 or above, you can try:
import matplotlib.pyplot as plt
from matplotlib.colors import ListedColormap
x = [1, 3, 4, 6, 7, 9]
y = [0, 0, 5, 8, 8, 8]
classes = ['A', 'B', 'C']
values = [0, 0, 1, 2, 2, 2]
colours = ListedColormap(['r','b','g'])
scatter = plt.scatter(x, y,c=values, cmap=colours)
plt.legend(handles=scatter.legend_elements()[0], labels=classes)
In javascript the "+" operator is used to add numbers or to concatenate strings. if one of the operands is a string "+" concatenates, and if it is only numbers it adds them.
example:
1+2+3 == 6
"1"+2+3 == "123"
Here's a piece of code I put in my scripts that I wan't to run in py2/3-agnostic environment:
# Thank you, python2-3 team, for making such a fantastic mess with
# input/raw_input :-)
real_raw_input = vars(__builtins__).get('raw_input',input)
Now you can use real_raw_input. It's quite expensive but short and readable. Using raw input is usually time expensive (waiting for input), so it's not important.
In theory, you can even assign raw_input instead of real_raw_input but there might be modules that check existence of raw_input and behave accordingly. It's better stay on the safe side.
The best solution i found out is to mute the video
HTML
<video loop muted autoplay id="videomain">
<source src="videoname.mp4" type="video/mp4">
</video>
You can use https://appery.io/ It is the same phonegap but in very convinient wrapper
Add a style with the attribute text-decoration:none;
:
There are a number of different ways of doing this.
Inline style:
<a href="xxx.html" style="text-decoration:none;">goto this link</a>
Inline stylesheet:
<html>
<head>
<style type="text/css">
a {
text-decoration:none;
}
</style>
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
External stylesheet:
<html>
<head>
<link rel="Stylesheet" href="stylesheet.css" />
</head>
<body>
<a href="xxx.html">goto this link</a>
</body>
</html>
stylesheet.css:
a {
text-decoration:none;
}
Yes you can target those specificaly using input[type=submit]
e.g.
.myFormClass input[type=submit] {
margin: 10px;
color: white;
background-color: blue;
}
I would try triming the number to see what you get:
select len(rtrim(ltrim(userid))) from audit
if that return the correct value then just do:
select convert(int, rtrim(ltrim(userid))) from audit
if that doesn't return the correct value then I would do a replace to remove the empty space:
select convert(int, replace(userid, char(0), '')) from audit
Update Aug 2020
Although the below is still worth reading for the useful info, we have had Flexbox for some time now, so just use that, as per this answer.
You can't use:
vertical-align:middle
because it's not applicable to block-level elements
margin-top:auto
and margin-bottom:auto
because their used values would compute as zero
margin-top:-50%
because percentage-based margin values are calculated relative to the width of containing block
In fact, the nature of document flow and element height calculation algorithms make it impossible to use margins for centering an element vertically inside its parent. Whenever a vertical margin's value is changed, it will trigger a parent element height re-calculation (re-flow), which would in turn trigger a re-center of the original element... making it an infinite loop.
You can use:
A few workarounds like this which work for your scenario; the three elements have to be nested like so:
.container {
display: table;
height: 100%;
position: absolute;
overflow: hidden;
width: 100%;
}
.helper {
#position: absolute;
#top: 50%;
display: table-cell;
vertical-align: middle;
}
.content {
#position: relative;
#top: -50%;
margin: 0 auto;
width: 200px;
border: 1px solid orange;
}
_x000D_
<div class="container">
<div class="helper">
<div class="content">
<p>stuff</p>
</div>
</div>
</div
_x000D_
JSFiddle works fine according to Browsershot.
Just another way of doing it, (or if you are using express) add the condition in code:
if(yourCondition)
{
System.Diagnostics.Debugger.Break();
}
In addition to the still very relevant answer of jujule, I find it quite important to also be aware of the implications of order_by()
on distinct("field_name")
queries. This is, however, a Postgres only feature!
If you are using Postgres and if you define a field name that the query should be distinct for, then order_by()
needs to begin with the same field name (or field names) in the same sequence (there may be more fields afterward).
Note
When you specify field names, you must provide an order_by() in the QuerySet, and the fields in order_by() must start with the fields in distinct(), in the same order.
For example, SELECT DISTINCT ON (a) gives you the first row for each value in column a. If you don’t specify an order, you’ll get some arbitrary row.
If you want to e-g- extract a list of cities that you know shops in , the example of jujule would have to be adapted to this:
# returns an iterable Queryset of cities.
models.Shop.objects.order_by('city').values_list('city', flat=True).distinct('city')
In Windows machine, please follows the preceding steps.
Now source your db.
I think this is exactly what you want http://da2i.univ-lille1.fr/doc/tutorial-java/reflect/object/arg.html
Although it seems a dead thread, someone might find it useful
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
serves two purposes.
IE=edge
: specifies that IE should run in the highest mode available to that version of IE as opposed to a compatability mode; IE8 can support up to IE8 modes, IE9 can support up to IE9 modes, and so on.chrome=1
: specifies that Google Chrome frame should start if the user has it installedThe IE=edge
flag is still relevant for IE versions 10 and below. IE11 sets this mode as the default.
As for the chrome flag, you can leave it if your users still use Chrome Frame. Despite support and updates for Chrome Frame ending, one can still install and use the final release. If you remove the flag, Chrome Frame will not be activated when installed. For other users, chrome=1
will do nothing more than consume a few bytes of bandwidth.
I recommend you analyze your audience and see if their browsers prohibit any needed features and then decide. Perhaps it might be better to encourage them to use a more modern, evergreen browser.
Note, the W3C validator will flag chrome=1
as an error:
Error: A meta element with an http-equiv attribute whose value is
X-UA-Compatible must have a content attribute with the value IE=edge.
The slickest way to do this:
{React.cloneElement(this.props.children, this.props)}
Perhaps GitHub's support for deploy keys is what you're looking for? To quote that page:
When should I use a deploy key?
Simple, when you have a server that needs pull access to a single private repo. This key is attached directly to the repository instead of to a personal user account.
If that's what you're already trying and it doesn't work, you might want to update your question with more details of the URLs being used, the names and location of the key files, etc.
Now for the technical part: How to use your SSH key with Jenkins?
If you have, say, a jenkins
unix user, you can store your deploy key in ~/.ssh/id_rsa
. When Jenkins tries to clone the repo via ssh, it will try to use that key.
In some setups, you cannot run Jenkins as an own user account, and possibly also cannot use the default ssh key location ~/.ssh/id_rsa
. In such cases, you can create a key in a different location, e.g. ~/.ssh/deploy_key
, and configure ssh
to use that with an entry in ~/.ssh/config
:
Host github-deploy-myproject
HostName github.com
User git
IdentityFile ~/.ssh/deploy_key
IdentitiesOnly yes
Because all you authenticate to all Github repositories using [email protected]
and you don't want the above key to be used for all your connections to Github, we created a host alias github-deploy-myproject. Your clone URL now becomes
git clone github-deploy-myproject:myuser/myproject
and that is also what you put as repository URL into Jenkins.
(Note that you must not put ssh:// in front in order for this to work.)
Your target SDK
might be higher than SDK
of the device, change that.
For example, your device is running API 23 but your target SDK
is 25.
Change 25 to 23.
With a small edit to Joseph's code, the element does not require a solid background:
div {
height: 300px;
background: url('http://images2.layoutsparks.com/1/190037/serene-nature-scenery-blue.jpg');
position: relative;
}
div:before {
content: '';
position: absolute;
top: 0; right: 0;
border-top: 80px solid white;
border-left: 80px solid rgba(0,0,0,0);
width: 0;
}
http://jsfiddle.net/2bZAW/1921/
This use of 'rgba(0,0,0,0)' allows the inner 'corner' to be invisible .
You can also edit the 4th parameter 'a', where 0 < a < 1, to have a shadow for more of a 'folded-corner' effect:
http://jsfiddle.net/2bZAW/1922/ (with shadow)
NOTE: RGBA color values are supported in IE9+, Firefox 3+, Chrome, Safari, and in Opera 10+.
Converting your set into an array may also help you for iterating over the elements:
Object[] array = set.toArray();
for(int i=0; i<array.length; i++)
Object o = array[i];
function helloWorld(name, symbol = '!!!') {
name = name || 'worlds';
console.log('hello ' + name + symbol);
}
helloWorld(); // hello worlds!!!
helloWorld('john'); // hello john!!!
helloWorld('john', '(>.<)'); // hello john(>.<)
helloWorld('john', undefined); // hello john!!!
helloWorld(undefined, undefined); // hello worlds!!!
You can get the HTML of the website with driver.getPageSource(). If the html does not change in a given interval of time this means that the page is done loading. One or two seconds should be enough. If you want to speed things up you can just compare the lenght of the two htmls. If their lenght is equal the htmls should be equal and that means the page is fully loaded. The JavaScript solution did not work for me.
http://anandsekar.github.io/exporting-the-private-key-from-a-jks-keystore/
public class ExportPrivateKey {
private File keystoreFile;
private String keyStoreType;
private char[] password;
private String alias;
private File exportedFile;
public static KeyPair getPrivateKey(KeyStore keystore, String alias, char[] password) {
try {
Key key=keystore.getKey(alias,password);
if(key instanceof PrivateKey) {
Certificate cert=keystore.getCertificate(alias);
PublicKey publicKey=cert.getPublicKey();
return new KeyPair(publicKey,(PrivateKey)key);
}
} catch (UnrecoverableKeyException e) {
} catch (NoSuchAlgorithmException e) {
} catch (KeyStoreException e) {
}
return null;
}
public void export() throws Exception{
KeyStore keystore=KeyStore.getInstance(keyStoreType);
BASE64Encoder encoder=new BASE64Encoder();
keystore.load(new FileInputStream(keystoreFile),password);
KeyPair keyPair=getPrivateKey(keystore,alias,password);
PrivateKey privateKey=keyPair.getPrivate();
String encoded=encoder.encode(privateKey.getEncoded());
FileWriter fw=new FileWriter(exportedFile);
fw.write(“—–BEGIN PRIVATE KEY—–\n“);
fw.write(encoded);
fw.write(“\n“);
fw.write(“—–END PRIVATE KEY—–”);
fw.close();
}
public static void main(String args[]) throws Exception{
ExportPrivateKey export=new ExportPrivateKey();
export.keystoreFile=new File(args[0]);
export.keyStoreType=args[1];
export.password=args[2].toCharArray();
export.alias=args[3];
export.exportedFile=new File(args[4]);
export.export();
}
}
try using apply function.
df['quantity'] = df['quantity'].apply(lambda x: x*-1)
pch=20 returns a symbol sized between "." and 19.
It's a filled symbol (which is probably what you want).
Aside from that, even the base graphics system in R allows a user fine-grained control over symbol size, color, and shape. E.g.,
dfx = data.frame(ev1=1:10, ev2=sample(10:99, 10), ev3=10:1)
with(dfx, symbols(x=ev1, y=ev2, circles=ev3, inches=1/3,
ann=F, bg="steelblue2", fg=NULL))
$("#save").click(function () {
debugger
var xx = [];
var dd = { "firstname": "", "lastname": "", "address": "" };
var otable1 = $("#table1").dataTable().fnGetData();
for (var i = 0; i < otable1.length; i++) {
dd.firstname = otable1[i][0];
dd.lastname = otable1[i][1];
dd.address = otable1[i][2];
xx.push(dd);
var dd = { "firstname": "", "lastname": "", "address": "" };
}
JSON.stringify(alert(xx));
$.ajax({
url: '../Home/save',
type: 'POST',
data: JSON.stringify({ u: xx }),
contentType: 'application/json;',
dataType: 'json',
success: function (event) {
alert(event);
$("#table2").dataTable().fnDraw();
location.reload();
}
});
});
Use trim($source)
before $s[$source]
.
You should better verify where you get that list from.
An empty list is all you need, because an empty list won't fail.
If you get this list from somewhere else and don't know if it is ok or not you could create a utility method and use it like this:
for( Object o : safe( list ) ) {
// do whatever
}
And of course safe
would be:
public static List safe( List other ) {
return other == null ? Collections.EMPTY_LIST : other;
}
Simple HTML trick to get this :
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<div class="row" >_x000D_
_x000D_
<div class="col-md-6">_x000D_
<div class="row">_x000D_
<div class="col-md-4" >_x000D_
<label for="hours">Hours</label>_x000D_
<select class="form-control" required>_x000D_
<option> </option>_x000D_
<option value="1"> 1 </option>_x000D_
<option value="2"> 2 </option>_x000D_
<option value="3"> 3 </option>_x000D_
<option value="4"> 4 </option>_x000D_
<option value="5"> 5 </option>_x000D_
<option value="6"> 6 </option>_x000D_
<option value="7"> 7 </option>_x000D_
<option value="8"> 8 </option>_x000D_
<option value="9"> 9 </option>_x000D_
<option value="10"> 10 </option>_x000D_
<option value="11"> 11 </option>_x000D_
<option value="12"> 12 </option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="col-md-4" >_x000D_
<label for="minutes">Minutes</label>_x000D_
<select class="form-control" required="">_x000D_
<option selected disabled> </option>_x000D_
<option value="00"> 00 </option>_x000D_
<option value="10"> 10 </option>_x000D_
<option value="20"> 20 </option>_x000D_
<option value="30"> 30 </option>_x000D_
<option value="40"> 40 </option>_x000D_
<option value="50"> 50 </option>_x000D_
</select>_x000D_
</div>_x000D_
<div class="col-md-4" >_x000D_
<label for="hours">Select Meridiem</label>_x000D_
<select class="form-control" required="" >_x000D_
<option selected="" value="AM"> AM </option>_x000D_
<option value="PM"> PM </option>_x000D_
</select>_x000D_
</div>_x000D_
</div></div>_x000D_
</div>
_x000D_
I use this:
1) The parent activity call the secondary activity with the method "startActivityForResult"
2) In the secondary activity when is closing:
int exitCode = 1; // Select the number you want
setResult(exitCode);
finish();
3) And in the parent activity override the method "onActivityResult":
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
int exitCode = 1;
if(resultCode == exitCode) {
super.setResult(exitCode); // use this if you have more than 2 activities
finish();
}
}
This works fine for me.
It is worth noting that if changing default_socket_timeout on the fly, it might be useful to restore its value after your file_get_contents call:
$default_socket_timeout = ini_get('default_socket_timeout');
....
ini_set('default_socket_timeout', 10);
file_get_contents($url);
...
ini_set('default_socket_timeout', $default_socket_timeout);
You can get it to launch via spotlight if you create an Automator launcher for it:
Automator.app
Xcode.app
package. So instead you'll have to navigate to it in a separate Finder window and drag it onto the file selector window. It will be at one of the following paths depending on your version of Xcode (oldest to newest):
/Applications/Xcode.app/Contents/Developer/iOS Simulator.app
/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/Applications/iOS Simulator.app
/Applications/Xcode.app/Contents/Developer/Applications/Simulator.app
iOS Simulator.app
To get a nice icon for the Automator app you just made, you can do the following:
iOS Simulator.app
and choose Get InfoCmd-C
to copy itCmd-V
to pasteI found something very useful on this site when I was searching for an answer on this question. You can check it out at http://www.codingforums.com/javascript-programming/230503-how-get-margin-left-value.html. The part that helped me was the following:
/***
* get live runtime value of an element's css style
* http://robertnyman.com/2006/04/24/get-the-rendered-style-of-an-element
* note: "styleName" is in CSS form (i.e. 'font-size', not 'fontSize').
***/
var getStyle = function(e, styleName) {
var styleValue = "";
if (document.defaultView && document.defaultView.getComputedStyle) {
styleValue = document.defaultView.getComputedStyle(e, "").getPropertyValue(styleName);
} else if (e.currentStyle) {
styleName = styleName.replace(/\-(\w)/g, function(strMatch, p1) {
return p1.toUpperCase();
});
styleValue = e.currentStyle[styleName];
}
return styleValue;
}
////////////////////////////////////
var e = document.getElementById('yourElement');
var marLeft = getStyle(e, 'margin-left');
console.log(marLeft); // 10px
_x000D_
#yourElement {
margin-left: 10px;
}
_x000D_
<div id="yourElement"></div>
_x000D_
And many lines may look like this. The html here is sample only.
var div = document.createElement("div");
div.innerHTML =
'<div class="slideshow-container">\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">1 / 3</div>\n' +
'<img src="image1.jpg" style="width:100%">\n' +
'<div class="text">Caption Text</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">2 / 3</div>\n' +
'<img src="image2.jpg" style="width:100%">\n' +
'<div class="text">Caption Two</div>\n' +
'</div>\n' +
'<div class="mySlides fade">\n' +
'<div class="numbertext">3 / 3</div>\n' +
'<img src="image3.jpg" style="width:100%">\n' +
'<div class="text">Caption Three</div>\n' +
'</div>\n' +
'<a class="prev" onclick="plusSlides(-1)">❮</a>\n' +
'<a class="next" onclick="plusSlides(1)">❯</a>\n' +
'</div>\n' +
'<br>\n' +
'<div style="text-align:center">\n' +
'<span class="dot" onclick="currentSlide(1)"></span> \n' +
'<span class="dot" onclick="currentSlide(2)"></span> \n' +
'<span class="dot" onclick="currentSlide(3)"></span> \n' +
'</div>\n';
document.body.appendChild(div);
I strongly recommend Perlbrew. It lets you run multiple versions of Perl, install packages, hack Perl internals if you want to, all regular user permissions.
$("#content ul").append('<li><a href="/user/messages"><span class="tab">Message Center</span></a></li>');
Here is some feedback regarding Code Readability (shameless plug for a blog). http://coderob.wordpress.com/2012/02/02/code-readability
Consider separating the declaration of your new elements from the action of adding them to your UL.. It would look something like this:
var tabSpan = $('<span/>', {
html: 'Message Center'
});
var messageCenterAnchor = $('<a/>', {
href='/user/messages',
html: tabSpan
});
var newListItem = $('<li/>', {
html: messageCenterAnchor,
"id": "myIDGoesHere"
}); // NOTE: you have to put quotes around "id" for IE..
$("content ul").append(newListItem);
Happy coding :)
It's implied by nsayer's answer, but it's worth noting that the OP's for(..) syntax will work when "someList" is anything that implements java.lang.Iterable -- it doesn't have to be a list, or some collection from java.util. Even your own types, therefore, can be used with this syntax.
is there a special guideline that should be followed
There is no "standard" way to do batch files, because the vast majority of their authors and maintainers either don't understand programming concepts, or they think they don't apply to batch files.
But I am a programmer. I'm used to compiling, and I'm used to debuggers. Batch files aren't compiled, and you can't run them through a debugger, so they make me nervous. I suggest you be extra strict on what you write, so you can be very sure it will do what you think it does.
There are some coding standards that say: If you write an if
statement, you must use braces, even if you don't have an else
clause. This saves you from subtle, hard-to-debug problems, and is unambiguously readable. I see no reason you couldn't apply this reasoning to batch files.
Let's take a look at your code.
IF EXIST somefile.txt IF EXIST someotherfile.txt SET var=somefile.txt,someotherfile.txt
And the IF
syntax, from the command, HELP IF
:
IF [NOT] ERRORLEVEL number command
IF [NOT] string1==string2 command
IF [NOT] EXISTS filename command
...
IF EXIST filename (
command
) ELSE (
other command
)
So you are chaining IF
's as commands.
If you use the common coding-standard rule I mentioned above, you would always want to use parens. Here is how you would do so for your example code:
IF EXIST "somefile.txt" (
IF EXIST "someotherfile.txt" (
SET var="somefile.txt,someotherfile.txt"
)
)
Make sure you cleanly format, and do some form of indentation. You do it in code, and you should do it in your batch scripts.
Also, you should also get in the habit of always quoting your file names, and getting the quoting right. There is some verbiage under HELP FOR
and HELP SET
that will help you with removing extra quotes when re-quoting strings.
Edit
From your comments, and re-reading your original question, it seems like you want to build a comma separated list of files that exist. For this case, you could simply use a bunch of if
/else
statements, but that would result in a bunch of duplicated logic, and would not be at all clean if you had more than two files.
A better way is to write a sub-routine that checks for a single file's existence, and appends to a variable if the file specified exists. Then just call that subroutine for each file you want to check for:
@ECHO OFF
SETLOCAL
REM Todo: Set global script variables here
CALL :MainScript
GOTO :EOF
REM MainScript()
:MainScript
SETLOCAL
CALL :AddIfExists "somefile.txt" "%files%" "files"
CALL :AddIfExists "someotherfile.txt" "%files%" "files"
ECHO.Files: %files%
ENDLOCAL
GOTO :EOF
REM AddIfExists(filename, existingFilenames, returnVariableName)
:AddIfExists
SETLOCAL
IF EXIST "%~1" (
SET "result=%~1"
) ELSE (
SET "result="
)
(
REM Cleanup, and return result - concatenate if necessary
ENDLOCAL
IF "%~2"=="" (
SET "%~3=%result%"
) ELSE (
SET "%~3=%~2,%result%"
)
)
GOTO :EOF
<select id="mySelect">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="mercedes">Mercedes</option>
<option value="audi">Audi</option>
</select>
var mySelect = document.getElementById('mySelect'),
newOption = document.createElement('option');
newOption.value = 'bmw';
// Not all browsers support textContent (W3C-compliant)
// When available, textContent is faster (see http://stackoverflow.com/a/1359822/139010)
if (typeof newOption.textContent === 'undefined')
{
newOption.innerText = 'BMW';
}
else
{
newOption.textContent = 'BMW';
}
mySelect.appendChild(newOption);
for PHP developer
filter_var($value, FILTER_VALIDATE_MAC)
I would assume you tried it without adding !important
?
Inline CSS (which is how JavaScript adds styling) overrides the stylesheet CSS. I'm pretty sure that's the case even when the stylesheet CSS rule has !important
.
Another question (maybe a stupid question but must be asked.): Is the element you are trying to work on display:block;
or display:inline-block;
?
Not knowing your expertise in CSS... inline elements don't always behave as you would expect.
I was having the same problem but wanted to minimize 3rd party dependencies (because this one-off script was to be executed by many users). My solution was to wrap a curl
call and make sure that the exit code was 0
. Worked like a charm.
Recaptcha contact form 7 and Recaptcha v3 solution.
body:not(.page-id-20) .grecaptcha-badge {
display: none;
}
More Than One Contact Form Page?
body:not(.page-id-12):not(.page-id-43) .grecaptcha-badge {
display: none;
}
You can add more “nots” if you have more contact form pages.
body:not(.page-id-45):not(.page-id-78):not(.page-id-98) .grecaptcha-badge {
display: none;
}
Make sure that your body section will like this:
<body>
Change it so that it looks like this:
<body <?php body_class(); ?>>
Yes you can, using SQLite you can read from or write to a database from within the jar file, so that you won't have to extract and then re jar it, follow my post http://shoaibinamdar.in/blog/?p=313
using the syntax "jdbc:sqlite::resource:" you would be able to read and write to a database from within the jar file
I think it's best to explicitly state where the form posts. If you want to be totally safe, enter the same URL the form is on in the action attribute if you want it to submit back to itself. Although mainstream browsers evaluate ""
to the same page, you can't guarantee that non-mainstream browsers will.
And of course, the entire URL including GET data like Juddling points out.
In SQL Server , cast text as datetime
select cast('5/21/2013 9:45:48' as datetime)
I think natually do it is straightforward, whether Intellij IDEA or Android Studio, I always click new Java class menu, and then typing the class name, press Enter to create. after that, I manually typing "extends Activity" in the class file, and then import the class by shortcut key. finally, I also manually override the onCreate() method and invoke the setContentView() method.
Liam's link looks great, but also check out pandas.Timedelta
- looks like it plays nicely with NumPy's and Python's time deltas.
https://pandas.pydata.org/pandas-docs/stable/timedeltas.html
pd.date_range('2014-01-01', periods=10) + pd.Timedelta(days=1)
How about this :
I used CustomViewPager
and next, override scrollTo method
I checked the movement when doing a lot of small swipes, it doesn't scroll to other pages.
public class CustomViewPager extends ViewPager {
private boolean enabled;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.enabled = true;
}
@Override
public boolean onTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onTouchEvent(event);
}
return false;
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (this.enabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean enabled) {
this.enabled = enabled;
}
@Override
public void scrollTo(int x, int y) {
if(enabled) {
super.scrollTo(x, y);
}
}
}
You can also specify context location relatively to current classpath, which may be preferable
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath*:applicationContext*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
Is there a way to remove all previous click events that have been assigned to a button?
$('#saveBtn').unbind('click').click(function(){saveQuestion(id)});
Use this method to set custom cell height width.
Make sure to add this protocols
UICollectionViewDelegate
UICollectionViewDataSource
UICollectionViewDelegateFlowLayout
If you are using swift 5 or xcode 11 and later you need to set Estimate Size
to none
using storyboard in order to make it work properly. If you will not set that than below code will not work as expected.
Swift 4 or Later
extension YourViewController: UICollectionViewDelegate {
//Write Delegate Code Here
}
extension YourViewController: UICollectionViewDataSource {
//Write DataSource Code Here
}
extension YourViewController: UICollectionViewDelegateFlowLayout {
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
return CGSize(width: screenWidth, height: screenWidth)
}
}
Objective-C
@interface YourViewController : UIViewController<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath
{
return CGSizeMake(CGRectGetWidth(collectionView.frame), (CGRectGetHeight(collectionView.frame)));
}
UPDATE will not do anything if the row does not exist.
Where as the INSERT OR REPLACE would insert if the row does not exist, or replace the values if it does.
It took me some time to figure this out: My php-file was encoded in UTF-8. And the BOM prevented header location to work properly. In Notepad++ I set the file encoding to "UTF-8 without BOM" and the problem was gone.
You have to traverse the whole array and keep two auxiliary values:
Suppose your array is called myArray. At the end of this code minIndex has the index of the smallest value.
var min = Number.MAX_VALUE; //the largest number possible in JavaScript
var minIndex = -1;
for (int i=0; i<myArray.length; i++){
if (myArray[i] < min){
min = myArray[i];
minIndex = i;
}
}
This is assuming the worst case scenario: a totally random array. It is an O(n) algorithm or order n algorithm, meaning that if you have n elements in your array, then you have to look at all of them before knowing your answer. O(n) algorithms are the worst ones because they take a lot of time to solve the problem.
If your array is sorted or has any other specific structure, then the algorithm can be optimized to be faster.
Having said that, though, unless you have a huge array of thousands of values then don't worry about optimization since the difference between an O(n) algorithm and a faster one would not be noticeable.
If you want to check the python version in a particular cond environment you can also use conda list python
3 answers, which you can combine:
Set implicit wait immediately after creating the web driver instance:
_ = driver.Manage().Timeouts().ImplicitWait;
This will try to wait until the page is fully loaded on every page navigation or page reload.
After page navigation, call JavaScript return document.readyState
until "complete"
is returned. The web driver instance can serve as JavaScript executor. Sample code:
C#
new WebDriverWait(driver, MyDefaultTimeout).Until(
d => ((IJavaScriptExecutor) d).ExecuteScript("return document.readyState").Equals("complete"));
Java
new WebDriverWait(firefoxDriver, pageLoadTimeout).until(
webDriver -> ((JavascriptExecutor) webDriver).executeScript("return document.readyState").equals("complete"));
Check if the URL matches the pattern you expect.
If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:
cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt
show variables
Show variables like "`secure_file_priv`";
Note: keep your csv file in location given by the above command.
create table assessments (course_code varchar(5),batch_code varchar(7),id_assessment int, assessment_type varchar(10), date int , weight int);
Note: here the 'date
' column has some blank values in the csv file.
LOAD DATA INFILE 'C:/ProgramData/MySQL/MySQL Server 8.0/Uploads/assessments.csv'
INTO TABLE assessments
FIELDS TERMINATED BY ','
OPTIONALLY ENCLOSED BY ''
LINES TERMINATED BY '\n'
IGNORE 1 ROWS
(course_code,batch_code,id_assessment,assessment_type,@date,weight)
SET date = IF(@date = '', NULL, @date);
If I Understood correctly you need to view the .db file that you extracted from internal storage of Emulator. If that's the case use this
http://sourceforge.net/projects/sqlitebrowser/
to view the db.
You can also use a firefox extension
https://addons.mozilla.org/en-us/firefox/addon/sqlite-manager/
EDIT: For online tool use : https://sqliteonline.com/
The (currently) accepted answer by Jerub is correct for python2, but incorrect and may produce garbled results (as Apalala points out in a comment to that solution), for python3. That's because the unicode_escape codec requires its source to be coded in latin-1, not utf-8, as per the official python docs. Hence, in python3 use:
>>> myString="špåm\\nëðþ\\x73"
>>> print(myString)
špåm\nëðþ\x73
>>> decoded_string = myString.encode('latin-1','backslashreplace').decode('unicode_escape')
>>> print(decoded_string)
špåm
ëðþs
This method also avoids the extra unnecessary roundtrip between strings and bytes in metatoaster's comments to Jerub's solution (but hats off to metatoaster for recognizing the bug in that solution).
The most simplest solution I have seen to supply a short execution to the UI thread is via the post() method of a view. This is needed since UI methods are not re-entrant. The method for this is:
package android.view;
public class View;
public boolean post(Runnable action);
The post() method corresponds to the SwingUtilities.invokeLater(). Unfortunately I didn't find something simple that corresponds to the SwingUtilities.invokeAndWait(), but one can build the later based on the former with a monitor and a flag.
So what you save by this is creating a handler. You simply need to find your view and then post on it. You can find your view via findViewById() if you tend to work with id-ed resources. The resulting code is very simple:
/* inside your non-UI thread */
view.post(new Runnable() {
public void run() {
/* the desired UI update */
}
});
}
Note: Compared to SwingUtilities.invokeLater() the method View.post() does return a boolean, indicating whether the view has an associated event queue. Since I used the invokeLater() resp. post() anyway only for fire and forget, I did not check the result value. Basically you should call post() only after onAttachedToWindow() has been called on the view.
Best Regards
Here is a starting point for developing Android apps with HTML5. The HTML code will be stored in the "assets/www" folder in your Android project.
The reason this is failing is because (Python 3) input
returns a string. To convert it to an integer, use int(some_string)
.
You do not typically keep track of indices manually in Python. A better way to implement such a function would be
def cat_n_times(s, n):
for i in range(n):
print(s)
text = input("What would you like the computer to repeat back to you: ")
num = int(input("How many times: ")) # Convert to an int immediately.
cat_n_times(text, num)
I changed your API above a bit. It seems to me that n
should be the number of times and s
should be the string.
Use element.outerHTML to get full representation of element, including outer tags and attributes.
Here is a work around. You can use filter instead of find; but filter returns an array of matching objects. find
only returns the first match inside an array. So, why not use filter as following;
data.filter(function (x) {
return x.Id === e
})[0];
The difference is that variant 1 forces you to use an ArrayList
while variant 2 only guarantees you have anything that implements List<String>
.
Later on you could change that to List<String> arrayList = new LinkedList<String>();
without much hassle. Variant 1 might require you to change not only that line but other parts as well if they rely on working with an ArrayList<String>
.
Thus I'd use List<String>
in almost any case, except when I'd need to call the additional methods that ArrayList
provides (which was never the case so far): ensureCapacity(int)
and trimToSize()
.
The Heap is divided into young and old generations as follows :
Young Generation : It is place where lived for short period and divided into two spaces:
Old Generation : This pool basically contains tenured and virtual (reserved) space and will be holding those objects which survived after garbage collection from Young Generation.
Permanent Generation : This memory pool as name also says contain permanent class metadata and descriptors information so PermGen space always reserved for classes and those that is tied to the classes for example static members.
Java8 Update: PermGen is replaced with Metaspace which is very similar.
Main difference is that Metaspace re-sizes dynamically i.e., It can expand at runtime.
Java Metaspace space: unbounded (default)
Code Cache (Virtual or reserved) : If you are using HotSpot Java VM this includes code cache area that containing memory which will be used for compilation and storage of native code.
I'm using intelliJ 15 community edition and I'm able to right click a file and select 'add to .gitignore'
Extract single value from JSON response Python
Try this
import json
import sys
#load the data into an element
data={"test1" : "1", "test2" : "2", "test3" : "3"}
#dumps the json object into an element
json_str = json.dumps(data)
#load the json to a string
resp = json.loads(json_str)
#print the resp
print (resp)
#extract an element in the response
print (resp['test1'])
You can delete all breakpoints using
del <start_breakpoint_num> - <end_breakpoint_num>
To view the start_breakpoint_num and end_breakpoint_num use:
info break
As Ciro Santilli notes using command substitutions will drop trailing newlines. Their workaround adding trailing characters is great, but after using it for quite some time I decided I needed a solution that didn't use command substitution at all.
My approach now uses read
along with the printf
builtin's -v
flag in order to read the contents of stdin directly into a variable.
# Reads stdin into a variable, accounting for trailing newlines. Avoids
# needing a subshell or command substitution.
# Note that NUL bytes are still unsupported, as Bash variables don't allow NULs.
# See https://stackoverflow.com/a/22607352/113632
read_input() {
# Use unusual variable names to avoid colliding with a variable name
# the user might pass in (notably "contents")
: "${1:?Must provide a variable to read into}"
if [[ "$1" == '_line' || "$1" == '_contents' ]]; then
echo "Cannot store contents to $1, use a different name." >&2
return 1
fi
local _line _contents=()
while IFS='' read -r _line; do
_contents+=("$_line"$'\n')
done
# include $_line once more to capture any content after the last newline
printf -v "$1" '%s' "${_contents[@]}" "$_line"
}
This supports inputs with or without trailing newlines.
Example usage:
$ read_input file_contents < /tmp/file
# $file_contents now contains the contents of /tmp/file
You can call a reset function before appending. Something like this:
function resetNewReviewBoardForm() {
$("#Description").val('');
$("#PersonName").text('');
$("#members").empty(); //this one what worked in my case
$("#EmailNotification").val('False');
}
For Windows 7 and up, scheduled tasks are not run by cmd.exe
, but rather by MMC
(Microsoft Management Console). %SystemRoot%\Tasks
should work on any other Windows version though.
You need to add the following line at every environment:
config.action_mailer.default_url_options = { :host => "yourhost" }
That way, it can work in all environments and could be different from environment to environment. For example:
development.rb
config.action_mailer.default_url_options = { :host => "dev.yourhost.com" }
test.rb
config.action_mailer.default_url_options = { :host => "test.yourhost.com" }
production.rb
config.action_mailer.default_url_options = { :host => "www.yourhost.com" }
This post is high up when you google that error message, which I got when installing security patch KB4505224 on SQL Server 2017 Express i.e. None of the above worked for me, but did consume several hours trying.
The solution for me, partly from here was:
And all was well.
In certain circumstances you might want to differentiate between a PivotTable and its PivotCache. The Cache has it's own refresh method and its own collections. So we could have refreshed all the PivotCaches instead of the PivotTables.
The difference? When you create a new Pivot Table you are asked if you want it based on a previous table. If you say no, this Pivot Table gets its own cache and doubles the size of the source data. If you say yes, you keep your WorkBook small, but you add to a collection of Pivot Tables that share a single cache. The entire collection gets refreshed when you refresh any single Pivot Table in that collection. You can imagine therefore what the difference might be between refreshing every cache in the WorkBook, compared to refreshing every Pivot Table in the WorkBook.
Regarding commits, refs, branches and "et cetera", Magnus answer just works (git remote update
).
But unfortunately there is no way to clone
/ mirror / update
the hooks, as I wanted...
I have found this very interesting thread about cloning/mirroring the hooks:
http://kerneltrap.org/mailarchive/git/2007/8/28/256180/thread
I learned:
The hooks are not considered part of the repository contents.
There is more data, like the .git/description
folder, which does not get cloned, just as the hooks.
The default hooks that appear in the hooks
dir comes from the TEMPLATE_DIR
There is this interesting template
feature on git.
So, I may either ignore this "clone the hooks thing", or go for a rsync
strategy, given the purposes of my mirror (backup + source for other clones, only).
Well... I will just forget about hooks cloning, and stick to the git remote update
way.
clone
/ update
process, but also stashes, rerere, etc... So, for a strict backup, rsync
or equivalent would really be the way to go. As this is not really necessary in my case (I can afford not having hooks, stashes, and so on), like I said, I will stick to the remote update
.Thanks! Improved a bit of my own "git-fu"... :-)
I came up with this:
from datetime import date, timedelta
sdate = date(2008, 8, 15) # start date
edate = date(2008, 9, 15) # end date
delta = edate - sdate # as timedelta
for i in range(delta.days + 1):
day = sdate + timedelta(days=i)
print(day)
The output:
2008-08-15
2008-08-16
...
2008-09-13
2008-09-14
2008-09-15
Your question asks for dates in-between but I believe you meant including the start and end points, so they are included. To remove the end date, delete the "+ 1" at the end of the range function. To remove the start date, insert a 1 argument to the beginning of the range function.
Every method in HtmlHelper class has a twin with For
suffix.
Html.Hidden takes a string as an argument that you must provide but Html.HiddenFor takes an Expression that if you view is a strongly typed view you can benefit from this and feed that method a lambda expression like this
o=>o.SomeProperty
instead of "SomeProperty" in the case of using Html.Hidden method.
var example = "I am too long string";
var result;
// Slice is JS function
result = example.slice(0, 10)+'...'; //if you need dots after the string you can add
Result variable contains "I am too l..."
If you're using Xcode 11 onwards:
Go to General
tab and add the framework in Frameworks, Libraries, and Embedded Content
section.
Important: By default it might be marked as Do Not Embed
, change it to Embed Without Signing
like shown in the image and you are good to go.
For Xcode versions below 11:
Just add the framework in Embedded Binaries
section and you are done.
Cheers!
sql = "INSERT INTO MyTable (Name) VALUES (@Name);" +
"SELECT CAST(scope_identity() AS int)";
SqlCommand cmd = new SqlCommand(sql, conn);
int newId = (int)cmd.ExecuteScalar();
$st = $data->prepare("SELECT * FROM exampleWHERE example LIKE :search LIMIT 10");
$unixtime = 1307595105;
echo $time = date("m/d/Y h:i:s A T",$unixtime);
Where
Android 3.0
In activity_main.xml
Replace in this tag i.e <android.support.constraint.ConstraintLayout>
android.support.constraint.ConstraintLayout
with
RelativeLayout
I have experienced the same problem when trying to publish my nodejs app in a private server running CentOs using root user. The same error is fired by "postinstall": "./node_modules/bower/bin/bower install" in my package.json file so the only solution that was working for me is to use both options to avoid the error:
1: use --allow-root option for bower install command
"postinstall": "./node_modules/bower/bin/bower --allow-root install"
2: use --unsafe-perm option for npm install command
npm install --unsafe-perm
I got same error. Because i used v4 alpha class names like carousel-control-next
When i changed with v3, problem solved.
Carbon has a bunch of comparison functions with mnemonic names:
Usage:
if($model->edited_at->greaterThan($model->created_at)){
// edited at is newer than created at
}
Valid for nesbot/carbon 1.36.2
if you are not sure what Carbon version you are on, run this
$composer show "nesbot/carbon"
documentation: https://carbon.nesbot.com/docs/#api-comparison
$("input[type=checkbox]").on("change", function() {
if (this.checked) {
//do your stuff
}
});
In addition to the 16/32/64 bit differences even odder things can occur.
There have been machines where sizeof(int *) will be one value, probably 4 but where sizeof(char *) is larger. Machines that naturally address words instead of bytes have to "augment" character pointers to specify what portion of the word you really want in order to properly implement the C/C++ standard.
This is now very unusual as hardware designers have learned the value of byte addressability.
Switch off compatibility view if you use IE9.
UPDATE totals
SET total = total + 1
WHERE name = 'bill';
If you want to make sure the current value is indeed 203 (and not accidently increase it again) you can also add another condition:
UPDATE totals
SET total = total + 1
WHERE name = 'bill'
AND total = 203;
This promise will not resolve if the argument of JSON.parse() can not be parsed into a JSON object.
Promise.resolve(JSON.parse('{"key":"value"}')).then(json => {
console.log(json);
}).catch(err => {
console.log(err);
});
The merge method returns the merged collection, it doesn't mutate the original collection, thus you need to do the following
$original = new Collection(['foo']);
$latest = new Collection(['bar']);
$merged = $original->merge($latest); // Contains foo and bar.
Applying the example to your code
$related = new Collection();
foreach ($question->tags as $tag)
{
$related = $related->merge($tag->questions);
}
I solved this by uninstalling and then re-installing the dnspython module with PIP.
$ pip uninstall dnspython
After the long list of files within pycache, type y to continue with the uninstall. After complete type:
$ pip install dnspython
I then ran my script and the errors were resolved.
just combine the value and the stud_name e.g. 1_sre and split the value when get it into php. Javascript seems like hammer to crack a nut. N.B. this method assumes you can edit the the html. Here is what the html might look like:
<form name='add'>
Age: <select name='age'>
<option value='1_sre'>23</option>
<option value='2_sam>24</option>
<option value='5_john>25</option>
</select>
<input type='submit' name='submit'/>
</form>
It is the equivalent to \n -> LF (Line Feed).
Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine
.
You can probably use the KeyDown event, KeyPress event or KeyUp event. I would first try the KeyDown event I think.
You can set the Handled property of the event args to stop handling the event.
There are two cases in which this error is raised.
This is a simple way to access a component's methods from other component
// This is external shared (reusable) component, so you can call its methods from other components
export default {
name: 'SharedBase',
methods: {
fetchLocalData: function(module, page){
// .....fetches some data
return { jsonData }
}
}
}
// This is your component where you can call SharedBased component's method(s)
import SharedBase from '[your path to component]';
var sections = [];
export default {
name: 'History',
created: function(){
this.sections = SharedBase.methods['fetchLocalData']('intro', 'history');
}
}
Using LINQ to xml if you are using framework 3.5
using System.Xml.Linq;
XDocument xmlFile = XDocument.Load("books.xml");
var query = from c in xmlFile.Elements("catalog").Elements("book")
select c;
foreach (XElement book in query)
{
book.Attribute("attr1").Value = "MyNewValue";
}
xmlFile.Save("books.xml");
I know this is an old post but I recently ran into a very similar problem. Unfortunately I wasn't able to use any of the alter database commands because an exclusive lock couldn't be placed. But I was never able to find an open connection to the db. I eventually had to forcefully delete the health state of the database to force it into a restoring state instead of in recovery.
'JavaType' works !!
I was trying to unmarshall (deserialize) a List in json String to ArrayList java Objects and was struggling to find a solution since days.
Below is the code that finally gave me solution.
Code:
JsonMarshallerUnmarshaller<T> {
T targetClass;
public ArrayList<T> unmarshal(String jsonString) {
ObjectMapper mapper = new ObjectMapper();
AnnotationIntrospector introspector = new JacksonAnnotationIntrospector();
mapper.getDeserializationConfig()
.withAnnotationIntrospector(introspector);
mapper.getSerializationConfig()
.withAnnotationIntrospector(introspector);
JavaType type = mapper.getTypeFactory().
constructCollectionType(
ArrayList.class,
targetclass.getClass());
try {
Class c1 = this.targetclass.getClass();
Class c2 = this.targetclass1.getClass();
ArrayList<T> temp = (ArrayList<T>)
mapper.readValue(jsonString, type);
return temp ;
} catch (JsonParseException e) {
e.printStackTrace();
} catch (JsonMappingException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return null ;
}
}
Nothing above worked, this is what worked for me:
ftype Python.File=C:\Path\to\python.exe "%1" %*
This command should be run in Command prompt launched as administrator
Warning: even if the path in this command is set to python35, if you have python36 installed it's going to set the default to python36. To prevent this, you can temporarily change the folder name from Python36
to xxPython36
, run the command and then remove the change to the Python 36 folder.
The main point is that as of December 2018 it's Scripts
not bin
.
Use one of these:
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda2/Scripts/:$PATH
export PATH=$USERPROFILE/AppData/Local/Continuum/anaconda3/Scripts/:$PATH
Use one of these:
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda2\Scripts\;%PATH%
SET PATH=%USERPROFILE%\AppData\Local\Continuum\anaconda3\Scripts\;%PATH%
Change /app
to your installation location. If you installed anaconda change Miniconda
to Anaconda
. Also, check for Script vs. bin,.
export PATH="/app/Miniconda/bin:$PATH"
You may need to run set -a
before setting the path, I think this is important if you're setting the path in a script. For example if you have your export command in a file called set_my_path.sh
, I think you'd need to do set -a; source("set_my_path.sh")
.
The set -a
will make your changes to the path persist for your session, but they are still not permanent.
For a more permanent solution add the command to ~/.bashrc
. The installers may offer to add something like this to your ~/.bashrc
file, but you can do it too (or comment it out to undo it).
Background: I installed the 64 bit versions of Anaconda 2 and 3 recently on my Windows 10 machine following the recommended installation steps in December of 2018.
ipython
, which works much better in the native Windows command line/bin
folder seems to have been replaced with Scripts
See help(Sys.sleep)
.
For example, from ?Sys.sleep
testit <- function(x)
{
p1 <- proc.time()
Sys.sleep(x)
proc.time() - p1 # The cpu usage should be negligible
}
testit(3.7)
Yielding
> testit(3.7)
user system elapsed
0.000 0.000 3.704
Here is the complete method for converting InputStream
into String
without using any third party library. Use StringBuilder
for single threaded environment otherwise use StringBuffer
.
public static String getString( InputStream is) throws IOException {
int ch;
StringBuilder sb = new StringBuilder();
while((ch = is.read()) != -1)
sb.append((char)ch);
return sb.toString();
}
DECLARE @JCnt int=null
SEt @JCnt=(SELECT COUNT( ISNUll(EmpCode,0)) FROM tbl_Employees WHERE EmpCode=1 )
UPDATE #TempCode
SET janCA= CASE WHEN @JCnt>0 THEN (SELECT SUM (ISNUll(Amount,0)) FROM tbl_Salary WHERE Code=1 )ELSE 0 END
WHERE code=1
Hamidreza's solution almost worked for me.
I noticed from experimentation that a simple tap usually has 2-5 action move events. Checking the time between action down and up was simpler and behaved more like what I expected.
private class CheckForClickTouchLister implements View.OnTouchListener {
private final static long MAX_TOUCH_DURATION = 100;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
m_DownTime = event.getEventTime(); //init time
break;
case MotionEvent.ACTION_UP:
if(event.getEventTime() - m_DownTime <= MAX_TOUCH_DURATION)
//On click action
break;
default:
break; //No-Op
}
return false;
}
It seems Yahoo server does some heuristic based on User-Agent
in a case Accept
header is set to */*
.
Accept: text/html
did the trick for me.
e.g.
wget --header="Accept: text/html" --user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10.8; rv:21.0) Gecko/20100101 Firefox/21.0" http://yahoo.com
Note: if you don't declare Accept
header then wget
automatically adds Accept:*/*
which means give me anything you have.
Most Simplest solution
from datetime import timedelta, datetime
date = datetime(2003,8,1,12,4,5)
for i in range(5):
date += timedelta(days=1)
print(date)
I'd have done it like this:
perl -e 'while (<>) {chop; $h{$_}++;} for $k (keys %h) {print "$k $h{$k}\n";}' ip_addresses
but uniq might work for you.
If you don't need ticks and such (e.g. for plotting qualitative illustrations) you could also use this quick workaround:
Make the axis invisible (e.g. with plt.gca().axison = False
) and then draw them manually with plt.arrow
.
You can "abort" a task by running it on a thread you control and aborting that thread. This causes the task to complete in a faulted state with a ThreadAbortException
. You can control thread creation with a custom task scheduler, as described in this answer. Note that the caveat about aborting a thread applies.
(If you don't ensure the task is created on its own thread, aborting it would abort either a thread-pool thread or the thread initiating the task, neither of which you typically want to do.)
The TTFB is not the time to first byte of the body of the response (i.e., the useful data, such as: json, xml, etc.), but rather the time to first byte of the response received from the server. This byte is the start of the response headers.
For example, if the server sends the headers before doing the hard work (like heavy SQL), you will get a very low TTFB, but it isn't "true".
In your case, TTFB represents the time you spend processing data on the server.
To reduce the TTFB, you need to do the server-side work faster.
DTO
is an abbreviation for Data Transfer Object, so it is used to transfer the data between classes and modules of your application.
DTO
should only contain private fields for your data, getters, setters, and constructors.DTO
is not recommended to add business logic methods to such classes, but it is OK to add some util methods.DAO
is an abbreviation for Data Access Object, so it should encapsulate the logic for retrieving, saving and updating data in your data storage (a database, a file-system, whatever).
Here is an example of how the DAO and DTO interfaces would look like:
interface PersonDTO {
String getName();
void setName(String name);
//.....
}
interface PersonDAO {
PersonDTO findById(long id);
void save(PersonDTO person);
//.....
}
The MVC
is a wider pattern. The DTO/DAO would be your model in the MVC pattern.
It tells you how to organize the whole application, not just the part responsible for data retrieval.
As for the second question, if you have a small application it is completely OK, however, if you want to follow the MVC pattern it would be better to have a separate controller, which would contain the business logic for your frame in a separate class and dispatch messages to this controller from the event handlers.
This would separate your business logic from the view.
I had this problem when I was trying to run commands through CLI.
It was a problem with system looking at the JRE folder i.e.
D:\Program Files\Java\jre8\bin
. If we look in there, there is no Tools.jar
, hence the error.
You need to find where the JDK
is, in my case: D:\Program Files\Java\jdk1.8.0_11
, and if you look in the lib
directory, you will see Tools.jar
.
What I did I created a new environment variable JAVA_HOME
:
And then you need to edit your PATH variable to include JAVA_HOME, i.e. %JAVA_HOME%/bin;
Re-open command prompt and should run.
Can I recommend doing it this way, define your test like this:
@RunWith(SpringJUnit4ClassRunner.class)
@TestExecutionListeners({
TestPreperationExecutionListener.class
})
@Transactional
@ActiveProfiles(profiles = "localtest")
@ContextConfiguration
public class TestContext {
@Test
public void testContext(){
}
@Configuration
@PropertySource("classpath:/myprops.properties")
@ImportResource({"classpath:context.xml" })
public static class MyContextConfiguration{
}
}
with the following content in myprops.properties file:
spring.profiles.active=localtest
With this your second properties file should get resolved:
META-INF/spring/config_${spring.profiles.active}.properties
little detail more
infix operator ^^ { associativity left precedence 160 }
func ^^ (radix: Int, power: Int) -> Int {
return Int(pow(CGFloat(radix), CGFloat(power)))
}
check if file exist in side the document/catchimage path :
NSString *stringPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0];
NSString *tempName = [NSString stringWithFormat:@"%@/catchimage/%@.png",stringPath,@"file name"];
NSLog(@"%@",temName);
if([[NSFileManager defaultManager] fileExistsAtPath:temName]){
// ur code here
} else {
// ur code here**
}
i was facing this problem and i checked all the answers and nothing worked for me, but then i reset mail.php and didn't touch it and set the mail server from .env file and it worked perfectly, hope this will save the time for someone :).
For my future self who comes here via Google:
train_test_split
is now in model_selection
, hence:
from sklearn.model_selection import train_test_split
# given:
# features: xs
# ground truth: ys
x_train, x_test, y_train, y_test = train_test_split(xs, ys,
test_size=0.33,
random_state=0,
stratify=ys)
is the way to use it. Setting the random_state
is desirable for reproducibility.
@commonpike's answer is "the right one", but as he goes on to comment...
most browsers nowadays just support
Object.keys()
Yeah.. Object.keys()
is WAY better.
But what's even better? Duh, it's it in coffeescript
!
sortedKeys = (x) -> Object.keys(x).sort (a,b) -> x[a] - x[b]
sortedKeys
'a' : 1
'b' : 3
'c' : 4
'd' : -1
[ 'd', 'a', 'b', 'c' ]
use this function that i've made:
function buildObject($class,$data){
$object = new $class;
foreach($data as $key=>$value){
if(property_exists($class,$key)){
$object->{'set'.ucfirst($key)}($value);
}
}
return $object;
}
Usage:
$myObject = buildObject('MyClassName',$myArray);
You could use a temp table which the stored procedure expects to exist. This will work on older versions of SQL Server, which do not support XML etc.
CREATE TABLE #temp
(INT myid)
GO
CREATE PROC myproc
AS
BEGIN
DELETE YourTable
FROM YourTable
LEFT OUTER JOIN #temp T ON T.myid=s.id
WHERE s.id IS NULL
END
This problem has been bothering me as well; this is why I have created this project.
With it you can do:
final ThrowingFunction<String, Integer> f = yourMethodReferenceHere;
There are a totla of 39 interfaces defined by the JDK which have such a Throwing
equivalent; those are all @FunctionalInterface
s used in streams (the base Stream
but also IntStream
, LongStream
and DoubleStream
).
And as each of them extend their non throwing counterpart, you can directly use them in lambdas as well:
myStringStream.map(f) // <-- works
The default behavior is that when your throwing lambda throws a checked exception, a ThrownByLambdaException
is thrown with the checked exception as the cause. You can therefore capture that and get the cause.
Other features are available as well.
Look at the File javadoc, the method createNewFile will create the file only if it doesn't exist, and will return a boolean to say if the file was created.
You may also use the exists() method:
int i = 0;
String filename = Integer.toString(i);
File f = new File(filename);
while (f.exists()) {
i++;
filename = Integer.toString(i);
f = new File(filename);
}
f.createNewFile();
System.out.println("File in use: " + f);
If you need binary mode, you'll need to do it the hard way:
s = File.open(filename, 'rb') { |f| f.read }
If not, shorter and sweeter is:
s = IO.read(filename)
Put the threads in a list and then use the Join method
threads = []
t = Thread(...)
threads.append(t)
...repeat as often as necessary...
# Start all threads
for x in threads:
x.start()
# Wait for all of them to finish
for x in threads:
x.join()
To complement Justus Thane's helpful answer:
As Joey notes in a comment, PowerShell has a powerful, regex-based -split
operator.
-split '...'
), -split
behaves like awk
's default field splitting, which means that:
In PowerShell v4+ an expression-based - and therefore faster - alternative to the ForEach-Object
cmdlet became available: the .ForEach()
array (collection) method, as described in this blog post (alongside the .Where()
method, a more powerful, expression-based alternative to Where-Object
).
Here's a solution based on these features:
PS> (-split ' One for the money ').ForEach({ "token: [$_]" })
token: [One]
token: [for]
token: [the]
token: [money]
Note that the leading and trailing whitespace was ignored, and that the multiple spaces between One
and for
were treated as a single separator.
I was not even concentrating, here is how to do it
$DOCDIR = [Environment]::GetFolderPath("MyDocuments")
$TARGETDIR = '$DOCDIR\MatchedLog'
if(!(Test-Path -Path $TARGETDIR )){
New-Item -ItemType directory -Path $TARGETDIR
}
If you use linq and want to keep your code short, I recommand to always use !=null
And this is why:
Let imagine we have some class Foo
with a nullable double variable SomeDouble
public class Foo
{
public double? SomeDouble;
//some other properties
}
If somewhere in our code we want to get all Foo with a non null SomeDouble values from a collection of Foo (assuming some foos in the collection can be null too), we end up with at least three way to write our function (if we use C# 6) :
public IEnumerable<Foo> GetNonNullFoosWithSomeDoubleValues(IEnumerable<Foo> foos)
{
return foos.Where(foo => foo?.SomeDouble != null);
return foos.Where(foo=>foo?.SomeDouble.HasValue); // compile time error
return foos.Where(foo=>foo?.SomeDouble.HasValue == true);
return foos.Where(foo=>foo != null && foo.SomeDouble.HasValue); //if we don't use C#6
}
And in this kind of situation I recommand to always go for the shorter one
It looks like you're just missing an opening double-quote. Try:
if Verbose:
print("Building internam Index for %d tile(s) ..." % len(inputTiles), end=' ')
Use git archive branch-index | tar -x -C your-folder-on-PC
to clone a branch to another folder. I think, then you can copy any file that you need
With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.
I use a method to add or remove values in the formArray. It may be a bad approch, but it works !
component.html
<div *ngFor="let choice of checks; let i=index" class="col-md-2">
<label>
<input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
{{choice.description}}
</label>
</div>
component.ts
// For example, an array of choices
public checks: Array<ChoiceClass> = [
{description: 'descr1', value: 'value1'},
{description: "descr2", value: 'value2'},
{description: "descr3", value: 'value3'}
];
initModelForm(): FormGroup{
return this._fb.group({
otherControls: [''],
// The formArray, empty
myChoices: new FormArray([]),
}
}
onCheckChange(event) {
const formArray: FormArray = this.myForm.get('myChoices') as FormArray;
/* Selected */
if(event.target.checked){
// Add a new control in the arrayForm
formArray.push(new FormControl(event.target.value));
}
/* unselected */
else{
// find the unselected element
let i: number = 0;
formArray.controls.forEach((ctrl: FormControl) => {
if(ctrl.value == event.target.value) {
// Remove the unselected element from the arrayForm
formArray.removeAt(i);
return;
}
i++;
});
}
}
When I submit my form, for example my model looks like:
otherControls : "foo",
myChoices : ['value1', 'value2']
Only one thing is missing, a function to fill the formArray if your model already has checked values.
Because none of the answers above worked for me, I write here the solution that finally solved my problem on Ubuntu. My problem was:
I did the following steps:
conda activate MyEnv
jupyter notebook
Although MyEnv
was active in the terminal and had an asterix when writing conda env list
, but jupyter notebook was started with the base environment.
Installing nb_conda
and ipykernel
didn't solve the problem for me either. Additionally, the conda
tab wasn't appearing in jupyter notebook and also clicking on the kernels or going to the menu Kernel->Change Kernel
didn't show the kernel MyEnv
.
Solution was: install the jupyter_environment_kernel in MyEnv
environment:
pip install environment_kernels
After that when starting jupyter notebook, it is started with the right environment. You can also switch between environments without stopping the kernel, by going to the menu Kernel->Change Kernel
and selecting the desired kernel.
sth's solution didn't work for me
because in ...
Imaging/PIL/Image.pyc line 1423 -> raise KeyError(ext) # unknown extension
It was trying to detect the format from the extension in the filename , which doesn't exist in StringIO case
You can bypass the format detection by setting the format yourself in a parameter
import StringIO
output = StringIO.StringIO()
format = 'PNG' # or 'JPEG' or whatever you want
image.save(output, format)
contents = output.getvalue()
output.close()
we can use \b as a word boundary and then; \b\d+\b
just change wb to w
outfile=open('./immates.csv','wb')
to
outfile=open('./immates.csv','w')
My suggestion is the log file should always be logged above the root context of the webApp, so in case we redeploy the webApp, we don't want to override the existing log files.
Add this, I think it is what you're looking for:
<meta name = "format-detection" content = "telephone=no">