@Wardenclyffe and @SColvin, you both are trying to save image using the canvas, not by using canvas's context. both you should try to ctx.toDataURL(); Try This:
var canvas1 = document.getElementById("yourCanvasId"); <br>
var ctx = canvas1.getContext("2d");<br>
var img = new Image();<br>
img.src = ctx.toDataURL('image/png');<br>
ctx.drawImage(img,200,150);<br>
Also you may refer to following links:
http://tutorials.jenkov.com/html5-canvas/todataurl.html
http://www.w3.org/TR/2012/WD-html5-author-20120329/the-canvas-element.html#the-canvas-element
psoul's excellent post answers to your question so I won't replicate his good work, but I feel it'd help to explain why this is at once a perfectly valid but also terribly silly question. After all, this is a place to learn, right?
Modern computer programs are produced through a series of conversions, starting with the input of a human-readable body of text instructions (called "source code") and ending with a computer-readable body of instructions (called alternatively "binary" or "machine code").
The way that a computer runs a set of machine code instructions is ultimately very simple. Each action a processor can take (e.g., read from memory, add two values) is represented by a numeric code. If I told you that the number 1 meant scream and the number 2 meant giggle, and then held up cards with either 1 or 2 on them expecting you to scream or giggle accordingly, I would be using what is essentially the same system a computer uses to operate.
A binary file is just a set of those codes (usually call "op codes") and the information ("arguments") that the op codes act on.
Now, assembly language is a computer language where each command word in the language represents exactly one op-code on the processor. There is a direct 1:1 translation between an assembly language command and a processor op-code. This is why coding assembly for an x386 processor is different than coding assembly for an ARM processor.
Disassembly is simply this: a program reads through the binary (the machine code), replacing the op-codes with their equivalent assembly language commands, and outputs the result as a text file. It's important to understand this; if your computer can read the binary, then you can read the binary too, either manually with an op-code table in your hand (ick) or through a disassembler.
Disassemblers have some new tricks and all, but it's important to understand that a disassembler is ultimately a search and replace mechanism. Which is why any EULA which forbids it is ultimately blowing hot air. You can't at once permit the computer reading the program data and also forbid the computer reading the program data.
(Don't get me wrong, there have been attempts to do so. They work as well as DRM on song files.)
However, there are caveats to the disassembly approach. Variable names are non-existent; such a thing doesn't exist to your CPU. Library calls are confusing as hell and often require disassembling further binaries. And assembly is hard as hell to read in the best of conditions.
Most professional programmers can't sit and read assembly language without getting a headache. For an amateur it's just not going to happen.
Anyway, this is a somewhat glossed-over explanation, but I hope it helps. Everyone can feel free to correct any misstatements on my part; it's been a while. ;)
I got this error when I set ft_min_word_len = 2
in my.cnf
, which lowers the minimum word length in a full text index to 2, from the default of 4.
Repairing the table fixed the problem.
In your git dir, suppose you have sync all changes.
rm -rf .git
rm -rf .gitmodules
Then do:
git init
git submodule add url_to_repo projectfolder
There are some issues worth noticing if you're dealing with classes that are persisted using an Object-Relationship Mapper (ORM) like Hibernate, if you didn't think this was unreasonably complicated already!
Lazy loaded objects are subclasses
If your objects are persisted using an ORM, in many cases you will be dealing with dynamic proxies to avoid loading object too early from the data store. These proxies are implemented as subclasses of your own class. This means thatthis.getClass() == o.getClass()
will return false
. For example:
Person saved = new Person("John Doe");
Long key = dao.save(saved);
dao.flush();
Person retrieved = dao.retrieve(key);
saved.getClass().equals(retrieved.getClass()); // Will return false if Person is loaded lazy
If you're dealing with an ORM, using o instanceof Person
is the only thing that will behave correctly.
Lazy loaded objects have null-fields
ORMs usually use the getters to force loading of lazy loaded objects. This means that person.name
will be null
if person
is lazy loaded, even if person.getName()
forces loading and returns "John Doe". In my experience, this crops up more often in hashCode()
and equals()
.
If you're dealing with an ORM, make sure to always use getters, and never field references in hashCode()
and equals()
.
Saving an object will change its state
Persistent objects often use a id
field to hold the key of the object. This field will be automatically updated when an object is first saved. Don't use an id field in hashCode()
. But you can use it in equals()
.
A pattern I often use is
if (this.getId() == null) {
return this == other;
}
else {
return this.getId().equals(other.getId());
}
But: you cannot include getId()
in hashCode()
. If you do, when an object is persisted, its hashCode
changes. If the object is in a HashSet
, you'll "never" find it again.
In my Person
example, I probably would use getName()
for hashCode
and getId()
plus getName()
(just for paranoia) for equals()
. It's okay if there are some risk of "collisions" for hashCode()
, but never okay for equals()
.
hashCode()
should use the non-changing subset of properties from equals()
To start with you can't do this:
having rid!=MAX(rid)
The HAVING clause can only contain things which are attributes of the aggregate groups.
In addition, 1, 2, 3
is not valid in GROUP BY in SQL Server - I think that's only valid in ORDER BY.
Can you explain why this isn't what you are looking for:
select
LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound,
MAX(qvalues.rid)
from batchinfo join qvalues on batchinfo.rowid=qvalues.rowid
where LEN(datapath)>4
group by LEFT(SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000), PATINDEX('%[^0-9]%', SUBSTRING(batchinfo.datapath, PATINDEX('%[0-9][0-9][0-9]%', batchinfo.datapath), 8000))-1),
qvalues.name,
qvalues.compound
Format(Now(), "yyyy-MM-dd hh:mm:ss")
These are the directories that gcc looks in by default for the specified header files ( given that the header files are included in chevrons <>); 1. /usr/local/include/ --used for 3rd party header files. 2. /usr/include/ -- used for system header files.
If in case you decide to put your custom header file in a place other than the above mentioned directories, you can include them as follows: 1. using quotes ("./custom_header_files/foo.h") with files path, instead of chevrons in the include statement. 2. using the -I switch when compiling the code. gcc -I /home/user/custom_headers/ -c foo.c -p foo.o Basically the -I switch tells the compiler to first look in the directory specified with the -I switch ( before it checks the standard directories).When using the -I switch the header files may be included using chevrons.
As others have said, you could use Object.keys()
, but who cares about older browsers, right?
Well, I do.
Try this. array_keys
from PHPJS ports PHP's handy array_keys
function, so it can be used in JavaScript.
At a glance, it uses Object.keys
if supported, but it handles the case where it isn't very easily. It even includes filtering the keys based on values you might be looking for (optional) and a toggle for whether or not to use strict comparison ===
versus typecasting comparison ==
(optional).
you have to iterate gridview Rows
for (int count = 0; count < grd.Rows.Count; count++)
{
if (((CheckBox)grd.Rows[count].FindControl("yourCheckboxID")).Checked)
{
((Label)grd.Rows[count].FindControl("labelID")).Text
}
}
Most probably it has to do with caching on the device. Catching the exception and ignoring is not nice but my problem was fixed and it seems to work.
Have you tried just going: git commit -m "Message here"
So in your case:
git commit -m "Form validation added"
After you've added your files of course.
If you want to toggle a class to an element using native solution, you could try this suggestion. I have tasted it in different cases, with or without other classes onto the element, and I think it works pretty much:
(function(objSelector, objClass){
document.querySelectorAll(objSelector).forEach(function(o){
o.addEventListener('click', function(e){
var $this = e.target,
klass = $this.className,
findClass = new RegExp('\\b\\s*' + objClass + '\\S*\\s?', 'g');
if( !findClass.test( $this.className ) )
if( klass )
$this.className = klass + ' ' + objClass;
else
$this.setAttribute('class', objClass);
else
{
klass = klass.replace( findClass, '' );
if(klass) $this.className = klass;
else $this.removeAttribute('class');
}
});
});
})('.yourElemetnSelector', 'yourClass');
If you are using a console application and you are pumping messages, can't you use the WM_QUIT message?
If you are working with DATE columns (or can cast them as date columns), try DATEDIFF() and then multiply by 24 hours, 60 min, 60 secs (since DATEDIFF returns diff in days). From MySQL:
http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
for example:
mysql> SELECT DATEDIFF('2007-12-31 23:59:59','2007-12-30 00:00:00') * 24*60*60
Arrays.asList(myArray).contains(false)
A safer way to resolve conflicts is to use git-mediate (the common solutions suggested here are quite error prone imho).
See this post for a quick intro on how to use it.
This question is vague, but if you want to make the image with Javascript. It is simple.
function loadImages(src) {
if (document.images) {
img1 = new Image();
img1.src = src;
}
loadImages("image.jpg");
The image will be requested but until you show it it will never be displayed. great for pre loading images you expect to be requests but delaying it until the document is loaded.
function EmailValidation($email)
{
$email = htmlspecialchars(stripslashes(strip_tags($email))); //parse unnecessary characters to prevent exploits
if (eregi('[a-z||0-9]@[a-z||0-9].[a-z]', $email)) {
//checks to make sure the email address is in a valid format
$domain = explode( "@", $email ); //get the domain name
if (@fsockopen ($domain[1],80,$errno,$errstr,3)) {
//if the connection can be established, the email address is probably valid
echo "Domain Name is valid ";
return true;
} else {
echo "Con not a email domian";
return false; //if a connection cannot be established return false
}
return false; //if email address is an invalid format return false
}
}
If I understand your question correctly:
for elem in doc.findall('timeSeries/values/value'):
print elem.get('dateTime'), elem.text
or if you prefer (and if there is only one occurrence of timeSeries/values
:
values = doc.find('timeSeries/values')
for value in values:
print value.get('dateTime'), elem.text
The findall()
method returns a list of all matching elements, whereas find()
returns only the first matching element. The first example loops over all the found elements, the second loops over the child elements of the values
element, in this case leading to the same result.
I don't see where the problem with not finding timeSeries
comes from however. Maybe you just forgot the getroot()
call? (note that you don't really need it because you can work from the elementtree itself too, if you change the path expression to for example /timeSeriesResponse/timeSeries/values
or //timeSeries/values
)
With user defined functions, you have to declare every parameter, even if they have a default value.
The following would execute successfully:
IF dbo.CheckIfSFExists( 23, default ) = 0
SET @retValue = 'bla bla bla;
great work on this class. Simple and easy to use. I modified the class to include a title in the first row of the export; figured I would share:
use:
CsvExport myExport = new CsvExport();
myExport.addTitle = String.Format("Name: {0},{1}", lastName, firstName));
class:
public class CsvExport
{
List<string> fields = new List<string>();
public string addTitle { get; set; } // string for the first row of the export
List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
Dictionary<string, object> currentRow
{
get
{
return rows[rows.Count - 1];
}
}
public object this[string field]
{
set
{
if (!fields.Contains(field)) fields.Add(field);
currentRow[field] = value;
}
}
public void AddRow()
{
rows.Add(new Dictionary<string, object>());
}
string MakeValueCsvFriendly(object value)
{
if (value == null) return "";
if (value is Nullable && ((INullable)value).IsNull) return "";
if (value is DateTime)
{
if (((DateTime)value).TimeOfDay.TotalSeconds == 0)
return ((DateTime)value).ToString("yyyy-MM-dd");
return ((DateTime)value).ToString("yyyy-MM-dd HH:mm:ss");
}
string output = value.ToString();
if (output.Contains(",") || output.Contains("\""))
output = '"' + output.Replace("\"", "\"\"") + '"';
return output;
}
public string Export()
{
StringBuilder sb = new StringBuilder();
// if there is a title
if (!string.IsNullOrEmpty(addTitle))
{
// escape chars that would otherwise break the row / export
char[] csvTokens = new[] { '\"', ',', '\n', '\r' };
if (addTitle.IndexOfAny(csvTokens) >= 0)
{
addTitle = "\"" + addTitle.Replace("\"", "\"\"") + "\"";
}
sb.Append(addTitle).Append(",");
sb.AppendLine();
}
// The header
foreach (string field in fields)
sb.Append(field).Append(",");
sb.AppendLine();
// The rows
foreach (Dictionary<string, object> row in rows)
{
foreach (string field in fields)
sb.Append(MakeValueCsvFriendly(row[field])).Append(",");
sb.AppendLine();
}
return sb.ToString();
}
public void ExportToFile(string path)
{
File.WriteAllText(path, Export());
}
public byte[] ExportToBytes()
{
return Encoding.UTF8.GetBytes(Export());
}
}
You can make use of DecimalFormat
to give you the style you wish.
DecimalFormat df = new DecimalFormat("0.00E0");
double number = 1.2975118E7;
System.out.println(df.format(number)); // prints 1.30E7
Since it's in scientific notation, you won't be able to get the number any smaller than 107 without losing that many orders of magnitude of accuracy.
(Background: I have some experience implementing C and C++ compilers.)
Variable-length arrays in C99 were basically a misstep. In order to support VLAs, C99 had to make the following concessions to common sense:
sizeof x
is no longer always a compile-time constant; the compiler must sometimes generate code to evaluate a sizeof
-expression at runtime.
Allowing two-dimensional VLAs (int A[x][y]
) required a new syntax for declaring functions that take 2D VLAs as parameters: void foo(int n, int A[][*])
.
Less importantly in the C++ world, but extremely important for C's target audience of embedded-systems programmers, declaring a VLA means chomping an arbitrarily large chunk of your stack. This is a guaranteed stack-overflow and crash. (Anytime you declare int A[n]
, you're implicitly asserting that you have 2GB of stack to spare. After all, if you know "n
is definitely less than 1000 here", then you would just declare int A[1000]
. Substituting the 32-bit integer n
for 1000
is an admission that you have no idea what the behavior of your program ought to be.)
Okay, so let's move to talking about C++ now. In C++, we have the same strong distinction between "type system" and "value system" that C89 does… but we've really started to rely on it in ways that C has not. For example:
template<typename T> struct S { ... };
int A[n];
S<decltype(A)> s; // equivalently, S<int[n]> s;
If n
weren't a compile-time constant (i.e., if A
were of variably modified type), then what on earth would be the type of S
? Would S
's type also be determined only at runtime?
What about this:
template<typename T> bool myfunc(T& t1, T& t2) { ... };
int A1[n1], A2[n2];
myfunc(A1, A2);
The compiler must generate code for some instantiation of myfunc
. What should that code look like? How can we statically generate that code, if we don't know the type of A1
at compile time?
Worse, what if it turns out at runtime that n1 != n2
, so that !std::is_same<decltype(A1), decltype(A2)>()
? In that case, the call to myfunc
shouldn't even compile, because template type deduction should fail! How could we possibly emulate that behavior at runtime?
Basically, C++ is moving in the direction of pushing more and more decisions into compile-time: template code generation, constexpr
function evaluation, and so on. Meanwhile, C99 was busy pushing traditionally compile-time decisions (e.g. sizeof
) into the runtime. With this in mind, does it really even make sense to expend any effort trying to integrate C99-style VLAs into C++?
As every other answerer has already pointed out, C++ provides lots of heap-allocation mechanisms (std::unique_ptr<int[]> A = new int[n];
or std::vector<int> A(n);
being the obvious ones) when you really want to convey the idea "I have no idea how much RAM I might need." And C++ provides a nifty exception-handling model for dealing with the inevitable situation that the amount of RAM you need is greater than the amount of RAM you have. But hopefully this answer gives you a good idea of why C99-style VLAs were not a good fit for C++ — and not really even a good fit for C99. ;)
For more on the topic, see N3810 "Alternatives for Array Extensions", Bjarne Stroustrup's October 2013 paper on VLAs. Bjarne's POV is very different from mine; N3810 focuses more on finding a good C++ish syntax for the things, and on discouraging the use of raw arrays in C++, whereas I focused more on the implications for metaprogramming and the typesystem. I don't know if he considers the metaprogramming/typesystem implications solved, solvable, or merely uninteresting.
A good blog post that hits many of these same points is "Legitimate Use of Variable Length Arrays" (Chris Wellons, 2019-10-27).
For completeness, write_csv()
from the readr
package is faster and never writes row names
# install.packages('readr', dependencies = TRUE)
library(readr)
write_csv(t, "t.csv")
If you need to write big data out, use fwrite()
from the data.table
package. It's much faster than both write.csv
and write_csv
# install.packages('data.table')
library(data.table)
fwrite(t, "t.csv")
Below is a benchmark that Edouard published on his site
microbenchmark(write.csv(data, "baseR_file.csv", row.names = F),
write_csv(data, "readr_file.csv"),
fwrite(data, "datatable_file.csv"),
times = 10, unit = "s")
## Unit: seconds
## expr min lq mean median uq max neval
## write.csv(data, "baseR_file.csv", row.names = F) 13.8066424 13.8248250 13.9118324 13.8776993 13.9269675 14.3241311 10
## write_csv(data, "readr_file.csv") 3.6742610 3.7999409 3.8572456 3.8690681 3.8991995 4.0637453 10
## fwrite(data, "datatable_file.csv") 0.3976728 0.4014872 0.4097876 0.4061506 0.4159007 0.4355469 10
I would use:
awk 'FNR <= 1' file_*.txt
As @Kusalananda points out there are many ways to capture the first line in command line but using the head -n 1
may not be the best option when using wildcards since it will print additional info. Changing 'FNR == i'
to 'FNR <= i'
allows to obtain the first i lines.
For example, if you have n files named file_1.txt, ... file_n.txt:
awk 'FNR <= 1' file_*.txt
hello
...
bye
But with head
wildcards print the name of the file:
head -1 file_*.txt
==> file_1.csv <==
hello
...
==> file_n.csv <==
bye
The issue seems to be that you are adding the deffered.promise
when deffered
is itself the promise you should be adding:
Try changing to promises.push(deffered);
so you don't add the unwrapped promise to the array.
UploadService.uploadQuestion = function(questions){
var promises = [];
for(var i = 0 ; i < questions.length ; i++){
var deffered = $q.defer();
var question = questions[i];
$http({
url : 'upload/question',
method: 'POST',
data : question
}).
success(function(data){
deffered.resolve(data);
}).
error(function(error){
deffered.reject();
});
promises.push(deffered);
}
return $q.all(promises);
}
I prefer parsing results of dumpsys window windows
over dumpsys activity
adb shell dumpsys window windows | grep -E 'mCurrentFocus|mFocusedApp'
Keyguard or Recent tasks list used to not show up as Activities but you were able to see them with mCurrentFocus
. I have explained why in this answer.
If you need in different Layer :
Create a Static Class and expose all config properties on that layer as below :
using Microsoft.Extensions.Configuration;_x000D_
using System.IO;_x000D_
_x000D_
namespace Core.DAL_x000D_
{_x000D_
public static class ConfigSettings_x000D_
{_x000D_
public static string conStr1 { get ; }_x000D_
static ConfigSettings()_x000D_
{_x000D_
var configurationBuilder = new ConfigurationBuilder();_x000D_
string path = Path.Combine(Directory.GetCurrentDirectory(), "appsettings.json");_x000D_
configurationBuilder.AddJsonFile(path, false);_x000D_
conStr1 = configurationBuilder.Build().GetSection("ConnectionStrings:ConStr1").Value;_x000D_
}_x000D_
}_x000D_
}
_x000D_
You can use an OFFSET
in a LIMIT
command:
SELECT * FROM aTable LIMIT 1 OFFSET 99
in case your table has 100 rows this return the last row without relying on a primary_key
You need geopy
pip install geopy
and then:
from geopy.geocoders import Nominatim
geolocator = Nominatim()
location = geolocator.reverse("48.8588443, 2.2943506")
print(location.address)
to get more information:
print (location.raw)
{'place_id': '24066644', 'osm_id': '2387784956', 'lat': '41.442115', 'lon': '-8.2939909', 'boundingbox': ['41.442015', '41.442215', '-8.2940909', '-8.2938909'], 'address': {'country': 'Portugal', 'suburb': 'Oliveira do Castelo', 'house_number': '99', 'city_district': 'Oliveira do Castelo', 'country_code': 'pt', 'city': 'Oliveira, São Paio e São Sebastião', 'state': 'Norte', 'state_district': 'Ave', 'pedestrian': 'Rua Doutor Avelino Germano', 'postcode': '4800-443', 'county': 'Guimarães'}, 'osm_type': 'node', 'display_name': '99, Rua Doutor Avelino Germano, Oliveira do Castelo, Oliveira, São Paio e São Sebastião, Guimarães, Braga, Ave, Norte, 4800-443, Portugal', 'licence': 'Data © OpenStreetMap contributors, ODbL 1.0. http://www.openstreetmap.org/copyright'}
Just use this script to dynamically backup all databases on the server. Then create batch file according to the article. It is usefull to create two batch files, one for full backup a and one for diff backup. Then Create two tasks in Task Scheduler, one for full and one for diff.
-- // Copyright © Microsoft Corporation. All Rights Reserved.
-- // This code released under the terms of the
-- // Microsoft Public License (MS-PL, http://opensource.org/licenses/ms-pl.html.)
USE [master]
GO
/****** Object: StoredProcedure [dbo].[sp_BackupDatabases] ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
-- =============================================
-- Author: Microsoft
-- Create date: 2010-02-06
-- Description: Backup Databases for SQLExpress
-- Parameter1: databaseName
-- Parameter2: backupType F=full, D=differential, L=log
-- Parameter3: backup file location
-- =============================================
CREATE PROCEDURE [dbo].[sp_BackupDatabases]
@databaseName sysname = null,
@backupType CHAR(1),
@backupLocation nvarchar(200)
AS
SET NOCOUNT ON;
DECLARE @DBs TABLE
(
ID int IDENTITY PRIMARY KEY,
DBNAME nvarchar(500)
)
-- Pick out only databases which are online in case ALL databases are chosen to be backed up
-- If specific database is chosen to be backed up only pick that out from @DBs
INSERT INTO @DBs (DBNAME)
SELECT Name FROM master.sys.databases
where state=0
AND name=@DatabaseName
OR @DatabaseName IS NULL
ORDER BY Name
-- Filter out databases which do not need to backed up
IF @backupType='F'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','AdventureWorks')
END
ELSE IF @backupType='D'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE IF @backupType='L'
BEGIN
DELETE @DBs where DBNAME IN ('tempdb','Northwind','pubs','master','AdventureWorks')
END
ELSE
BEGIN
RETURN
END
-- Declare variables
DECLARE @BackupName varchar(100)
DECLARE @BackupFile varchar(100)
DECLARE @DBNAME varchar(300)
DECLARE @sqlCommand NVARCHAR(1000)
DECLARE @dateTime NVARCHAR(20)
DECLARE @Loop int
-- Loop through the databases one by one
SELECT @Loop = min(ID) FROM @DBs
WHILE @Loop IS NOT NULL
BEGIN
-- Database Names have to be in [dbname] format since some have - or _ in their name
SET @DBNAME = '['+(SELECT DBNAME FROM @DBs WHERE ID = @Loop)+']'
-- Set the current date and time n yyyyhhmmss format
SET @dateTime = REPLACE(CONVERT(VARCHAR, GETDATE(),101),'/','') + '_' + REPLACE(CONVERT(VARCHAR, GETDATE(),108),':','')
-- Create backup filename in path\filename.extension format for full,diff and log backups
IF @backupType = 'F'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_FULL_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'D'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_DIFF_'+ @dateTime+ '.BAK'
ELSE IF @backupType = 'L'
SET @BackupFile = @backupLocation+REPLACE(REPLACE(@DBNAME, '[',''),']','')+ '_LOG_'+ @dateTime+ '.TRN'
-- Provide the backup a name for storing in the media
IF @backupType = 'F'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' full backup for '+ @dateTime
IF @backupType = 'D'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' differential backup for '+ @dateTime
IF @backupType = 'L'
SET @BackupName = REPLACE(REPLACE(@DBNAME,'[',''),']','') +' log backup for '+ @dateTime
-- Generate the dynamic SQL command to be executed
IF @backupType = 'F'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'D'
BEGIN
SET @sqlCommand = 'BACKUP DATABASE ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH DIFFERENTIAL, INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
IF @backupType = 'L'
BEGIN
SET @sqlCommand = 'BACKUP LOG ' +@DBNAME+ ' TO DISK = '''+@BackupFile+ ''' WITH INIT, NAME= ''' +@BackupName+''', NOSKIP, NOFORMAT'
END
-- Execute the generated SQL command
EXEC(@sqlCommand)
-- Goto the next database
SELECT @Loop = min(ID) FROM @DBs where ID>@Loop
END
And batch file can look like this:
sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='F'" >> c:\Dropbox\backup\DB\full.log 2>&1
and
sqlcmd -S localhost\myDB -Q "EXEC sp_BackupDatabases @backupLocation='c:\Dropbox\backup\DB\', @backupType='D'" >> c:\Dropbox\backup\DB\diff.log 2>&1
The advantage of this method is that you don't need to change anything if you add new database or delete a database, you don't even need to list the databases in the script. Answer from JohnB is better/simpler for server with one database, this approach is more suitable for multi database servers.
Use Instant to compute microseconds since Epoch:
val instant = Instant.now();
val currentTimeMicros = instant.getEpochSecond() * 1000_000 + instant.getNano() / 1000;
To clarify the problem with @@Identity
:
For instance, if you insert a table and that table has triggers doing inserts, @@Identity
will return the id from the insert in the trigger (a log_id
or something), while scope_identity()
will return the id from the insert in the original table.
So if you don't have any triggers, scope_identity()
and @@identity
will return the same value. If you have triggers, you need to think about what value you'd like.
For full numbers (non-floats) in Angular you can use:
if (Number.isInteger(yourVariable)) {
...
}
Here you can find also add watermark codes in this class :
public class ImageProcessor
{
public Bitmap Resize(Bitmap image, int newWidth, int newHeight, string message)
{
try
{
Bitmap newImage = new Bitmap(newWidth, Calculations(image.Width, image.Height, newWidth));
using (Graphics gr = Graphics.FromImage(newImage))
{
gr.SmoothingMode = SmoothingMode.AntiAlias;
gr.InterpolationMode = InterpolationMode.HighQualityBicubic;
gr.PixelOffsetMode = PixelOffsetMode.HighQuality;
gr.DrawImage(image, new Rectangle(0, 0, newImage.Width, newImage.Height));
var myBrush = new SolidBrush(Color.FromArgb(70, 205, 205, 205));
double diagonal = Math.Sqrt(newImage.Width * newImage.Width + newImage.Height * newImage.Height);
Rectangle containerBox = new Rectangle();
containerBox.X = (int)(diagonal / 10);
float messageLength = (float)(diagonal / message.Length * 1);
containerBox.Y = -(int)(messageLength / 1.6);
Font stringFont = new Font("verdana", messageLength);
StringFormat sf = new StringFormat();
float slope = (float)(Math.Atan2(newImage.Height, newImage.Width) * 180 / Math.PI);
gr.RotateTransform(slope);
gr.DrawString(message, stringFont, myBrush, containerBox, sf);
return newImage;
}
}
catch (Exception exc)
{
throw exc;
}
}
public int Calculations(decimal w1, decimal h1, int newWidth)
{
decimal height = 0;
decimal ratio = 0;
if (newWidth < w1)
{
ratio = w1 / newWidth;
height = h1 / ratio;
return height.To<int>();
}
if (w1 < newWidth)
{
ratio = newWidth / w1;
height = h1 * ratio;
return height.To<int>();
}
return height.To<int>();
}
}
Simple solution which properly handles ByteOrder:
ByteBuffer.allocate(4).order(ByteOrder.nativeOrder()).putInt(yourInt).array();
The second function's signature is identical to the Array.prototype.splice
method.
function mutate(s) {
return function splice() {
var a = s.split('');
Array.prototype.splice.apply(a, arguments);
return a.join('');
};
}
mutate('101')(1, 1, '1');
I know there's already an accepted answer, but hope this is useful.
or you can simply do
$('select[name=a[b]] option:selected').val()
The one liner "no imports" version
a = [0,88,26,3,48,85,65,16,97,83,91]
ind_pos = [1,5,7]
[ a[i] for i in ind_pos ]
Results to text only allows a maximum of 8192 characters.
I use this approach
DECLARE @Query NVARCHAR(max);
set @Query = REPLICATE('A',4000)
set @Query = @Query + REPLICATE('B',4000)
set @Query = @Query + REPLICATE('C',4000)
set @Query = @Query + REPLICATE('D',4000)
select LEN(@Query)
SELECT @Query /*Won't contain any "D"s*/
SELECT @Query as [processing-instruction(x)] FOR XML PATH /*Not truncated*/
split($pattern,$string)
split strings within a given pattern or regex (it's deprecated since 5.3.0)
preg_split($pattern,$string)
split strings within a given regex pattern
explode($pattern,$string)
split strings within a given pattern
end($arr)
get last array element
So:
end(split('-',$str))
end(preg_split('/-/',$str))
$strArray = explode('-',$str)
$lastElement = end($strArray)
Will return the last element of a -
separated string.
And there's a hardcore way to do this:
$str = '1-2-3-4-5';
echo substr($str, strrpos($str, '-') + 1);
// | '--- get the last position of '-' and add 1(if don't substr will get '-' too)
// '----- get the last piece of string after the last occurrence of '-'
Not that there haven't been enough answers to this question, but there is a repeat function; just need to make a list of and then join the output:
from itertools import repeat
def rep(s,n):
''.join(list(repeat(s,n))
This is an extension method derived from @Seattle Leonard 's answer:
public static T GetMax<T,U>(this IEnumerable<T> data, Func<T,U> f) where U:IComparable
{
return data.Aggregate((i1, i2) => f(i1).CompareTo(f(i2))>0 ? i1 : i2);
}
Well, to use it i dont think matters (similar to disabled and readonly), personally i use checked="checked" but if you are trying to manipulate them with JavaScript, you use true/false
Remove static
keyword in method definition. Keep it just in your class definition.
static
keyword placed in .cpp file means that a certain function has a static linkage, ie. it is accessible only from other functions in the same file.
This might be late as I think most of us are using BS4. This article explained all the questions you asked in a detailed and simple manner also includes what to do when. The detailed guide to use bs4 or bootstrap
https://uxplanet.org/how-the-bootstrap-4-grid-works-a1b04703a3b7
None of the above answers worked for me. I kept getting this error:
Copy-Item : Access is denied
+ CategoryInfo : PermissionDenied: (\\192.168.1.100\Shared\test.txt:String) [Copy-Item], UnauthorizedAccessException>
+ FullyQualifiedErrorId : ItemExistsUnauthorizedAccessError,Microsoft.PowerShell.Commands.CopyItemCommand
So this did it for me:
netsh advfirewall firewall set rule group="File and Printer Sharing" new enable=yes
Then from my host my machine in the Run box I just did this:
\\{IP address of nanoserver}\C$
If you'd like to track only failed logins, you can use the SQL Server Audit feature (available in SQL Server 2008 and above). You will need to add the SQL server instance you want to audit, and check the failed login operation to audit.
Note: tracking failed logins via SQL Server Audit has its disadvantages. For example - it doesn't provide the names of client applications used.
If you want to audit a client application name along with each failed login, you can use an Extended Events session.
To get you started, I recommend reading this article: http://www.sqlshack.com/using-extended-events-review-sql-server-failed-logins/
Calling object.paintComponent(g)
is an error.
Instead this method is called automatically when the panel is created. The paintComponent()
method can also be called explicitly by the repaint()
method defined in Component
class.
The effect of calling repaint()
is that Swing automatically clears the graphic on the panel and executes the paintComponent
method to redraw the graphics on this panel.
I am not sure if you have edited right configuration file. Try following steps
open %userprofile%\ducuments\iisexpress\config\applicationhost.config
By default bellow given entries are commented in the applicationhost.config file. uncomment these entries.
<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" /> <add name="WebDAVModule" />
<add name="WebDAV" path="*"
verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK"
modules="WebDAVModule" resourceType="Unspecified" requireAccess="None"
/>
Do this:
<ToggleButton
android:id="@+id/toggle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@drawable/check" <!--check.xml-->
android:layout_margin="10dp"
android:textOn=""
android:textOff=""
android:focusable="false"
android:focusableInTouchMode="false"
android:layout_centerVertical="true"/>
create check.xml in drawable folder
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<!-- When selected, use grey -->
<item android:drawable="@drawable/selected_image"
android:state_checked="true" />
<!-- When not selected, use white-->
<item android:drawable="@drawable/unselected_image"
android:state_checked="false"/>
</selector>
Since the OP's question is about stripping the newline character from the last element, I would reset it with the_list[-1].rstrip()
:
>>> the_list = ['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3\n']
>>> the_list[-1] = ls[-1].rstrip()
>>> the_list
['Name1', '7.3', '6.9', '6.6', '6.6', '6.1', '6.4', '7.3']
It's O(1).
You have two " "
before the =
let imageToDeleteParameters = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }
Try and run the following command:
ALTER TABLE `investments`
MODIFY created_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
NOT NULL;
and
ALTER TABLE `investments`
MODIFY updated_at TIMESTAMP
DEFAULT CURRENT_TIMESTAMP
NOT NULL;
The reason you are getting this error is because you are not setting a default value for the created_at
and updated_at
fields. MySQL is not accepting your command since the values for these columns cannot be null.
You can use an enum of months:
public enum Month
{
January,
February,
// (...)
December,
}
public Month ToInt(Month Input)
{
return (int)Enum.Parse(typeof(Month), Input, true));
}
I am not 100% certain on the syntax for enum.Parse(), though.
In ASCII the upper and lower case alphabet are 0x20 apart from each other, so this is another way to do it.
int lower(int a)
{
if ((a >= 0x41) && (a <= 0x5A))
a |= 0x20;
return a;
}
Temporary tablespaces are used for database sorting and joining operations and for storing global temporary tables. It may grow in size over a period of time and thus either we need to recreate temporary tablespace or shrink it to release the unused space.
size_t is an unsigned integral type, that can represent the largest integer on you system. Only use it if you need very large arrays,matrices etc.
Some functions return an size_t and your compiler will warn you if you try to do comparisons.
Avoid that by using a the appropriate signed/unsigned datatype or simply typecast for a fast hack.
After this question was asked, Facebook launched HipHop for PHP which is probably the best-tested PHP compiler to date (seeing as it ran one of the world’s 10 biggest websites). However, Facebook discontinued it in favour of HHVM, which is a virtual machine, not a compiler.
Beyond that, googling PHP compiler
turns up a number of 3rd party solutions.
bcompiler_write_exe_footer()
manual)I found the solution reading the link that Gary gave (and I suggest to follow this way).
Summarizing to resolve the tree conflict committing your working directory with SVN client 1.6.x you can use:
svn resolve --accept working -R .
where .
is the directory in conflict.
WARNING: "Committing your working directory" means that your sandbox structure will be the one you are committing, so if, for instance, you deleted some file from your sandbox they will be deleted from the repository too. This applies only to the conflicted directory.
In this way, we are suggesting SVN to resolve the conflict (--resolve
), accepting the working copy inside your sandbox (--accept working
), recursively (-R
), starting from the current directory (.
).
In TortoiseSVN, selecting "Resolved" on right click, actually resolves this issue.
The accepted answer by Adam (flex: 1 1 0
) works perfectly for flexbox containers whose width is either fixed, or determined by an ancestor. Situations where you want the children to fit the container.
However, you may have a situation where you want the container to fit the children, with the children equally sized based on the largest child. You can make a flexbox container fit its children by either:
position: absolute
and not setting width
or right
, ordisplay: inline-block
For such flexbox containers, the accepted answer does NOT work, the children are not sized equally. I presume that this is a limitation of flexbox, since it behaves the same in Chrome, Firefox and Safari.
The solution is to use a grid instead of a flexbox.
Demo: https://codepen.io/brettdonald/pen/oRpORG
<p>Normal scenario — flexbox where the children adjust to fit the container — and the children are made equal size by setting {flex: 1 1 0}</p>
<div id="div0">
<div>
Flexbox
</div>
<div>
Width determined by viewport
</div>
<div>
All child elements are equal size with {flex: 1 1 0}
</div>
</div>
<p>Now we want to have the container fit the children, but still have the children all equally sized, based on the largest child. We can see that {flex: 1 1 0} has no effect.</p>
<div class="wrap-inline-block">
<div id="div1">
<div>
Flexbox
</div>
<div>
Inside inline-block
</div>
<div>
We want all children to be the size of this text
</div>
</div>
</div>
<div id="div2">
<div>
Flexbox
</div>
<div>
Absolutely positioned
</div>
<div>
We want all children to be the size of this text
</div>
</div>
<br><br><br><br><br><br>
<p>So let's try a grid instead. Aha! That's what we want!</p>
<div class="wrap-inline-block">
<div id="div3">
<div>
Grid
</div>
<div>
Inside inline-block
</div>
<div>
We want all children to be the size of this text
</div>
</div>
</div>
<div id="div4">
<div>
Grid
</div>
<div>
Absolutely positioned
</div>
<div>
We want all children to be the size of this text
</div>
</div>
body {
margin: 1em;
}
.wrap-inline-block {
display: inline-block;
}
#div0, #div1, #div2, #div3, #div4 {
border: 1px solid #888;
padding: 0.5em;
text-align: center;
white-space: nowrap;
}
#div2, #div4 {
position: absolute;
left: 1em;
}
#div0>*, #div1>*, #div2>*, #div3>*, #div4>* {
margin: 0.5em;
color: white;
background-color: navy;
padding: 0.5em;
}
#div0, #div1, #div2 {
display: flex;
}
#div0>*, #div1>*, #div2>* {
flex: 1 1 0;
}
#div0 {
margin-bottom: 1em;
}
#div2 {
top: 15.5em;
}
#div3, #div4 {
display: grid;
grid-template-columns: repeat(3,1fr);
}
#div4 {
top: 28.5em;
}
From the oracle documentation, the below query explains it better
INSERT INTO tbl_temp2 (fld_id)
SELECT tbl_temp1.fld_order_id
FROM tbl_temp1 WHERE tbl_temp1.fld_order_id > 100;
You can read this link
Your query would be as follows
//just the concept
INSERT INTO quotedb
(COLUMN_NAMES) //seperated by comma
SELECT COLUMN_NAMES FROM tickerdb,quotedb WHERE quotedb.ticker = tickerdb.ticker
Note: Make sure the columns in insert and select are in right position as per your requirement
Hope this helps!
"_blank" is not guaranteed to be a new tab or window. It's implemented differently per-browser.
You can, however, put anything into target. I usually just say "_tab", and every browser I know of just opens it in a new tab.
Be aware that it means it's a named target, so if you try to open 2 URLs, they will use the same tab.
There's also terms query which should save you some work. Here example from docs:
{
"terms" : {
"tags" : [ "blue", "pill" ],
"minimum_should_match" : 1
}
}
Under hood it constructs boolean should. So it's basically the same thing as above but shorter.
There's also a corresponding terms filter.
So to summarize your query could look like this:
{
"filtered": {
"query": {
"match": { "title": "hello world" }
},
"filter": {
"terms": {
"tags": ["c", "d"]
}
}
}
}
With greater number of tags this could make quite a difference in length.
Many UNIX programs respect the http_proxy
environment variable, curl included. The format curl accepts is [protocol://]<host>[:port]
.
In your shell configuration:
export http_proxy http://proxy.server.com:3128
For proxying HTTPS requests, set https_proxy
as well.
Curl also allows you to set this in your .curlrc
file (_curlrc
on Windows), which you might consider more permanent:
http_proxy=http://proxy.server.com:3128
Hash.merge! is the cleanest solution
o = { a: 'a', b: 'b' }
o.merge!(o) { |key, value| "%#{ value }%" }
puts o.inspect
> { :a => "%a%", :b => "%b%" }
try this:
sudo pip install -i https://testpypi.python.org/pypi psycopg2==2.7b2
.. this is especially helpful if you're running into egg error
on aws ec2 instances if you run into gcc error; try this
1. sudo yum install gcc python-setuptools python-devel postgresql-devel
2. sudo su -
3. sudo pip install psycopg2
While moopasta's answer works, it doesn't appear to allow wildcards and there is another (potentially better) option. The Chromium project has some HTTP authentication documentation that is useful but incomplete.
Specifically the option that I found best is to whitelist sites that you would like to allow Chrome to pass authentication information to, you can do this by:
auth-server-whitelist
command line switch. e.g. --auth-server-whitelist="*example.com,*foobar.com,*baz"
. Downfall to this approach is that opening links from other programs will launch Chrome without the command line switch.AuthServerWhitelist
/"Authentication server whitelist" Group Policy or Local Group Policy. This seems like the most stable option but takes more work to setup. You can set this up locally, no need to have this remotely deployed.Those looking to set this up for an enterprise can likely follow the directions for using Group Policy or the Admin console to configure the AuthServerWhitelist
policy. Those looking to set this up for one machine only can also follow the Group Policy instructions:
Start > Run > gpedit.msc
Local Computer Policy > Computer Configuration > Administrative Templates
Administrative Templates
, and select Add/Remove Templates
windows\adm\en-US\chrome.adm
template via the dialogComputer Configuration > Administrative Templates > Classic Administrative Templates > Google > Google Chrome > Policies for HTTP Authentication
enable and configure Authentication server whitelist
chrome://policy
to view active policiesThis is an excellent article : http://www.daniweb.com/software-development/computer-science/threads/13488/time-complexity-of-algorithm
The below answer is copied from above (in case the excellent link goes bust)
The most common metric for calculating time complexity is Big O notation. This removes all constant factors so that the running time can be estimated in relation to N as N approaches infinity. In general you can think of it like this:
statement;
Is constant. The running time of the statement will not change in relation to N.
for ( i = 0; i < N; i++ )
statement;
Is linear. The running time of the loop is directly proportional to N. When N doubles, so does the running time.
for ( i = 0; i < N; i++ ) {
for ( j = 0; j < N; j++ )
statement;
}
Is quadratic. The running time of the two loops is proportional to the square of N. When N doubles, the running time increases by N * N.
while ( low <= high ) {
mid = ( low + high ) / 2;
if ( target < list[mid] )
high = mid - 1;
else if ( target > list[mid] )
low = mid + 1;
else break;
}
Is logarithmic. The running time of the algorithm is proportional to the number of times N can be divided by 2. This is because the algorithm divides the working area in half with each iteration.
void quicksort ( int list[], int left, int right )
{
int pivot = partition ( list, left, right );
quicksort ( list, left, pivot - 1 );
quicksort ( list, pivot + 1, right );
}
Is N * log ( N ). The running time consists of N loops (iterative or recursive) that are logarithmic, thus the algorithm is a combination of linear and logarithmic.
In general, doing something with every item in one dimension is linear, doing something with every item in two dimensions is quadratic, and dividing the working area in half is logarithmic. There are other Big O measures such as cubic, exponential, and square root, but they're not nearly as common. Big O notation is described as O ( <type> )
where <type>
is the measure. The quicksort algorithm would be described as O ( N * log ( N ) )
.
Note that none of this has taken into account best, average, and worst case measures. Each would have its own Big O notation. Also note that this is a VERY simplistic explanation. Big O is the most common, but it's also more complex that I've shown. There are also other notations such as big omega, little o, and big theta. You probably won't encounter them outside of an algorithm analysis course. ;)
I have changed the code of serge_gubenko and it works better
for (int i = 0; i < dataGrid.Items.Count; i++)
{
string txt = searchTxt.Text;
dataGrid.ScrollIntoView(dataGrid.Items[i]);
DataGridRow row = (DataGridRow)dataGrid.ItemContainerGenerator.ContainerFromIndex(i);
TextBlock cellContent = dataGrid.Columns[1].GetCellContent(row) as TextBlock;
if (cellContent != null && cellContent.Text.ToLower().Equals(txt.ToLower()))
{
object item = dataGrid.Items[i];
dataGrid.SelectedItem = item;
dataGrid.ScrollIntoView(item);
row.MoveFocus(new TraversalRequest(FocusNavigationDirection.Next));
break;
}
}
Aside: Note that the standard LINQ operators (as per the earlier example) don't change the existing list - list.OrderBy(...).ToList()
will create a new list based on the re-ordered sequence. It is pretty easy, however, to create an extension method that allows you to use lambdas with List<T>.Sort
:
static void Sort<TSource, TValue>(this List<TSource> list,
Func<TSource, TValue> selector)
{
var comparer = Comparer<TValue>.Default;
list.Sort((x,y) => comparer.Compare(selector(x), selector(y)));
}
static void SortDescending<TSource, TValue>(this List<TSource> list,
Func<TSource, TValue> selector)
{
var comparer = Comparer<TValue>.Default;
list.Sort((x,y) => comparer.Compare(selector(y), selector(x)));
}
Then you can use:
list.Sort(x=>x.SomeProp); // etc
This updates the existing list in the same way that List<T>.Sort
usually does.
Just sharing what worked in my case as someone else might find it useful. I have a modal and just wanted to print the body of the modal which could be several pages on paper.
Other solutions I tried just printed one page and only what was on screen. Emil's accepted solution worked for me:
https://stackoverflow.com/a/30137174/3123109
This is what the component ended up looking like. It prints everything in the body of the modal.
import React, { Component } from 'react';
import {
Button,
Modal,
ModalBody,
ModalHeader
} from 'reactstrap';
export default class TestPrint extends Component{
constructor(props) {
super(props);
this.state = {
modal: false,
data: [
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test',
'test', 'test', 'test', 'test', 'test', 'test'
]
}
this.toggle = this.toggle.bind(this);
this.print = this.print.bind(this);
}
print() {
var content = document.getElementById('printarea');
var pri = document.getElementById('ifmcontentstoprint').contentWindow;
pri.document.open();
pri.document.write(content.innerHTML);
pri.document.close();
pri.focus();
pri.print();
}
renderContent() {
var i = 0;
return this.state.data.map((d) => {
return (<p key={d + i++}>{i} - {d}</p>)
});
}
toggle() {
this.setState({
modal: !this.state.modal
})
}
render() {
return (
<div>
<Button
style={
{
'position': 'fixed',
'top': '50%',
'left': '50%',
'transform': 'translate(-50%, -50%)'
}
}
onClick={this.toggle}
>
Test Modal and Print
</Button>
<Modal
size='lg'
isOpen={this.state.modal}
toggle={this.toggle}
className='results-modal'
>
<ModalHeader toggle={this.toggle}>
Test Printing
</ModalHeader>
<iframe id="ifmcontentstoprint" style={{
height: '0px',
width: '0px',
position: 'absolute'
}}></iframe>
<Button onClick={this.print}>Print</Button>
<ModalBody id='printarea'>
{this.renderContent()}
</ModalBody>
</Modal>
</div>
)
}
}
Note: However, I am having difficulty getting styles to be reflected in the iframe
.
One like with events
(keydown)="$event.keyCode != 32 ? $event:$event.preventDefault()"
Just a quick modification to DaniP's answer, for anyone dealing with elements that can sometimes extend beyond the bounds of the device's viewport.
Added just a slight conditional - In the case of elements that are bigger than the viewport, the element will be revealed once it's top half has completely filled the viewport.
function elementInView(el) {
// The vertical distance between the top of the page and the top of the element.
var elementOffset = $(el).offset().top;
// The height of the element, including padding and borders.
var elementOuterHeight = $(el).outerHeight();
// Height of the window without margins, padding, borders.
var windowHeight = $(window).height();
// The vertical distance between the top of the page and the top of the viewport.
var scrollOffset = $(this).scrollTop();
if (elementOuterHeight < windowHeight) {
// Element is smaller than viewport.
if (scrollOffset > (elementOffset + elementOuterHeight - windowHeight)) {
// Element is completely inside viewport, reveal the element!
return true;
}
} else {
// Element is larger than the viewport, handle visibility differently.
// Consider it visible as soon as it's top half has filled the viewport.
if (scrollOffset > elementOffset) {
// The top of the viewport has touched the top of the element, reveal the element!
return true;
}
}
return false;
}
Why not so?:
set host=%COMPUTERNAME%
echo %host%
Most of the other answers point to eager loading, but I found another solution.
In my case I had an EF object InventoryItem
with a collection of InvActivity
child objects.
class InventoryItem {
...
// EF code first declaration of a cross table relationship
public virtual List<InvActivity> ItemsActivity { get; set; }
public GetLatestActivity()
{
return ItemActivity?.OrderByDescending(x => x.DateEntered).SingleOrDefault();
}
...
}
And since I was pulling from the child object collection instead of a context query (with IQueryable
), the Include()
function was not available to implement eager loading. So instead my solution was to create a context from where I utilized GetLatestActivity()
and attach()
the returned object:
using (DBContext ctx = new DBContext())
{
var latestAct = _item.GetLatestActivity();
// attach the Entity object back to a usable database context
ctx.InventoryActivity.Attach(latestAct);
// your code that would make use of the latestAct's lazy loading
// ie latestAct.lazyLoadedChild.name = "foo";
}
Thus you aren't stuck with eager loading.
I found the console output of my job in the browser at the following location:
http://[Jenkins URL]/job/[Job Name]/default/[Build Number]/console
Settings ->
Preference ->
Edit Components (tab) ->
Tab Setting (group) ->
Replace by space
In version 5.6.8 (and above):
Settings ->
Preferences... ->
Language Menu/Tab Settings ->
Tab Settings (group) ->
Replace by space
$21.4 - "static const size_type npos = -1;"
It is returned by string functions indicating error/not found etc.
I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.
openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text
You can try like this:
Sum({Tablename.Columnname})
It will work without creating a summarize field in formulae.
ok, you may use substr in correlation to instr to find the starting position of your string
select
dbms_lob.substr(
product_details,
length('NEW.PRODUCT_NO'), --amount
dbms_lob.instr(product_details,'NEW.PRODUCT_NO') --offset
)
from my_table
where dbms_lob.instr(product_details,'NEW.PRODUCT_NO')>=1;
My solution
SET sql_mode='';
UPDATE tnx_k2_items
SET created_by = 790
, modified = '0000-00-00 00:00:00'
, modified_by = 0
You can use
jQuery(document).ready(function(){ ...... });
or
(function ($) { ...... }(jQuery));
You don't create subfolders of the drawable folder but rather 'sibling' folders next to it under the /res
folder for the different screen densities or screen sizes.
The /drawable
folder (without any dimension) is mostly used for drawables that don't relate to any screen sizes like selector
s.
See this screenshot (use the name drawable-hdpi
instead of mipmap-hdpi
):
You can also use @media queries to establish your max/min padding/margin (but only according to screen size):
Let's say you want a max padding of 8px, you can do the following
div {
padding: 1vh 0;
}
@media (max-height: 800px) {
div {
padding: 8px 0;
}
}
I think I've found a better solution than the accepted answer. The alternative solutions weren't working for me and I didn't want to have to work in binary mode all the time. Fortunately this seems to get the job done and I haven't encountered any nasty side-effects yet: preserve missing end-of-line at end of text files. I just added the whole thing to my ~/.vimrc.
Typescript 3.4
introduces the new 'const' assertion
You can now prevent literal types (eg. 'orange'
or 'red'
) being 'widened' to type string
with a so-called const
assertion.
You will be able to do:
let fruit = 'orange' as const; // or...
let fruit = <const> 'orange';
And then it won't turn itself into a string
anymore - which is the root of the problem in the question.
It's easy enough to just use $route.reload()
(don't forget to inject $route into your controller), but from your example you could just use "href" instead of "ng-href":
<a href="" class="navbar-brand" title="home" data-translate>PORTAL_NAME</a>
You only need to use ng-href to protect the user from invalid links caused by them clicking before Angular has replaced the contents of the {{ }} tags.
Kind of, use the XmlAttribute
instead of XmlElement
, but it won't look like what you want. It will look like the following:
<SomeModel SomeStringElementName="testData">
</SomeModel>
The only way I can think of to achieve what you want (natively) would be to have properties pointing to objects named SomeStringElementName and SomeInfoElementName where the class contained a single getter named "value". You could take this one step further and use DataContractSerializer so that the wrapper classes can be private. XmlSerializer won't read private properties.
// TODO: make the class generic so that an int or string can be used.
[Serializable]
public class SerializationClass
{
public SerializationClass(string value)
{
this.Value = value;
}
[XmlAttribute("value")]
public string Value { get; }
}
[Serializable]
public class SomeModel
{
[XmlIgnore]
public string SomeString { get; set; }
[XmlIgnore]
public int SomeInfo { get; set; }
[XmlElement]
public SerializationClass SomeStringElementName
{
get { return new SerializationClass(this.SomeString); }
}
}
Rails 4:
If you want to use both not equal and equal, you can use:
user_id = 4
group_id = 27
GroupUser.where(group_id: group_id).where.not(user_id: user_id)
If you want to use a variety of operators (ie. >
, <
), at some point you may want to switch notations to the following:
GroupUser.where("group_id > ? AND user_id != ?", group_id, user_id)
To expand on John's answer you can also use the Dockerfile
CMD
command as following (in case you want it to self start without additional args)
CMD ["nginx", "-g", "daemon off;"]
This is a simpler one
$('#some_select_box').find('option:selected').remove().end();
You can try progress bar instead of seek bar
<ProgressBar
android:id="@+id/progressBar"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="50dp"
android:layout_marginBottom="35dp"
/>
I know this is a two year old question, but this is a quick answer for those searching for a 'how to'.
If you don't want to have to put quotes around anything you can simply write a block of text to a file, and escape variables you want to export as text (for instance for use in a script) and not escape one's you want to export as the value of the variable.
#!/bin/bash
FILE_NAME="test.txt"
VAR_EXAMPLE="\"string\""
cat > ${FILE_NAME} << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} in ${FILE_NAME}
EOF
Will write "${VAR_EXAMPLE}="string" in test.txt" into test.txt
This can also be used to output blocks of text to the console with the same rules by omitting the file name
#!/bin/bash
VAR_EXAMPLE="\"string\""
cat << EOF
\${VAR_EXAMPLE}=${VAR_EXAMPLE} to console
EOF
Will output "${VAR_EXAMPLE}="string" to console" to the console
After experimenting with all the different answers on this site, I ended up with this solution:
#!/bin/sh
path="$1"
if [ ! -f "$path/.git" ]; then
echo "$path is no valid git submodule"
exit 1
fi
git submodule deinit -f $path &&
git rm --cached $path &&
rm -rf .git/modules/$path &&
rm -rf $path &&
git reset HEAD .gitmodules &&
git config -f .gitmodules --remove-section submodule.$path
This restores the exact same state as before you added the submodule. You can right away add the submodule again, which was not possible with most of the answers here.
git submodule add $giturl test
aboveScript test
This leaves you with a clean checkout with no changes to commit.
This was tested with:
$ git --version
git version 1.9.3 (Apple Git-50)
I had today a similar error message. What was peculiar is that it did not break the Application. It was running smoothly but the command prompt (Windows machine) indicated there was an error. I did not update the Typescript version but found another culprit. It turned there was a tiny omission of symbol - closing ")", which I believe The Typescript is compensating for. Just for reference the code is the following:
[new Object('First Characteristic','Second Characteristic',
'Third Characteristic'*]
* notice here the ending ")" is missing.
Once brought back no more issues on the command prompt!
This fixes the math to scale to the max size in both width and height rather than just one depending on the width and height of the original.
- (UIImage *) scaleProportionalToSize: (CGSize)size
{
float widthRatio = size.width/self.size.width;
float heightRatio = size.height/self.size.height;
if(widthRatio > heightRatio)
{
size=CGSizeMake(self.size.width*heightRatio,self.size.height*heightRatio);
} else {
size=CGSizeMake(self.size.width*widthRatio,self.size.height*widthRatio);
}
return [self scaleToSize:size];
}
Below would be the best way to insert a row into pandas dataframe without sorting and reseting an index:
import pandas as pd
df = pd.DataFrame(columns=['a','b','c'])
def insert(df, row):
insert_loc = df.index.max()
if pd.isna(insert_loc):
df.loc[0] = row
else:
df.loc[insert_loc + 1] = row
insert(df,[2,3,4])
insert(df,[8,9,0])
print(df)
A recent web.config change may be in the wrong web.config file.
A <machineKey...>
property had been added to Views/web.config. No matter how many Cleans and Rebuilds the error remained. The fix was to move the property into the root /web.config.
showModalBottomSheet(
backgroundColor: Colors.transparent,
context: context, builder: (context) {
return Container(
decoration: BoxDecoration(
color: Colors.white,
borderRadius: BorderRadius.only(
topLeft:Radius.circular(40) ,
topRight: Radius.circular(40)
),
),
padding: EdgeInsets.symmetric(vertical: 20,horizontal: 60),
child: Settings_Form(),
);
});
For Windows, CaptureStackBackTrace()
is also an option, which requires less preparation code on the user's end than StackWalk64()
does. (Also, for a similar scenario I had, CaptureStackBackTrace()
ended up working better (more reliably) than StackWalk64()
.)
Just add
[textField endEditing:YES];
where you want to disable keyboard and display the picker view.
Don't moveTo()
after each lineTo()
In other words, remove every moveTo()
except the first one.
Seriously, if I just copy-paste OP's code and remove the unnecessary moveTo()
calls, it works.
Nothing else needs to be done.
EDIT: I know the OP already posted his "final working solution", but he didn't state why it works. The actual reason was quite surprising to me, so I felt the need to add an answer.
You can also use the [NonSerialized]
attribute
[Serializable]
public struct MySerializableStruct
{
[NonSerialized]
public string hiddenField;
public string normalField;
}
Indicates that a field of a serializable class should not be serialized. This class cannot be inherited.
If you're using Unity for example (this isn't only for Unity) then this works with UnityEngine.JsonUtility
using UnityEngine;
MySerializableStruct mss = new MySerializableStruct
{
hiddenField = "foo",
normalField = "bar"
};
Debug.Log(JsonUtility.ToJson(mss)); // result: {"normalField":"bar"}
use your code within
<script type="text/javascript">
function window.onload()
{
var d = new Date()
var gmtOffSet = -d.getTimezoneOffset();
var gmtHours = Math.floor(gmtOffSet / 60);
var GMTMin = Math.abs(gmtOffSet % 60);
var dot = ".";
var retVal = "" + gmtHours + dot + GMTMin;
document.getElementById('<%= offSet.ClientID%>').value = retVal;
}
</script>
Many string update functions in MySQL seems to be working like this:
If one argument is null
, then concatenation or other functions return null
too.
So, to update a field with null
value, first set it to a non-null value, such as ''
For example:
update table set field='' where field is null;
update table set field=concat(field,' append');
An iframe is used to embed another document inside a html page.
If the form is to be submitted to an iframe within the form page, then it can be easily acheived using the target attribute of the tag.
Set the target attribute of the form to the name of the iframe tag.
<form action="action" method="post" target="output_frame">
<!-- input elements here -->
</form>
<iframe name="output_frame" src="" id="output_frame" width="XX" height="YY">
</iframe>
Advanced iframe target use
This property can also be used to produce an ajax like experience, especially in cases like file upload, in which case where it becomes mandatory to submit the form, in order to upload the files
The iframe can be set to a width and height of 0, and the form can be submitted with the target set to the iframe, and a loading dialog opened before submitting the form. So, it mocks a ajax control as the control still remains on the input form jsp, with the loading dialog open.
Exmaple
<script>
$( "#uploadDialog" ).dialog({ autoOpen: false, modal: true, closeOnEscape: false,
open: function(event, ui) { jQuery('.ui-dialog-titlebar-close').hide(); } });
function startUpload()
{
$("#uploadDialog").dialog("open");
}
function stopUpload()
{
$("#uploadDialog").dialog("close");
}
</script>
<div id="uploadDialog" title="Please Wait!!!">
<center>
<img src="/imagePath/loading.gif" width="100" height="100"/>
<br/>
Loading Details...
</center>
</div>
<FORM ENCTYPE="multipart/form-data" ACTION="Action" METHOD="POST" target="upload_target" onsubmit="startUpload()">
<!-- input file elements here-->
</FORM>
<iframe id="upload_target" name="upload_target" src="#" style="width:0;height:0;border:0px solid #fff;" onload="stopUpload()">
</iframe>
The problem can also be the ordering of your style sheet imports. I had to move my custom style sheet import below the bootstrap import.
You can create a folder with os.makedirs()
and use os.path.exists() to see if it already exists:
newpath = r'C:\Program Files\arbitrary'
if not os.path.exists(newpath):
os.makedirs(newpath)
If you're trying to make an installer: Windows Installer does a lot of work for you.
Bitmap bitmap = MediaStore.Images.Media.getBitmap(getContentResolver(), uri);
you can implement a helper doing something like that :
public static LocalDateTime convertUTCFRtoUTCZ(LocalDateTime dateTime) {
ZoneId fr = ZoneId.of("Europe/Paris");
ZoneId utcZ = ZoneId.of("Z");
ZonedDateTime frZonedTime = ZonedDateTime.of(dateTime, fr);
ZonedDateTime utcZonedTime = frZonedTime.withZoneSameInstant(utcZ);
return utcZonedTime.toLocalDateTime();
}
I wanted to save Recycler View's scroll position when navigating away from my list activity and then clicking the back button to navigate back. Many of the solutions provided for this problem were either much more complicated than needed or didn't work for my configuration, so I thought I'd share my solution.
First save your instance state in onPause as many have shown. I think it's worth emphasizing here that this version of onSaveInstanceState is a method from the RecyclerView.LayoutManager class.
private LinearLayoutManager mLayoutManager;
Parcelable state;
@Override
public void onPause() {
super.onPause();
state = mLayoutManager.onSaveInstanceState();
}
The key to getting this to work properly is to make sure you call onRestoreInstanceState after you attach your adapter, as some have indicated in other threads. However the actual method call is much simpler than many have indicated.
private void someMethod() {
mVenueRecyclerView.setAdapter(mVenueAdapter);
mLayoutManager.onRestoreInstanceState(state);
}
GPRESULT
is the right command, but it cannot be run without parameters. /v
or verbose option is difficult to manage without also outputting to a text file. E.G. I recommend using
gpresult /user myAccount /v > C:\dev\me.txt
--Ensure C:\Dev\me.txt exists
Another option is to display summary information only which may be entirely visible in the command window:
gpresult /user myAccount /r
The accounts are listed under the heading:
The user is a part of the following security groups
---------------------------------------------------
Vertical align doesn't quite work the way you want it to. See: http://phrogz.net/css/vertical-align/index.html
This isn't pretty, but it WILL do what you want: Vertical align behaves as expected only when used in a table cell.
There are other alternatives: You can declare things as tables or table cells within CSS to make them behave as desired, for example. Margins and positioning can sometimes be played with to get the same effect. None of the solutions are terrible pretty, though.
This Works for me.
Read this blog.
It is a static function on the MessageBox class, the simple way to do this is using
MessageBox.Show("my message");
in the System.Windows.Forms class. You can find more on the msdn page for this here . Among other things you can control the message box text, title, default button, and icons. Since you didn't specify, if you are trying to do this in a webpage you should look at triggering the javascript alert("my message"); or confirm("my question"); functions.
Just came into this issue and finally realised that LocalDateTime doesn't have any timezone information. If you received a date string with timezone information, you need to use this as the type:
ZonedDateTime
Check this link
Instead of using list.index(x)
which returns the index of x if it is found in list or returns a #ValueError
message if x is not found, you could use list.count(x)
which returns the number of occurrences of x in list (validation that x is indeed in the list) or it returns 0 otherwise (in the absence of x). The cool thing about count()
is that it doesn't break your code or require you to throw an exception for when x is not found
The use of file.exists() to test for the existence of the directory is a problem in the original post. If subDir included the name of an existing file (rather than just a path), file.exists() would return TRUE, but the call to setwd() would fail because you can't set the working directory to point at a file.
I would recommend the use of file_test(op="-d", subDir), which will return "TRUE" if subDir is an existing directory, but FALSE if subDir is an existing file or a non-existent file or directory. Similarly, checking for a file can be accomplished with op="-f".
Additionally, as described in another comment, the working directory is part of the R environment and should be controlled by the user, not a script. Scripts should, ideally, not change the R environment. To address this problem, I might use options() to store a globally available directory where I wanted all of my output.
So, consider the following solution, where someUniqueTag is just a programmer-defined prefix for the option name, which makes it unlikely that an option with the same name already exists. (For instance, if you were developing a package called "filer", you might use filer.mainDir and filer.subDir).
The following code would be used to set options that are available for use later in other scripts (thus avoiding the use of setwd() in a script), and to create the folder if necessary:
mainDir = "c:/path/to/main/dir"
subDir = "outputDirectory"
options(someUniqueTag.mainDir = mainDir)
options(someUniqueTag.subDir = "subDir")
if (!file_test("-d", file.path(mainDir, subDir)){
if(file_test("-f", file.path(mainDir, subDir)) {
stop("Path can't be created because a file with that name already exists.")
} else {
dir.create(file.path(mainDir, subDir))
}
}
Then, in any subsequent script that needed to manipulate a file in subDir, you might use something like:
mainDir = getOption(someUniqueTag.mainDir)
subDir = getOption(someUniqueTag.subDir)
filename = "fileToBeCreated.txt"
file.create(file.path(mainDir, subDir, filename))
This solution leaves the working directory under the control of the user.
Ok, solved it myself;
def sout = new StringBuilder(), serr = new StringBuilder()
def proc = 'ls /badDir'.execute()
proc.consumeProcessOutput(sout, serr)
proc.waitForOrKill(1000)
println "out> $sout\nerr> $serr"
displays:
out> err> ls: cannot access /badDir: No such file or directory
add this to your form:
<form id="regform" action="insert.php" method="post">
add this to your function:
<script>
function myFunction() {
var pass1 = document.getElementById("pass1").value;
var pass2 = document.getElementById("pass2").value;
if (pass1 != pass2) {
//alert("Passwords Do not match");
document.getElementById("pass1").style.borderColor = "#E34234";
document.getElementById("pass2").style.borderColor = "#E34234";
}
else {
alert("Passwords Match!!!");
document.getElementById("regForm").submit();
}
}
</script>
exDict = {1:1, 2:2, 3:3}
with open('file.txt', 'w+') as file:
file.write(str(exDict))
UPDATE: This is no longer valid for newer Keras versions. Please use argmax()
as in the answer from Emilia Apostolova.
The functional API models have just the predict()
function which for classification would return the class probabilities. You can then select the most probable classes using the probas_to_classes()
utility function. Example:
y_proba = model.predict(x)
y_classes = keras.np_utils.probas_to_classes(y_proba)
This is equivalent to model.predict_classes(x)
on the Sequential model.
The reason for this is that the functional API support more general class of tasks where predict_classes()
would not make sense.
Seems like both the conditions are met, perhaps key('contact') is the issue
if(store.telefon) {
detailItems.push( new DetailItem('contact', store.telefon, 'Anrufen', 'fontawesome|phone') );
}
if(store.email) {
detailItems.push( new DetailItem('contact', store.email, 'Email', 'fontawesome|envelope') );
}
string result = System.Text.Encoding.UTF8.GetString(fs.ToArray());
In MS Windows, the mongoimport command has to be run in a normal Windows command prompt, not from the mongodb command prompt.
Go through http://nodejs.org/api/fs.html
One important thing - you can use sync functions also. (It will work like C program)
mysqli_error
function requires $myConnection
as parameters, that's why you get the warning
If you happens to change the columns and stumbled on
'Doctrine\DBAL\Driver\PDOMySql\Driver' not found
then just install
composer require doctrine/dbal
URL url = new URL("https://test.domain:443");
String keyStore = "server.p12"
String keyStorePassword = "changeit";
String keyPassword = "changeit";
String KeyStoreType= "PKCS12";
String KeyManagerAlgorithm = "SunX509";
String SSLVersion = "SSLv3";
public HttpURLConnection getHttpsURLConnection(URL url, String keystore,
String keyStorePass,String keyPassword, String KeyStoreType
,String KeyManagerAlgorithm, String SSLVersion)
throws NoSuchAlgorithmException, KeyStoreException,
CertificateException, FileNotFoundException, IOException,
UnrecoverableKeyException, KeyManagementException {
System.setProperty("javax.net.debug","ssl,handshake,record");
SSLContext sslcontext = SSLContext.getInstance(SSLVersion);
KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerAlgorithm);
KeyStore ks = KeyStore.getInstance(KeyStoreType);
ks.load(new FileInputStream(keystore), keyStorePass.toCharArray());
kmf.init(ks, keyPassword.toCharArray());
TrustManagerFactory tmf = TrustManagerFactory
.getInstance(TrustManagerFactory.getDefaultAlgorithm());
tmf.init(ks);
TrustManager[] tm = tmf.getTrustManagers();
sslcontext.init(kmf.getKeyManagers(), tm, null);
SSLSocketFactory sslSocketFactory = sslcontext.getSocketFactory();
HttpsURLConnection.setDefaultSSLSocketFactory(sslSocketFactory);
HttpsURLConnection httpsURLConnection = ( HttpsURLConnection)uRL.openConnection();
return httpsURLConnection;
}
Use the following code it worked for me:
# Create the figure
fig = plt.figure()
ax = fig.add_subplot(111, projection='3d')
# Generate the values
x_vals = X_iso[:, 0:1]
y_vals = X_iso[:, 1:2]
z_vals = X_iso[:, 2:3]
# Plot the values
ax.scatter(x_vals, y_vals, z_vals, c = 'b', marker='o')
ax.set_xlabel('X-axis')
ax.set_ylabel('Y-axis')
ax.set_zlabel('Z-axis')
plt.show()
while X_iso is my 3-D array and for X_vals, Y_vals, Z_vals I copied/used 1 column/axis from that array and assigned to those variables/arrays respectively.
Sometimes the extensions also create a problem. I was using a dark mode extension(Night Eye) in Microsoft edge. So kernel was busy. When I uninstalled it. It working fine.
For sentOs, it's works for me
At first stop service by sudo service jenkins stop
Than remove by sudo yum remove jenkins
There are a few different libraries doing parsing of Excel files (.xlsx). I will list two projects I find interesting and worth looking into.
Excel parser and builder. It's kind of a wrapper for a popular project JS-XLSX, which is a pure javascript implementation from the Office Open XML spec.
Example for parsing file
var xlsx = require('node-xlsx');
var obj = xlsx.parse(__dirname + '/myFile.xlsx'); // parses a file
var obj = xlsx.parse(fs.readFileSync(__dirname + '/myFile.xlsx')); // parses a buffer
Read, manipulate and write spreadsheet data and styles to XLSX and JSON. It's an active project. At the time of writing the latest commit was 9 hours ago. I haven't tested this myself, but the api looks extensive with a lot of possibilites.
Code example:
// read from a file
var workbook = new Excel.Workbook();
workbook.xlsx.readFile(filename)
.then(function() {
// use workbook
});
// pipe from stream
var workbook = new Excel.Workbook();
stream.pipe(workbook.xlsx.createInputStream());
I would rather prefer that you use BitBucket, as it is not public and there is an official tutorial by Unity on Bitbucket.
https://unity3d.com/learn/tutorials/topics/cloud-build/creating-your-first-source-control-repository
hope this helps.
I would do something like this:
HTML:
<div class="wrapper">
<div class="side">sidebar here</div>
<div class="main">
<textarea class="taclass"></textarea>
</div>
</div><!--/ wrapper -->
CSS:
.wrapper{
display: block;
width: 100%;
overflow: hidden;
}
.side{
float:left;
width:20%;
}
.main{
float:right;
width:80%;
}
.taclass{
display:block;
width:100%;
padding:2%;
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
In python 3 or above, math class has the following functions
import math
math.log2(x)
math.log10(x)
math.log1p(x)
or you can generally use math.log(x, base)
for any base you want.
instead of receiving the json string a model binding is better. For example:
[HttpPost]
public ActionResult AddUser(UserAddModel model)
{
if (ModelState.IsValid) {
return Json(new { Response = "Success" });
}
return Json(new { Response = "Error" });
}
<script>
function submitForm() {
$.ajax({
type: 'POST',
url: "@Url.Action("AddUser")",
contentType: "application/json; charset=utf-8",
dataType: 'json',
data: $("form[name=UserAddForm]").serialize(),
success: function (data) {
console.log(data);
}
});
}
</script>
Since 2017 and Symfony 3.3 you can register Repository as service, with all its advantages it has.
Check my post How to use Repository with Doctrine as Service in Symfony for more general description.
To your specific case, original code with tuning would look like this:
<?php
namespace Test\CommonBundle\Services;
use Doctrine\ORM\EntityManagerInterface;
class UserService
{
private $userRepository;
// use custom repository over direct use of EntityManager
// see step 2
public function __constructor(UserRepository $userRepository)
{
$this->userRepository = $userRepository;
}
public function getUser($userId)
{
return $this->userRepository->find($userId);
}
}
<?php
namespace Test\CommonBundle\Repository;
use Doctrine\ORM\EntityManagerInterface;
class UserRepository
{
private $repository;
public function __construct(EntityManagerInterface $entityManager)
{
$this->repository = $entityManager->getRepository(UserEntity::class);
}
public function find($userId)
{
return $this->repository->find($userId);
}
}
# app/config/services.yml
services:
_defaults:
autowire: true
Test\CommonBundle\:
resource: ../../Test/CommonBundle
find the numbers and then replaced with strings which specified. It is achieved by two methods
Using a regular expression literal
Using keyword RegExp object
Using a regular expression literal:
<script type="text/javascript">
var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));
</script>
**Output:**my contact number is XXX. my age is XXX.
for more details:
http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156
This answers the 'best random' request:
Adi's answer1 from Security.StackExchange has a solution for this:
Make sure you have OpenSSL support, and you'll never go wrong with this one-liner
$token = bin2hex(openssl_random_pseudo_bytes(16));
1. Adi, Mon Nov 12 2018, Celeritas, "Generating an unguessable token for confirmation e-mails", Sep 20 '13 at 7:06, https://security.stackexchange.com/a/40314/
Try one of these:
gdb -p 12271
gdb /path/to/exe 12271
gdb /path/to/exe
(gdb) attach 12271
Seems I don't have enough rep to post a comment, so another answer will have to do.
When you unlink a node using removeChild() or by setting the innerHTML property on the parent, you also need to make sure that there is nothing else referencing it otherwise it won't actually be destroyed and will lead to a memory leak. There are lots of ways in which you could have taken a reference to the node before calling removeChild() and you have to make sure those references that have not gone out of scope are explicitly removed.
Doug Crockford writes here that event handlers are known a cause of circular references in IE and suggests removing them explicitly as follows before calling removeChild()
function purge(d) {
var a = d.attributes, i, l, n;
if (a) {
for (i = a.length - 1; i >= 0; i -= 1) {
n = a[i].name;
if (typeof d[n] === 'function') {
d[n] = null;
}
}
}
a = d.childNodes;
if (a) {
l = a.length;
for (i = 0; i < l; i += 1) {
purge(d.childNodes[i]);
}
}
}
And even if you take a lot of precautions you can still get memory leaks in IE as described by Jens-Ingo Farley here.
And finally, don't fall into the trap of thinking that Javascript delete is the answer. It seems to be suggested by many, but won't do the job. Here is a great reference on understanding delete by Kangax.
Ruby exposes several different methods for handling equality:
a.equal?(b) # object identity - a and b refer to the same object
a.eql?(b) # object equivalence - a and b have the same value
a == b # object equivalence - a and b have the same value with type conversion.
Continue reading by clicking the link below, it gave me a clear summarized understanding.
https://www.relishapp.com/rspec/rspec-expectations/v/2-0/docs/matchers/equality-matchers
Hope it helps others.
Finally, the latest node.js release v10.3.0 has natively supported fs promises.
const fsPromises = require('fs').promises; // or require('fs/promises') in v10.0.0
fsPromises.writeFile(ASIN + '.json', JSON.stringify(results))
.then(() => {
console.log('JSON saved');
})
.catch(er => {
console.log(er);
});
You can check the official documentation for more details. https://nodejs.org/api/fs.html#fs_fs_promises_api
An alternative to the answer Max Fahl gave.
You can define callback function as an arrow function in the parent component so that you won't need to bind that.
@Component({_x000D_
..._x000D_
// unlike this, template: '<child [myCallback]="theCallback.bind(this)"></child>',_x000D_
template: '<child [myCallback]="theCallback"></child>',_x000D_
directives: [ChildComponent]_x000D_
})_x000D_
export class ParentComponent {_x000D_
_x000D_
// unlike this, public theCallback(){_x000D_
public theCallback = () => {_x000D_
..._x000D_
}_x000D_
}_x000D_
_x000D_
@Component({...})_x000D_
export class ChildComponent{_x000D_
//This will be bound to the ParentComponent.theCallback_x000D_
@Input()_x000D_
public myCallback: Function; _x000D_
..._x000D_
}
_x000D_
Here's an alternative since you don't like the cast to int:
foreach(byte b in System.Text.Encoding.UTF8.GetBytes(str.ToCharArray()))
Console.Write(b.ToString());
docker start -a -i `docker ps -q -l`
Explanation:
docker start
start a container (requires name or ID)
-a
attach to container
-i
interactive mode
docker ps
List containers
-q
list only container IDs
-l
list only last created container
null is unknown in sql so we cant expect two unknowns to be same.
However you can get that behavior by setting ANSI_NULLS to Off(its On by Default) You will be able to use = operator for nulls
SET ANSI_NULLS off
if null=null
print 1
else
print 2
set ansi_nulls on
if null=null
print 1
else
print 2
Please open your Visual Studio as administrator:
To open the Eye Dropper simply:
Its main functionality is to inspect pixel color values by clicking them though with its new features you can also see your page's existing colors palette or material design palette by clicking on the two arrows icon at the bottom. It can get quite handy when designing your page.
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'])
Here is the YUI counterpart to the jQuery posts above.
<script>
YAHOO.util.Event.onDOMReady(function() {
document.getElementById("foo").onclick = function (){alert('foo');};
});
</script>
when you are building any enterprise or any of your own software,you should just think like a hacker.as we know hackers are also not expert in all the things,but when they find any vulnerability they start digging into it by gathering information about all the things and finally attack on our software.so for preventing such attacks we should follow some well known rules like:
you can find more security resource on the following links:
for more information google about your application vendor security flows.
In my case, display: block was breaking the design as intended.
The max-width
property just saved me.
and for styling, you can use text-overflow: ellipsis
as well.
my code was
max-width: 255px
overflow:hidden
12 years later for anyone having similar problems.
try:
s.connect((address, '80'))
except:
alert('failed' + address, 'down')
doesn't work because the port '80' is a string. Your port needs to be int.
try:
s.connect((address, 80))
This should work. Not sure why even the best answer didnt see this.
If your'e looking bor boost's shared_ptr, you could have easily found the answer by googling shared_ptr, following the links to the docs, and pulling up a complete working example such as this.
In any case, here is a minimalistic complete working example for you which I just hacked up:
#include <boost/shared_ptr.hpp>
struct MyGizmo
{
int n_;
};
int main()
{
boost::shared_ptr<MyGizmo> p(new MyGizmo);
return 0;
}
In order for the #include
to find the header, the libraries obviously need to be in the search path. In MSVC, you set this in Project Settings>Configuration Properties>C/C++>Additional Include Directories. In my case, this is set to C:\Program Files (x86)\boost\boost_1_42
solution is easy:
replace
mask = (50 < df['heart rate'] < 101 &
140 < df['systolic blood pressure'] < 160 &
90 < df['dyastolic blood pressure'] < 100 &
35 < df['temperature'] < 39 &
11 < df['respiratory rate'] < 19 &
95 < df['pulse oximetry'] < 100
, "excellent", "critical")
by
mask = ((50 < df['heart rate'] < 101) &
(140 < df['systolic blood pressure'] < 160) &
(90 < df['dyastolic blood pressure'] < 100) &
(35 < df['temperature'] < 39) &
(11 < df['respiratory rate'] < 19) &
(95 < df['pulse oximetry'] < 100)
, "excellent", "critical")
You can execute an .exe from a Windows service very well in Windows XP. I have done it myself in the past.
You need to make sure you had checked the option "Allow to interact with the Desktop" in the Windows service properties. If that is not done, it will not execute.
I need to check in Windows 7 or Vista as these versions requires additional security privileges so it may throw an error, but I am quite sure it can be achieved either directly or indirectly. For XP I am certain as I had done it myself.
You can also do it by targeting the current input, with anything.target.reset()
. This is the most easiest way!
handleSubmit(e){
e.preventDefault();
e.target.reset();
}
<form onSubmit={this.handleSubmit}>
...
</form>
Actually, this too works great.
input[type=submit]{
width: 15px;
position: absolute;
right: 20px;
bottom: 20px;
background: #09c;
color: #fff;
font-family: tahoma,geneva,algerian;
height: 30px;
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
border-radius: 15px;
border: 1px solid #999;
}
Please note that you should not use any png when you are testing this , first work with jpg .
$myImage = "images/logos/mylogo.jpg"; // this is where you get your Image
$pdf->Image($myImage, 5, $pdf->GetY(), 33.78);
read -n1
is not portable. A portable way to do the same might be:
( trap "stty $(stty -g;stty -icanon)" EXIT
LC_ALL=C dd bs=1 count=1 >/dev/null 2>&1
) </dev/tty
Besides using read
, for just a press ENTER
to continue prompt you could do:
sed -n q </dev/tty
Try this,
<?php
$arr1=array('result1'=>'abcd','result2'=>'efg');
$arr2=array('result1'=>'hijk','result2'=>'lmn');
$arr3=array($arr1,$arr2);
print (json_encode($arr3));
?>
var answer = Math.floor(x)
I sincerely hope this will help future searchers when googling for this common question.
As Python newbie learning the Python ecosystem I've just completed this.
Install setuptools instructions
Install MySQL 5.1. Download the 97.6MB MSI from here You can't use the essentials version because it doesnt contain the C libraries.
Be sure to select a custom install, and mark the development tools / libraries for installation as that is not done by default. This is needed to get the C header files.
You can verify you have done this correctly by looking in your install directory for a folder named "include". E.G C:\Program Files\MySQL\MySQL Server 5.1\include. It should have a whole bunch of .h files.
Install Microsoft Visual Studio C++ Express 2008 from here This is needed to get a C compiler.
Open up a command line as administrator (right click on the Cmd shortcut and then "run as administrator". Be sure to open a fresh window after you have installed those things or your path won't be updated and the install will still fail.
From the command prompt:
easy_install -b C:\temp\sometempdir mysql-python
That will fail - which is OK.
Now open site.cfg in your temp directory C:\temp\sometempdir and edit the "registry_key" setting to:
registry_key = SOFTWARE\MySQL AB\MySQL Server 5.1
now CD into your temp dir and:
python setup.py clean
python setup.py install
You should be ready to rock!
Here is a super simple script to start off learning the Python DB API for you - if you need it.
Make sure your
AutowiringSpringBeanJobFactory extends SpringBeanJobFactory
dependency is pulled from
"org.springframework:spring-context-support:4..."
and NOT from
"org.springframework:spring-support:2..."
It wanted me to use
@Override
public Job newJob(TriggerFiredBundle bundle, Scheduler scheduler)
instead of
@Override
protected Object createJobInstance(final TriggerFiredBundle bundle)
so was failing to autowire job instance.
It depends on the server configuration or the relevant directives session.gc_maxlifetime in php.ini
.
Typically the default is 24 minutes (1440 seconds), but your webhost may have altered the default to something else.
Another way of doing that, which can make sense depending on your server architecture/framework of choice, is to repeat the same argument over and over again. Something like this:
/appointments?users=id1&users=id2
In this case I recommend using the parameter name in singular:
/appointments?user=id1&user=id2
This is supported natively by frameworks such as Jersey (for Java). Take a look on this question for more details.
Classes and Interfaces are both contracts. They provide methods and properties other parts of an application relies on.
You define an interface when you are not interested in the implementation details of this contract. The only thing to care about is that the contract (the interface) exists.
In this case you leave it up to the class which implements the interface to care about the details how the contract is fulfilled. Only classes can implement interfaces.
extends is used when you would like to replace details of an existing contract. This way you replace one way to fulfill a contract with a different way. Classes can extend other classes, and interfaces can extend other interfaces.
Travis-ci and Jenkins, while both are tools for continuous integration are very different.
Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.
Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml
which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.
You can have a similar feature with Jenkins if you use one of the following plugins:
.jervis.yml
file found at the root of project code. If .jervis.yml
does not exist, it will fall back to using .travis.yml
file instead.There are other hosted services you might also consider for continuous integration (non exhaustive list):
You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)
Depending on where your code repository is hosted I would make the following choices:
To setup Travis-CI on a github project, all you have to do is:
The features you get are:
An Angular approach to the methods previously described is to import DOCUMENT
from @angular/common
(or @angular/platform-browser
in Angular
< 4) and use
document.location.href = 'https://stackoverflow.com';
inside a function.
some-page.component.ts
import { DOCUMENT } from '@angular/common';
...
constructor(@Inject(DOCUMENT) private document: Document) { }
goToUrl(): void {
this.document.location.href = 'https://stackoverflow.com';
}
some-page.component.html
<button type="button" (click)="goToUrl()">Click me!</button>
Check out the plateformBrowser repo for more info.
I got the same issue when I ran mongod command after installing it on Windows10. I stopped the mongodb service and started it again. Working like a charm
Command to stop mongodb service (in windows): net stop mongodb
Command to start mongodb server: mongod --dbpath PATH_TO_DATA_FOLDER
Probably not, you will probably have the set the font on your control yourself, but you can make the process easier by centralizing where you get the font types from, for example have the app delegate or some other common class have a method that returns the font, and anything needing to set the font can call that method, that will help in case you need to change your font, youd change it in one place rather than everywhere you set the fonts...Another alternative can be to make subclasses of your UI Elements that will automatically set the font, but that might be overkill..
How about something like this ...
var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };
var g = l1.GroupBy( i => i );
foreach( var grp in g )
{
Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}
Edit per comment: I will try and do this justice. :)
In my example, it's a Func<int, TKey>
because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int>
(a grouping of ints keyed by an int). If I changed it to (i => i.ToString()
) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...
private string SampleMethod( int i )
{
// magically return "One" if i == 1, "Two" if i == 2, etc.
}
So, that's a Func that would take an int and return a string, just like ...
i => // magically return "One" if i == 1, "Two" if i == 2, etc.
But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.
It is because one of the DBs the column was created with " which makes its name case-sensitive.
Oracle Table Column Name : GoodRec Hive cannot recognize case sensitivity : ERROR thrown was - Caused by: java.sql.SQLSyntaxErrorException: ORA-00904: "GOODREC": invalid identifier
Solution : Rename Oracle column name to all caps.
img And You can use this kode
class Nokta:
def __init__(self,x,y):
self.x=x
self.y=y
class Dogru:
def __init__(self,a,b):
self.a=a
self.b=b
def Kesisim(self,Dogru_b):
x1= self.a.x
x2=self.b.x
x3=Dogru_b.a.x
x4=Dogru_b.b.x
y1= self.a.y
y2=self.b.y
y3=Dogru_b.a.y
y4=Dogru_b.b.y
#Notlardaki denklemleri kullandim
pay1=((x4 - x3) * (y1 - y3) - (y4 - y3) * (x1 - x3))
pay2=((x2-x1) * (y1 - y3) - (y2 - y1) * (x1 - x3))
payda=((y4 - y3) *(x2-x1)-(x4 - x3)*(y2 - y1))
if pay1==0 and pay2==0 and payda==0:
print("DOGRULAR BIRBIRINE ÇAKISIKTIR")
elif payda==0:
print("DOGRULAR BIRBIRNE PARALELDIR")
else:
ua=pay1/payda if payda else 0
ub=pay2/payda if payda else 0
#x ve y buldum
x=x1+ua*(x2-x1)
y=y1+ua*(y2-y1)
print("DOGRULAR {},{} NOKTASINDA KESISTI".format(x,y))
Adding to Rob?'s answer: in case you want to print rather large numbers, using thousand separators can be a great help (note the comma).
>>> f'{a*1000:,.2f}'
'10,123.40'
There's also oct2py which can call .m files within python
https://pypi.python.org/pypi/oct2py
It requires GNU Octave, which is highly compatible with MATLAB.
you can use this for url with parameters:
lynx -dump "http://vps-managed.com/tasks.php?code=23456"
lynx is available on all systems by default.
Use array_unshift() to insert the first element in an array.
User array_shift() to removes the first element of an array.
I've created an open source CodePlex project that does this. You can download the NuGet package from here.
<enumComboBox:EnumComboBox EnumType="{x:Type demoApplication:Status}" SelectedValue="{Binding Status}" />
I had to check System.ValueTuple.dll file was under source control and correct its reference in .cssproj files:
< Reference Include="System.ValueTuple" >
< HintPath >
....\ProjectName\ProjectName\obj\Release\Package\PackageTmp\bin\System.ValueTuple.dll
< /HintPath >
< /Reference >
into
< Reference Include="System.ValueTuple" >
< HintPath >
..\packages\System.ValueTuple.4.4.0\lib\netstandard1.0\System.ValueTuple.dll
< /HintPath >
< /Reference >
(Optional): 7. solve same problems with another .dll files this way
a = "A long string with a . in the middle ending with ."
# if you want to find the index of the last occurrence of any string, In our case we #will find the index of the last occurrence of with
index = a.rfind("with")
# the result will be 44, as index starts from 0.
As others have said multiprocessing
can only transfer Python objects to worker processes which can be pickled. If you cannot reorganize your code as described by unutbu, you can use dill
s extended pickling/unpickling capabilities for transferring data (especially code data) as I show below.
This solution requires only the installation of dill
and no other libraries as pathos
:
import os
from multiprocessing import Pool
import dill
def run_dill_encoded(payload):
fun, args = dill.loads(payload)
return fun(*args)
def apply_async(pool, fun, args):
payload = dill.dumps((fun, args))
return pool.apply_async(run_dill_encoded, (payload,))
if __name__ == "__main__":
pool = Pool(processes=5)
# asyn execution of lambda
jobs = []
for i in range(10):
job = apply_async(pool, lambda a, b: (a, b, a * b), (i, i + 1))
jobs.append(job)
for job in jobs:
print job.get()
print
# async execution of static method
class O(object):
@staticmethod
def calc():
return os.getpid()
jobs = []
for i in range(10):
job = apply_async(pool, O.calc, ())
jobs.append(job)
for job in jobs:
print job.get()
Because when you access a static field, you should do so on the class (or in this case the enum). As in
MyUnits.MILLISECONDS;
Not on an instance as in
m.MILLISECONDS;
Edit To address the question of why: In Java, when you declare something as static
, you are saying that it is a member of the class, not the object (hence why there is only one). Therefore it doesn't make sense to access it on the object, because that particular data member is associated with the class.
On server, su to root and do this:
# mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql mysql
(Note that the command at the end is of course mysql
, and, you're sending it to a table which happens to have the same name: mysql
.)
Next, you can now # ls /usr/share/zoneinfo
.
Use that command to see all the time zone info on ubuntu or almost any unixish server.
(BTW that's the convenient way to find the exact official name of some time zone.)
For example
mysql> select ts, CONVERT_TZ(ts, 'UTC', 'Pacific/Tahiti') from example_table ;
+---------------------+-----------------------------------------+
| ts | CONVERT_TZ(ts, 'UTC', 'Pacific/Tahiti') |
+---------------------+-----------------------------------------+
| 2020-10-20 16:59:57 | 2020-10-20 06:59:57 |
| 2020-10-20 17:02:59 | 2020-10-20 07:02:59 |
| 2020-10-20 17:30:08 | 2020-10-20 07:30:08 |
| 2020-10-20 18:36:29 | 2020-10-20 08:36:29 |
| 2020-10-20 18:37:20 | 2020-10-20 08:37:20 |
| 2020-10-20 18:37:20 | 2020-10-20 08:37:20 |
| 2020-10-20 19:00:18 | 2020-10-20 09:00:18 |
+---------------------+-----------------------------------------+
It's a generics literal. It means that you don't know the type of class this Class
instance is representing, but you are still using the generic version.
Class<Foo>
. That way you can create a new instance, for example, without casting: Foo foo = clazz.newInstance();
To check the database connection state you can just simple do the following
if(con.State == ConnectionState.Open){}
This is an informational message only. What the message is telling you is that the chromedriver executable will only accept connections from the local machine.
Most driver implementations (the Chrome driver and the IE driver for sure) create a HTTP server. The language bindings (Java, Python, Ruby, .NET, etc.) all use a JSON-over-HTTP protocol to communicate with the driver and automate the browser. Since the HTTP server is simply listening on an open port for HTTP requests generated by the language bindings, connections to the HTTP server started by the language bindings are only allowed to come from other processes on the same host. Note carefully that this limitation does not apply to connections the browser can make to outside websites; rather it simply prevents incoming connections from other websites.
It is possible to pass arrays to functions, and there are no special requirements for dealing with them. Are you sure that the array you are passing to to your function actually has an element at [0]
?
Try the following:
public static Stream ToStream(this Image image, ImageFormat format) {
var stream = new System.IO.MemoryStream();
image.Save(stream, format);
stream.Position = 0;
return stream;
}
Then you can use the following:
var stream = myImage.ToStream(ImageFormat.Gif);
Replace GIF with whatever format is appropriate for your scenario.
Make function name capital. This works for me.
export default function App() { }
You need to call the Configure
function of the XmlConfigurator
log4net.Config.XmlConfigurator.Configure();
Either call before your first loggin call or in your Global.asax like this:
protected void Application_Start(Object sender, EventArgs e) {
log4net.Config.XmlConfigurator.Configure();
}
MATLAB's FOR loop is static in nature; you cannot modify the loop variable between iterations, unlike the for(initialization;condition;increment) loop structure in other languages. This means that the following code always prints 1, 2, 3, 4, 5 regardless of the value of B.
A = 1:5;
for i = A
A = B;
disp(i);
end
If you want to be able to respond to changes in the data structure during iterations, a WHILE loop may be more appropriate --- you'll be able to test the loop condition at every iteration, and set the value of the loop variable(s) as you wish:
n = 10;
f = n;
while n > 1
n = n-1;
f = f*n;
end
disp(['n! = ' num2str(f)])
Btw, the for-each loop in Java (and possibly other languages) produces unspecified behavior when the data structure is modified during iteration. If you need to modify the data structure, you should use an appropriate Iterator instance which allows the addition and removal of elements in the collection you are iterating. The good news is that MATLAB supports Java objects, so you can do something like this:
A = java.util.ArrayList();
A.add(1);
A.add(2);
A.add(3);
A.add(4);
A.add(5);
itr = A.listIterator();
while itr.hasNext()
k = itr.next();
disp(k);
% modify data structure while iterating
itr.remove();
itr.add(k);
end