Hi try this -
function split(arr, howMany) {
var newArr = []; start = 0; end = howMany;
for(var i=1; i<= Math.ceil(arr.length / howMany); i++) {
newArr.push(arr.slice(start, end));
start = start + howMany;
end = end + howMany
}
console.log(newArr)
}
split([1,2,3,4,55,6,7,8,8,9],3)
You're in that annoying boundary area where regexps almost won't do (as has been pointed out by Bart, escaping the quotes would make life hard) , and yet a full-blown parser seems like overkill.
If you are likely to need greater complexity any time soon I would go looking for a parser library. For example this one
The 500 code would normally indicate an error on the server, not anything with your code. Some thoughts
When a function is a part of a class, it's called a method.
C# is an OOP language and doesn't have functions that are declared outside of classes, that's why all functions in C# are actually methods.
Though, beside this formal difference, they are the same...
Use
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
public class test {
public static void main(String[] args){
try {
File fileDir = new File("PATH_TO_FILE");
BufferedReader in = new BufferedReader(
new InputStreamReader(new FileInputStream(fileDir), "UTF-8"));
String str;
while ((str = in.readLine()) != null) {
System.out.println(str);
}
in.close();
}
catch (UnsupportedEncodingException e)
{
System.out.println(e.getMessage());
}
catch (IOException e)
{
System.out.println(e.getMessage());
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
}
}
You need to put UTF-8 in quotes
The simplest solution I've found that doesn't require a plugin:
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;
var yDown = null;
function handleTouchStart(evt) {
xDown = evt.touches[0].clientX;
yDown = evt.touches[0].clientY;
};
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* left swipe */
} else {
/* right swipe */
}
} else {
if ( yDiff > 0 ) {
/* up swipe */
} else {
/* down swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};
public class checkBoxSel {
public static void main(String[] args) {
WebDriver driver = new FirefoxDriver();
EventFiringWebDriver dr = null ;
dr = new EventFiringWebDriver(driver);
dr.get("http://www.google.co.in/");
dr.manage().timeouts().implicitlyWait(30, TimeUnit.SECONDS);
dr.findElement(By.linkText("Gmail")).click() ;
Select sel = new Select(driver.findElement(By.tagName("select")));
sel.selectByValue("fil");
}
}
I am using GOOGLE LOGIN PAGE to test the seletion option. The above example was to find and select language "Filipino" from the drop down list. I am sure this will solve the problem.
Not really. There are a number of dex disassembler/decompiler suites out there such as smali, or dex2jar that will generate semi-humanreadable output (in the case of dex2jar, you can get java code through the use of something like JD-GUI but the process is not perfect and it is very unlikely that you'll be able to 100% recreate your source code. However, it could potentially give you a place to start rebuilding your source tree.
Starting with Version 42, released April 14, 2015, Chrome blocks all NPAPI plugins, including Java. Until September 2015 there will be a way around this, by going to chrome://flags/#enable-npapi
and clicking on Enable
. After that, you will have to use the IE tab extension to run the Direct-X version of the Java plugin.
Late to the party, but here's some simple javascript-only code to scroll any element to the bottom:
function scrollToBottom(e) {
e.scrollTop = e.scrollHeight - e.getBoundingClientRect().height;
}
UPDATE table_name
SET field = replace(field, 'string-to-find', 'string-that-will-replace-it');
I strongly disagree with CaspNZ's approach.
First of all, this invisible view will be measured because it is "fill_parent". Android will try to calculate the right width of it. Instead, a small constant number (1dp) is recommended here.
Secondly, View should be replaced by a simpler class Space, a class dedicated to create empty spaces between UI component for fastest speed.
I hope this would provide you with the right solution:
Syntax:
CASE
WHEN search_condition THEN statement_list
[WHEN search_condition THEN statement_list]....
[ELSE statement_list]
END CASE
Implementation:
select id, action_heading,
case when
action_type="Expense" then action_amount
else NULL
end as Expense_amt,
case when
action_type ="Income" then action_amount
else NULL
end as Income_amt
from tbl_transaction;
Here I am using CASE
statement as it is more flexible than if-then-else
. It allows more than one branch. And CASE
statement is standard SQL and works in most databases.
I am using DBLINK to connect internal database for cross database queries.
Reference taken from this article.
Install DbLink extension.
CREATE EXTENSION dblink;
Verify DbLink:
SELECT pg_namespace.nspname, pg_proc.proname
FROM pg_proc, pg_namespace
WHERE pg_proc.pronamespace=pg_namespace.oid
AND pg_proc.proname LIKE '%dblink%';
Test connection of database:
SELECT dblink_connect('host=localhost user=postgres password=enjoy dbname=postgres');
It's not possible to create a many-to-many relationship with a customized join table. In a many-to-many relationship EF manages the join table internally and hidden. It's a table without an Entity class in your model. To work with such a join table with additional properties you will have to create actually two one-to-many relationships. It could look like this:
public class Member
{
public int MemberID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class Comment
{
public int CommentID { get; set; }
public string Message { get; set; }
public virtual ICollection<MemberComment> MemberComments { get; set; }
}
public class MemberComment
{
[Key, Column(Order = 0)]
public int MemberID { get; set; }
[Key, Column(Order = 1)]
public int CommentID { get; set; }
public virtual Member Member { get; set; }
public virtual Comment Comment { get; set; }
public int Something { get; set; }
public string SomethingElse { get; set; }
}
If you now want to find all comments of members with LastName
= "Smith" for example you can write a query like this:
var commentsOfMembers = context.Members
.Where(m => m.LastName == "Smith")
.SelectMany(m => m.MemberComments.Select(mc => mc.Comment))
.ToList();
... or ...
var commentsOfMembers = context.MemberComments
.Where(mc => mc.Member.LastName == "Smith")
.Select(mc => mc.Comment)
.ToList();
Or to create a list of members with name "Smith" (we assume there is more than one) along with their comments you can use a projection:
var membersWithComments = context.Members
.Where(m => m.LastName == "Smith")
.Select(m => new
{
Member = m,
Comments = m.MemberComments.Select(mc => mc.Comment)
})
.ToList();
If you want to find all comments of a member with MemberId
= 1:
var commentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1)
.Select(mc => mc.Comment)
.ToList();
Now you can also filter by the properties in your join table (which would not be possible in a many-to-many relationship), for example: Filter all comments of member 1 which have a 99 in property Something
:
var filteredCommentsOfMember = context.MemberComments
.Where(mc => mc.MemberId == 1 && mc.Something == 99)
.Select(mc => mc.Comment)
.ToList();
Because of lazy loading things might become easier. If you have a loaded Member
you should be able to get the comments without an explicit query:
var commentsOfMember = member.MemberComments.Select(mc => mc.Comment);
I guess that lazy loading will fetch the comments automatically behind the scenes.
Edit
Just for fun a few examples more how to add entities and relationships and how to delete them in this model:
1) Create one member and two comments of this member:
var member1 = new Member { FirstName = "Pete" };
var comment1 = new Comment { Message = "Good morning!" };
var comment2 = new Comment { Message = "Good evening!" };
var memberComment1 = new MemberComment { Member = member1, Comment = comment1,
Something = 101 };
var memberComment2 = new MemberComment { Member = member1, Comment = comment2,
Something = 102 };
context.MemberComments.Add(memberComment1); // will also add member1 and comment1
context.MemberComments.Add(memberComment2); // will also add comment2
context.SaveChanges();
2) Add a third comment of member1:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
var comment3 = new Comment { Message = "Good night!" };
var memberComment3 = new MemberComment { Member = member1,
Comment = comment3,
Something = 103 };
context.MemberComments.Add(memberComment3); // will also add comment3
context.SaveChanges();
}
3) Create new member and relate it to the existing comment2:
var comment2 = context.Comments.Where(c => c.Message == "Good evening!")
.SingleOrDefault();
if (comment2 != null)
{
var member2 = new Member { FirstName = "Paul" };
var memberComment4 = new MemberComment { Member = member2,
Comment = comment2,
Something = 201 };
context.MemberComments.Add(memberComment4);
context.SaveChanges();
}
4) Create relationship between existing member2 and comment3:
var member2 = context.Members.Where(m => m.FirstName == "Paul")
.SingleOrDefault();
var comment3 = context.Comments.Where(c => c.Message == "Good night!")
.SingleOrDefault();
if (member2 != null && comment3 != null)
{
var memberComment5 = new MemberComment { Member = member2,
Comment = comment3,
Something = 202 };
context.MemberComments.Add(memberComment5);
context.SaveChanges();
}
5) Delete this relationship again:
var memberComment5 = context.MemberComments
.Where(mc => mc.Member.FirstName == "Paul"
&& mc.Comment.Message == "Good night!")
.SingleOrDefault();
if (memberComment5 != null)
{
context.MemberComments.Remove(memberComment5);
context.SaveChanges();
}
6) Delete member1 and all its relationships to the comments:
var member1 = context.Members.Where(m => m.FirstName == "Pete")
.SingleOrDefault();
if (member1 != null)
{
context.Members.Remove(member1);
context.SaveChanges();
}
This deletes the relationships in MemberComments
too because the one-to-many relationships between Member
and MemberComments
and between Comment
and MemberComments
are setup with cascading delete by convention. And this is the case because MemberId
and CommentId
in MemberComment
are detected as foreign key properties for the Member
and Comment
navigation properties and since the FK properties are of type non-nullable int
the relationship is required which finally causes the cascading-delete-setup. Makes sense in this model, I think.
data-target
is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.
The data-target
attribute should contain a CSS selector that points to the HTML Element that will be changed.
<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
Launch demo modal
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
[...]
</div>
In this example, the button has data-target="#myModal"
, if you click on it, <div id="myModal">...</div>
will be modified (in this case faded in).
This happens because #myModal
in CSS selectors points to elements that have an id
attribute with the myModal
value.
Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes
You had thead
in your selector, but there is no thead
in your table. Also you had your selectors backwards. As you mentioned above, you wanted to be adding the tr
class to the th
, not vice-versa (although your comment seems to contradict what you wrote up above).
$('tr th').each(function(index){ if($('tr td').eq(index).attr('class') != ''){ // get the class of the td var tdClass = $('tr td').eq(index).attr('class'); // add it to this th $(this).addClass(tdClass ); } });
1.mysql_set_charset('utf8');
// set this line on top of your page in which you are using json.
latin1_swedish_ci
". <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="@+id/activity_register_header"
android:minHeight="50dp"
android:orientation="vertical"
android:visibility="gone" />
Try this piece of code..For me this code worked..
This will get you count:
get-alias | measure
You can work with the result as with object:
$m = get-alias | measure
$m.Count
And if you would like to have aliases in some variable also, you can use Tee-Object:
$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases
Some more info on Measure-Object cmdlet is on Technet.
Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)
Many modern browsers now support ES6 modules. As long as you import your scripts (including the entrypoint to your application) using <script type="module" src="...">
it will work.
Take a look at caniuse.com for more details: https://caniuse.com/#feat=es6-module
What's the default superuser username/password for postgres after a new install?:
CAUTION The answer about changing the UNIX password for "postgres" through "$ sudo passwd postgres" is not preferred, and can even be DANGEROUS!
This is why: By default, the UNIX account "postgres" is locked, which means it cannot be logged in using a password. If you use "sudo passwd postgres", the account is immediately unlocked. Worse, if you set the password to something weak, like "postgres", then you are exposed to a great security danger. For example, there are a number of bots out there trying the username/password combo "postgres/postgres" to log into your UNIX system.
What you should do is follow Chris James's answer:
sudo -u postgres psql postgres # \password postgres Enter new password:
To explain it a little bit...
double d = 14.4;
if((d-(int)d)!=0)
System.out.println("decimal value is there");
else
System.out.println("decimal value is not there");
The bash code I use
if ls /syslog/*.log > /dev/null 2>&1; then
echo "Log files are present in /syslog/;
fi
Thanks!
A quick Google on that ('kth largest element array') returned this: http://discuss.joelonsoftware.com/default.asp?interview.11.509587.17
"Make one pass through tracking the three largest values so far."
(it was specifically for 3d largest)
and this answer:
Build a heap/priority queue. O(n)
Pop top element. O(log n)
Pop top element. O(log n)
Pop top element. O(log n)
Total = O(n) + 3 O(log n) = O(n)
Taking answers from @Nicola and @Victor Wing and adding a more standardized way:
import org.springframework.beans.factory.InitializingBean;
import org.springframework.http.HttpStatus;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpResponse;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
public class UnauthorizedErrorAuthenticationEntryPoint implements AuthenticationEntryPoint, InitializingBean {
private HttpMessageConverter messageConverter;
@SuppressWarnings("unchecked")
@Override
public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException exception) throws IOException, ServletException {
MyGenericError error = new MyGenericError();
error.setDescription(exception.getMessage());
ServerHttpResponse outputMessage = new ServletServerHttpResponse(response);
outputMessage.setStatusCode(HttpStatus.UNAUTHORIZED);
messageConverter.write(error, null, outputMessage);
}
public void setMessageConverter(HttpMessageConverter messageConverter) {
this.messageConverter = messageConverter;
}
@Override
public void afterPropertiesSet() throws Exception {
if (messageConverter == null) {
throw new IllegalArgumentException("Property 'messageConverter' is required");
}
}
}
Now, you can inject configured Jackson, Jaxb or whatever you use to convert response bodies on your MVC annotation or XML based configuration with its serializers, deserializers and so on.
You have to set the associatedEmployee on the Vehicle before persisting the Employee.
Employee newEmployee = new Employee("matt");
vehicle1.setAssociatedEmployee(newEmployee);
vehicles.add(vehicle1);
newEmployee.setVehicles(vehicles);
Employee savedEmployee = employeeDao.persistOrMerge(newEmployee);
u should add a theme
to ur all activities (u should add theme
for all application in ur <application>
in ur manifest)
but if u have set different theme to ur activity u can use :
android:theme="@style/Theme.AppCompat"
or each kind of AppCompat
theme!
You could simply get the character length of the current directory, and remove them from your absolute list
setlocal EnableDelayedExpansion
for /L %%n in (1 1 500) do if "!__cd__:~%%n,1!" neq "" set /a "len=%%n+1"
setlocal DisableDelayedExpansion
for /r . %%g in (*.log) do (
set "absPath=%%g"
setlocal EnableDelayedExpansion
set "relPath=!absPath:~%len%!"
echo(!relPath!
endlocal
)
random functions like borland complier
using namespace std;
int sys_random(int min, int max) {
return (rand() % (max - min+1) + min);
}
void sys_randomize() {
srand(time(0));
}
Here one big collection of debug constants that we use. Enjoy.
// Uncomment the defitions to show additional info.
// #define DEBUG
// #define DEBUGWHERE_SHOWFULLINFO
// #define DEBUG_SHOWLINES
// #define DEBUG_SHOWFULLPATH
// #define DEBUG_SHOWSEPARATORS
// #define DEBUG_SHOWFULLINFO
// Definition of DEBUG functions. Only work if DEBUG is defined.
#ifdef DEBUG
#define debug_separator() NSLog( @"----------------------------------------------------------------------------" );
#ifdef DEBUG_SHOWSEPARATORS
#define debug_showSeparators() debug_separator();
#else
#define debug_showSeparators()
#endif
/// /// /// ////// /////
#ifdef DEBUG_SHOWFULLPATH
#define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,__FILE__,__FUNCTION__); debug_showSeparators();
#else
#define debug_whereFull() debug_showSeparators(); NSLog(@"Line:%d : %s : %s", __LINE__,[ [ [ [NSString alloc] initWithBytes:__FILE__ length:strlen(__FILE__) encoding:NSUTF8StringEncoding] lastPathComponent] UTF8String ] ,__FUNCTION__); debug_showSeparators();
#endif
/// /// /// ////// /////
#define debugExt(args,...) debug_separator(); debug_whereFull(); NSLog( args, ##__VA_ARGS__); debug_separator();
/// /// /// ////// ///// Debug Print Macros
#ifdef DEBUG_SHOWFULLINFO
#define debug(args,...) debugExt(args, ##__VA_ARGS__);
#else
#ifdef DEBUG_SHOWLINES
#define debug(args,...) debug_showSeparators(); NSLog([ NSString stringWithFormat:@"Line:%d : %@", __LINE__, args ], ##__VA_ARGS__); debug_showSeparators();
#else
#define debug(args,...) debug_showSeparators(); NSLog(args, ##__VA_ARGS__); debug_showSeparators();
#endif
#endif
/// /// /// ////// ///// Debug Specific Types
#define debug_object( arg ) debug( @"Object: %@", arg );
#define debug_int( arg ) debug( @"integer: %i", arg );
#define debug_float( arg ) debug( @"float: %f", arg );
#define debug_rect( arg ) debug( @"CGRect ( %f, %f, %f, %f)", arg.origin.x, arg.origin.y, arg.size.width, arg.size.height );
#define debug_point( arg ) debug( @"CGPoint ( %f, %f )", arg.x, arg.y );
#define debug_bool( arg ) debug( @"Boolean: %@", ( arg == YES ? @"YES" : @"NO" ) );
/// /// /// ////// ///// Debug Where Macros
#ifdef DEBUGWHERE_SHOWFULLINFO
#define debug_where() debug_whereFull();
#else
#define debug_where() debug(@"%s",__FUNCTION__);
#endif
#define debug_where_separators() debug_separator(); debug_where(); debug_separator();
/// /// /// ////// /////
#else
#define debug(args,...)
#define debug_separator()
#define debug_where()
#define debug_where_separators()
#define debug_whereFull()
#define debugExt(args,...)
#define debug_object( arg )
#define debug_int( arg )
#define debug_rect( arg )
#define debug_bool( arg )
#define debug_point( arg )
#define debug_float( arg )
#endif
Here's an approach that doesn't require the brute-force 'ignore' which would only work if there was a key violation. This way works based on any conditions you specify in the update.
Try this...
-- Try to update any existing row
UPDATE players
SET age=32
WHERE user_name='steven';
-- If no update happened (i.e. the row didn't exist) then insert one
INSERT INTO players (user_name, age)
SELECT 'steven', 32
WHERE (Select Changes() = 0);
The 'magic sauce' here is using Changes()
in the Where
clause. Changes()
represents the number of rows affected by the last operation, which in this case is the update.
In the above example, if there are no changes from the update (i.e. the record doesn't exist) then Changes()
= 0 so the Where
clause in the Insert
statement evaluates to true and a new row is inserted with the specified data.
If the Update
did update an existing row, then Changes()
= 1 (or more accurately, not zero if more than one row was updated), so the 'Where' clause in the Insert
now evaluates to false and thus no insert will take place.
The beauty of this is there's no brute-force needed, nor unnecessarily deleting, then re-inserting data which may result in messing up downstream keys in foreign-key relationships.
Additionally, since it's just a standard Where
clause, it can be based on anything you define, not just key violations. Likewise, you can use Changes()
in combination with anything else you want/need anywhere expressions are allowed.
Open the MySQL Command Line Client and type in your password
Change to the database you want to use for importing the .sql file data into. Do this by typing:
USE your_database_name
Now locate the .sql file you want to execute.
If the file is located in the main local C: drive directory and the .sql script file name is currentSqlTable.sql
, you would type the following:
\. C:\currentSqlTable.sql
and press Enter to execute the SQL script file.
Setting the underlying socket ReceiveTimeout
property did the trick. You can access it like this: yourTcpClient.Client.ReceiveTimeout
. You can read the docs for more information.
Now the code will only "sleep" as long as needed for some data to arrive in the socket, or it will raise an exception if no data arrives, at the beginning of a read operation, for more than 20ms. I can tweak this timeout if needed. Now I'm not paying the 20ms price in every iteration, I'm only paying it at the last read operation. Since I have the content-length of the message in the first bytes read from the server I can use it to tweak it even more and not try to read if all expected data has been already received.
I find using ReceiveTimeout much easier than implementing asynchronous read... Here is the working code:
string SendCmd(string cmd, string ip, int port)
{
var client = new TcpClient(ip, port);
var data = Encoding.GetEncoding(1252).GetBytes(cmd);
var stm = client.GetStream();
stm.Write(data, 0, data.Length);
byte[] resp = new byte[2048];
var memStream = new MemoryStream();
var bytes = 0;
client.Client.ReceiveTimeout = 20;
do
{
try
{
bytes = stm.Read(resp, 0, resp.Length);
memStream.Write(resp, 0, bytes);
}
catch (IOException ex)
{
// if the ReceiveTimeout is reached an IOException will be raised...
// with an InnerException of type SocketException and ErrorCode 10060
var socketExept = ex.InnerException as SocketException;
if (socketExept == null || socketExept.ErrorCode != 10060)
// if it's not the "expected" exception, let's not hide the error
throw ex;
// if it is the receive timeout, then reading ended
bytes = 0;
}
} while (bytes > 0);
return Encoding.GetEncoding(1252).GetString(memStream.ToArray());
}
In Python, indexing starts at 0. Therefore, if you have a list with 53 items, list[52]
will be the last item in the list.
if you are using VS Code and terminal select node from the right side dropdown first and then do Ctrl + C. Then It will work
Press y when you are prompted.
Thanks
In case you have only one controller and you want to access every action on root you can skip controller name like this
routes.MapRoute(
"Default",
"{action}/{id}",
new { controller = "Home", action = "Index",
id = UrlParameter.Optional }
);
Both setInterval
and setTimeout
can work for you (as @Doug Neiner and @John Boker wrote both now point to setInterval
).
See here for some more explanation about both to see which suites you most and how to stop each of them.
setInterval as suggested by SLaks was exactly what I needed to make my timer. (Thanks mate!)
Using setInterval and this great blog post I ended up creating the following function to display a timer inside my "box_header" div. I hope this helps anyone else with similar requirements!
function get_elapsed_time_string(total_seconds) {
function pretty_time_string(num) {
return ( num < 10 ? "0" : "" ) + num;
}
var hours = Math.floor(total_seconds / 3600);
total_seconds = total_seconds % 3600;
var minutes = Math.floor(total_seconds / 60);
total_seconds = total_seconds % 60;
var seconds = Math.floor(total_seconds);
// Pad the minutes and seconds with leading zeros, if required
hours = pretty_time_string(hours);
minutes = pretty_time_string(minutes);
seconds = pretty_time_string(seconds);
// Compose the string for display
var currentTimeString = hours + ":" + minutes + ":" + seconds;
return currentTimeString;
}
var elapsed_seconds = 0;
setInterval(function() {
elapsed_seconds = elapsed_seconds + 1;
$('#box_header').text(get_elapsed_time_string(elapsed_seconds));
}, 1000);
I have implemented this function in my application through fragments using SurfaceView. The link to this stackoverflow question and its answer can be found here
Hope this helps :)
A generic,simpler and a bit primitive approach to find tag, attribute and value
Pattern pattern = Pattern.compile("<(\\w+)( +.+)*>((.*))</\\1>");
System.out.println(pattern.matcher("<asd> TEST</asd>").find());
System.out.println(pattern.matcher("<asd TEST</asd>").find());
System.out.println(pattern.matcher("<asd attr='3'> TEST</asd>").find());
System.out.println(pattern.matcher("<asd> <x>TEST<x>asd>").find());
System.out.println("-------");
Matcher matcher = pattern.matcher("<as x> TEST</as>");
if (matcher.find()) {
for (int i = 0; i <= matcher.groupCount(); i++) {
System.out.println(i + ":" + matcher.group(i));
}
}
Step-by-step answer similar to the one you refer to, using the new cv2 Python bindings:
1. Read a grayscale image
import cv2
im_gray = cv2.imread('grayscale_image.png', cv2.IMREAD_GRAYSCALE)
2. Convert grayscale image to binary
(thresh, im_bw) = cv2.threshold(im_gray, 128, 255, cv2.THRESH_BINARY | cv2.THRESH_OTSU)
which determines the threshold automatically from the image using Otsu's method, or if you already know the threshold you can use:
thresh = 127
im_bw = cv2.threshold(im_gray, thresh, 255, cv2.THRESH_BINARY)[1]
3. Save to disk
cv2.imwrite('bw_image.png', im_bw)
In case if you have the web-address/URL displayed on your view and you want it to make it clikable and direct user to particular website You can use:
android:autoLink="web"
In same way you can use different attributes of autoLink(email, phone, map, all) to accomplish your task...
Very Short and concise Answer
lateinit: It initialize non-null properties lately
Unlike lazy initialization, lateinit allows the compiler to recognize that the value of the non-null property is not stored in the constructor stage to compile normally.
lazy Initialization
by lazy may be very useful when implementing read-only(val) properties that perform lazy-initialization in Kotlin.
by lazy { ... } performs its initializer where the defined property is first used, not its declaration.
A Table can have a Composite Primary Key which is a primary key made from two or more columns. For example:
CREATE TABLE userdata (
userid INT,
userdataid INT,
info char(200),
primary key (userid, userdataid)
);
Update: Here is a link with a more detailed description of composite primary keys.
What worked for me was to go to the root folder, where .git/ is. I was inside one the child folders and got there error.
Note that it may be better use subdomains instead of usual URL. So, set .example.com
instead of https://example.com/
.
Thanks to Jody Jacobus Geers and others I wrote so:
if (savedInstanceState == null) {
val cookieManager = CookieManager.getInstance()
cookieManager.acceptCookie()
val domain = ".example.com"
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
cookieManager.setCookie(domain, "token=$token") {
view.webView.loadUrl(url)
}
cookieManager.setAcceptThirdPartyCookies(view.webView, true)
} else {
cookieManager.setCookie(domain, "token=$token")
view.webView.loadUrl(url)
}
} else {
// Check whether we're recreating a previously destroyed instance.
view.webView.restoreState(savedInstanceState)
}
Include the phrase:
@echo off
Right at the top of your bat script.
ES6 for the win!
const b = 'b';
const c = 'c';
const data = {
a: true,
[b]: true, // dynamic property
[`interpolated-${c}`]: true, // dynamic property + interpolation
[`${b}-${c}`]: true
}
If you log data
you get this:
{
a: true,
b: true,
interpolated-c: true,
b-c: true
}
This makes use of the new Computed Property syntax and Template Literals.
Set objShell = WScript.CreateObject("WScript.Shell")
objShell.Run("firefox")
Set objShell = Nothing
Please try this
i have alreay 2 situations where directives and services/factories didnt play well.
the scenario is that i have (had) a directive that has dependency injection of a service, and from the directive i ask the service to make an ajax call (with $http).
in the end, in both cases the ng-Repeat did not file at all, even when i gave the array an initial value.
i even tried to make a directive with a controller and an isolated-scope
only when i moved everything to a controller and it worked like magic.
example about this here Initialising jQuery plugin (RoyalSlider) in Angular JS
Your browser hasn't interpretted the encoding of the page correctly (either because you've forced it to a particular setting, or the page is set incorrectly), and thus cannot display some of the characters.
You Can Use Regex Like This:
^[0-9\-\(\)\, ]+$
You probably have syntax error.
You most likely forgot to put a }
or ;
somewhere above this function.
Additionally, adding na.rm= TRUE to your geom_bar() will work.
ggplot(data = MyData,aes(x= the_variable, fill=the_variable, na.rm = TRUE)) +
geom_bar(stat="bin", na.rm = TRUE)
I ran into this issue with a loop in a time series and this fixed it. The missing data is removed and the results are otherwise uneffected.
Very simple:
python.exe
(provided you have given path of it in environmental variables)Then, In the same command prompt window the python interpreter will start with >>>
This worked for me.
newlist = oldlist[::10]
This picks out every 10th element of the list.
I am not sure but when we have execute time out or command time out The client sends an "ABORT" to SQL Server then simply abandons the query processing. No transaction is rolled back, no locks are released. to solve this problem I Remove transaction in Stored-procedure and use SQL Transaction in my .Net Code To manage sqlException
In this specific case (mod 7), we still can replace %7 with bitwise operators:
// Return X%7 for X >= 0.
int mod7(int x)
{
while (x > 7) x = (x&7) + (x>>3);
return (x == 7)?0:x;
}
It works because 8%7 = 1. Obviously, this code is probably less efficient than a simple x%7, and certainly less readable.
Here's the stock "settings.xml" with comments (complete/unchopped file at the bottom)
License:
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
Main docs and top:
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single
| user, and is normally provided in
| ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all
| Maven users on a machine (assuming they're all using the
| same Maven installation). It's normally provided in
| ${maven.home}/conf/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start
| at getting the most out of your Maven installation. Where appropriate, the
| default values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
Local repository, interactive mode, plugin groups:
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set
| to false, maven will use a sensible default value, perhaps based on some
| other setting, for the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when
| executing a build. This will have an effect on artifact downloads,
| artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when
| resolving plugins by their prefix, i.e. when invoking a command line like
| "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
| already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
Proxies:
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to
| the network. Unless otherwise specified (by system property or command-
| line switch), the first proxy specification in this list marked as active
| will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
Servers:
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used
| within the system. Authentication profiles can be used whenever maven must
| make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a
| particular server, identified by a unique name within the system
| (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR
| privateKey/passphrase, since these pairings are used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
Mirrors:
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote
| repositories.
|
| It works like this: a POM may declare a repository to use in resolving
| certain artifacts. However, this repository may have problems with heavy
| traffic at times, so people have mirrored it to several places.
|
| That repository definition will have a unique id, so we can create a
| mirror reference for that repository, to be used as an alternate download
| site. The mirror site will be the preferred server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository.
| The repository that this mirror serves has an ID that matches the
| mirrorOf element of this mirror. IDs are used for inheritance and direct
| lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
</mirrors>
Profiles (1/3):
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways,
| and which can modify the build process. Profiles provided in the
| settings.xml are intended to provide local machine-specific paths and
| repository locations which allow the build to work in the local
| environment.
|
| For example, if you have an integration testing plugin - like cactus -
| that needs to know where your Tomcat instance is installed, you can
| provide a variable here such that the variable is dereferenced during the
| build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One
| way - the activeProfiles section of this document (settings.xml) - will be
| discussed later. Another way essentially relies on the detection of a
| system property, either matching a particular value for the property, or
| merely testing its existence. Profiles can also be activated by JDK
| version prefix, where a value of '1.4' might activate a profile when the
| build is executed on a JDK version of '1.4.2_07'. Finally, the list of
| active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to
| specifying only artifact repositories, plugin repositories, and
| free-form properties to be used as configuration variables for
| plugins in the POM.
|
|-->
Profiles (2/3):
<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated
| using one or more of the mechanisms described above. For inheritance
| purposes, and to activate profiles via <activatedProfiles/> or the
| command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a
| consistent naming convention for profiles, such as 'env-dev',
| 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
| will make it more intuitive to understand what the set of introduced
| profiles is attempting to accomplish, particularly when you only have a
| list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and
| provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
Profiles (3/3):
<!--
| Here is another profile, activated by the system property 'target-env'
| with a value of 'dev', which provides a specific path to the Tomcat
| instance. To use this, your plugin configuration might hypothetically
| look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone
| set 'target-env' to anything, you could just leave off the
| <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
Bottom:
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
<?xml version="1.0" encoding="UTF-8"?>
<!--
Licensed to the Apache Software Foundation (ASF) under one
or more contributor license agreements. See the NOTICE file
distributed with this work for additional information
regarding copyright ownership. The ASF licenses this file
to you under the Apache License, Version 2.0 (the
"License"); you may not use this file except in compliance
with the License. You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing,
software distributed under the License is distributed on an
"AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
KIND, either express or implied. See the License for the
specific language governing permissions and limitations
under the License.
-->
<!--
| This is the configuration file for Maven. It can be specified at two levels:
|
| 1. User Level. This settings.xml file provides configuration for a single
| user, and is normally provided in
| ${user.home}/.m2/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -s /path/to/user/settings.xml
|
| 2. Global Level. This settings.xml file provides configuration for all
| Maven users on a machine (assuming they're all using the
| same Maven installation). It's normally provided in
| ${maven.home}/conf/settings.xml.
|
| NOTE: This location can be overridden with the CLI option:
|
| -gs /path/to/global/settings.xml
|
| The sections in this sample file are intended to give you a running start
| at getting the most out of your Maven installation. Where appropriate, the
| default values (values used when the setting is not specified) are provided.
|
|-->
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0 http://maven.apache.org/xsd/settings-1.0.0.xsd">
<!-- localRepository
| The path to the local repository maven will use to store artifacts.
|
| Default: ~/.m2/repository
<localRepository>/path/to/local/repo</localRepository>
-->
<!-- interactiveMode
| This will determine whether maven prompts you when it needs input. If set
| to false, maven will use a sensible default value, perhaps based on some
| other setting, for the parameter in question.
|
| Default: true
<interactiveMode>true</interactiveMode>
-->
<!-- offline
| Determines whether maven should attempt to connect to the network when
| executing a build. This will have an effect on artifact downloads,
| artifact deployment, and others.
|
| Default: false
<offline>false</offline>
-->
<!-- pluginGroups
| This is a list of additional group identifiers that will be searched when
| resolving plugins by their prefix, i.e. when invoking a command line like
| "mvn prefix:goal". Maven will automatically add the group identifiers
| "org.apache.maven.plugins" and "org.codehaus.mojo" if these are not
| already contained in the list.
|-->
<pluginGroups>
<!-- pluginGroup
| Specifies a further group identifier to use for plugin lookup.
<pluginGroup>com.your.plugins</pluginGroup>
-->
</pluginGroups>
<!-- proxies
| This is a list of proxies which can be used on this machine to connect to
| the network. Unless otherwise specified (by system property or command-
| line switch), the first proxy specification in this list marked as active
| will be used.
|-->
<proxies>
<!-- proxy
| Specification for one proxy, to be used in connecting to the network.
|
<proxy>
<id>optional</id>
<active>true</active>
<protocol>http</protocol>
<username>proxyuser</username>
<password>proxypass</password>
<host>proxy.host.net</host>
<port>80</port>
<nonProxyHosts>local.net|some.host.com</nonProxyHosts>
</proxy>
-->
</proxies>
<!-- servers
| This is a list of authentication profiles, keyed by the server-id used
| within the system. Authentication profiles can be used whenever maven must
| make a connection to a remote server.
|-->
<servers>
<!-- server
| Specifies the authentication information to use when connecting to a
| particular server, identified by a unique name within the system
| (referred to by the 'id' attribute below).
|
| NOTE: You should either specify username/password OR
| privateKey/passphrase, since these pairings are used together.
|
<server>
<id>deploymentRepo</id>
<username>repouser</username>
<password>repopwd</password>
</server>
-->
<!-- Another sample, using keys to authenticate.
<server>
<id>siteServer</id>
<privateKey>/path/to/private/key</privateKey>
<passphrase>optional; leave empty if not used.</passphrase>
</server>
-->
</servers>
<!-- mirrors
| This is a list of mirrors to be used in downloading artifacts from remote
| repositories.
|
| It works like this: a POM may declare a repository to use in resolving
| certain artifacts. However, this repository may have problems with heavy
| traffic at times, so people have mirrored it to several places.
|
| That repository definition will have a unique id, so we can create a
| mirror reference for that repository, to be used as an alternate download
| site. The mirror site will be the preferred server for that repository.
|-->
<mirrors>
<!-- mirror
| Specifies a repository mirror site to use instead of a given repository.
| The repository that this mirror serves has an ID that matches the
| mirrorOf element of this mirror. IDs are used for inheritance and direct
| lookup purposes, and must be unique across the set of mirrors.
|
<mirror>
<id>mirrorId</id>
<mirrorOf>repositoryId</mirrorOf>
<name>Human Readable Name for this Mirror.</name>
<url>http://my.repository.com/repo/path</url>
</mirror>
-->
</mirrors>
<!-- profiles
| This is a list of profiles which can be activated in a variety of ways,
| and which can modify the build process. Profiles provided in the
| settings.xml are intended to provide local machine-specific paths and
| repository locations which allow the build to work in the local
| environment.
|
| For example, if you have an integration testing plugin - like cactus -
| that needs to know where your Tomcat instance is installed, you can
| provide a variable here such that the variable is dereferenced during the
| build process to configure the cactus plugin.
|
| As noted above, profiles can be activated in a variety of ways. One
| way - the activeProfiles section of this document (settings.xml) - will be
| discussed later. Another way essentially relies on the detection of a
| system property, either matching a particular value for the property, or
| merely testing its existence. Profiles can also be activated by JDK
| version prefix, where a value of '1.4' might activate a profile when the
| build is executed on a JDK version of '1.4.2_07'. Finally, the list of
| active profiles can be specified directly from the command line.
|
| NOTE: For profiles defined in the settings.xml, you are restricted to
| specifying only artifact repositories, plugin repositories, and
| free-form properties to be used as configuration variables for
| plugins in the POM.
|
|-->
<profiles>
<!-- profile
| Specifies a set of introductions to the build process, to be activated
| using one or more of the mechanisms described above. For inheritance
| purposes, and to activate profiles via <activatedProfiles/> or the
| command line, profiles have to have an ID that is unique.
|
| An encouraged best practice for profile identification is to use a
| consistent naming convention for profiles, such as 'env-dev',
| 'env-test', 'env-production', 'user-jdcasey', 'user-brett', etc. This
| will make it more intuitive to understand what the set of introduced
| profiles is attempting to accomplish, particularly when you only have a
| list of profile id's for debug.
|
| This profile example uses the JDK version to trigger activation, and
| provides a JDK-specific repo.
<profile>
<id>jdk-1.4</id>
<activation>
<jdk>1.4</jdk>
</activation>
<repositories>
<repository>
<id>jdk14</id>
<name>Repository for JDK 1.4 builds</name>
<url>http://www.myhost.com/maven/jdk14</url>
<layout>default</layout>
<snapshotPolicy>always</snapshotPolicy>
</repository>
</repositories>
</profile>
-->
<!--
| Here is another profile, activated by the system property 'target-env'
| with a value of 'dev', which provides a specific path to the Tomcat
| instance. To use this, your plugin configuration might hypothetically
| look like:
|
| ...
| <plugin>
| <groupId>org.myco.myplugins</groupId>
| <artifactId>myplugin</artifactId>
|
| <configuration>
| <tomcatLocation>${tomcatPath}</tomcatLocation>
| </configuration>
| </plugin>
| ...
|
| NOTE: If you just wanted to inject this configuration whenever someone
| set 'target-env' to anything, you could just leave off the
| <value/> inside the activation-property.
|
<profile>
<id>env-dev</id>
<activation>
<property>
<name>target-env</name>
<value>dev</value>
</property>
</activation>
<properties>
<tomcatPath>/path/to/tomcat/instance</tomcatPath>
</properties>
</profile>
-->
</profiles>
<!-- activeProfiles
| List of profiles that are active for all builds.
|
<activeProfiles>
<activeProfile>alwaysActiveProfile</activeProfile>
<activeProfile>anotherAlwaysActiveProfile</activeProfile>
</activeProfiles>
-->
</settings>
I assume you want to link to a library called foo, its filename is usually something link foo.dll
or libfoo.so
.
1. Find the library
You have to find the library. This is a good idea, even if you know the path to your library. CMake will error out if the library vanished or got a new name. This helps to spot error early and to make it clear to the user (may yourself) what causes a problem.
To find a library foo and store the path in FOO_LIB
use
find_library(FOO_LIB foo)
CMake will figure out itself how the actual file name is. It checks the usual places like /usr/lib
, /usr/lib64
and the paths in PATH
.
You already know the location of your library. Add it to the CMAKE_PREFIX_PATH
when you call CMake, then CMake will look for your library in the passed paths, too.
Sometimes you need to add hints or path suffixes, see the documentation for details: https://cmake.org/cmake/help/latest/command/find_library.html
2. Link the library
From 1. you have the full library name in FOO_LIB
. You use this to link the library to your target GLBall
as in
target_link_libraries(GLBall PRIVATE "${FOO_LIB}")
You should add PRIVATE
, PUBLIC
, or INTERFACE
after the target, cf. the documentation:
https://cmake.org/cmake/help/latest/command/target_link_libraries.html
If you don't add one of these visibility specifiers, it will either behave like PRIVATE
or PUBLIC
, depending on the CMake version and the policies set.
3. Add includes (This step might be not mandatory.)
If you also want to include header files, use find_path
similar to find_library
and search for a header file. Then add the include directory with target_include_directories
similar to target_link_libraries
.
Documentation: https://cmake.org/cmake/help/latest/command/find_path.html and https://cmake.org/cmake/help/latest/command/target_include_directories.html
If available for the external software, you can replace find_library
and find_path
by find_package
.
Funny Easter Egg.
In Ubuntu version of Chrome, in Task Manager (shift+esc), with right-click you can add a sci-fi column that in italian version is "Capre Teletrasportate" (Teleported Goats).
A funny theory about it is here.
Inside Spring Boot
, I always put the webpages inside a folder like public
or webapps
or views
and place it inside src/main/resources
directory as you can see in application.properties
also.
and this is my application.properties
:
server.port=15800
spring.mvc.view.prefix=/public/
spring.mvc.view.suffix=.html
spring.datasource.url=jdbc:mysql://localhost:3306/hibernatedb
spring.datasource.username=root
spring.datasource.password=password
spring.datasource.driver-class-name=com.mysql.jdbc.Driver
spring.jpa.properties.hibernate.dialect = org.hibernate.dialect.MySQL5InnoDBDialect
spring.jpa.hibernate.ddl-auto = update
spring.jpa.properties.hibernate.format_sql = true
logging.level.org.hibernate.SQL=DEBUG
logging.level.org.hibernate.type.descriptor.sql.BasicBinder=TRACE
as soon you put the url like servername:15800
and this request received by Spring Boot occupied Servlet dispatcher it will exactly search the index.html
and this name will in case sensitive as the spring.mvc.view.suffix
which would be html, jsp, htm etc.
Hope it would help manyone.
Same problem I faced, I added
@XmlRootElement(name="yourRootElementName")
@XmlAccessorType(XmlAccessType.FIELD)
and now it is working.
I was recieving the same error when I was tring to call an object element by using another objects return value like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->$this->array1->country;// Error line
The above code was throwing the error and I tried many ways to fix it like; calling this part $this->array1->country
in another function as return value, (string)
, taking it into quotations etc. I couldn't even find the solution on the web then i realised that the solution was very simple. All you have to do it wrap it with curly brackets and that allows you to target an object with another object's element value. like;
$this->array1 = a json table which returns country codes of the ip
$this->array2 = a json table which returns languages of the country codes
$this->array2->{$this->array1->country};
If anyone facing the same and couldn't find the answer, I hope this can help because i spend a night for this simple solution =)
I use this if the exe is supposed to be called by double clicking it
var thisPath = System.IO.Directory.GetCurrentDirectory();
This might help:
CSS
.slick-counter{
position:absolute;
top:5px;
left:5px;
background:yellow;
padding:5px;
opacity:0.8;
border-radius:5px;
}
JavaScript
var $el = $('.slideshow');
$el.slick({
slide: 'img',
autoplay: true,
onInit: function(e){
$el.append('<div class="slick-counter">'+ parseInt(e.currentSlide + 1, 10) +' / '+ e.slideCount +'</div>');
},
onAfterChange: function(e){
$el.find('.slick-counter').html(e.currentSlide + 1 +' / '+e.slideCount);
}
});
Evaluate
might suit:
http://www.mrexcel.com/forum/showthread.php?t=62067
Function Eval(Ref As String)
Application.Volatile
Eval = Evaluate(Ref)
End Function
The whole thing should look like:
<form enctype='multipart/form-data' method='POST' action='submitFormTo.php'>
<input type='file' name='files[]' multiple />
<button type='submit'>Submit</button>
</form>
Make sure you have the enctype='multipart/form-data'
attribute in your <form>
tag, or you can't read the files on the server side after submission!
What if the incoming changes are the ones you want? I'm unable to run svn resolve --accept theirs-full
svn resolve --accept base
I have created a simple program for this and your question helped me complete the solution... I added one more feature and few configurations. In case you want to add a specific character/ string after every few lines (configurable). Please go through the notes. I have added the code files : https://github.com/mohitsharma779/FileSplit
Cross site request forgery (CSRF/XSRF) is when a malicious web page tricks users into performing a request that is not intended for example by using bookmarklets, iframes or just by creating a page which is visually similar enough to fool users.
The Rails CSRF protection is made for "classical" web apps - it simply gives a degree of assurance that the request originated from your own web app. A CSRF token works like a secret that only your server knows - Rails generates a random token and stores it in the session. Your forms send the token via a hidden input and Rails verifies that any non GET request includes a token that matches what is stored in the session.
However an API is usually by definition cross site and meant to be used in more than your web app, which means that the whole concept of CSRF does not quite apply.
Instead you should use a token based strategy of authenticating API requests with an API key and secret since you are verifying that the request comes from an approved API client - not from your own app.
You can deactivate CSRF as pointed out by @dcestari:
class ApiController < ActionController::Base
protect_from_forgery with: :null_session
end
Updated. In Rails 5 you can generate API only applications by using the --api
option:
rails new appname --api
They do not include the CSRF middleware and many other components that are superflouus.
Found one from Flickr that doesn't need registration / api.
Basic sample, Fiddle: http://jsfiddle.net/Braulio/vDr36/
More info: post
Pasted sample
HTML
<div id="images">
</div>
Javascript
// Querystring, "tags" search term, comma delimited
var query = "http://www.flickr.com/services/feeds/photos_public.gne?tags=soccer&format=json&jsoncallback=?";
// This function is called once the call is satisfied
// http://stackoverflow.com/questions/13854250/understanding-cross-domain-xhr-and-xml-data
var mycallback = function (data) {
// Start putting together the HTML string
var htmlString = "";
// Now start cycling through our array of Flickr photo details
$.each(data.items, function(i,item){
// I only want the ickle square thumbnails
var sourceSquare = (item.media.m).replace("_m.jpg", "_s.jpg");
// Here's where we piece together the HTML
htmlString += '<li><a href="' + item.link + '" target="_blank">';
htmlString += '<img title="' + item.title + '" src="' + sourceSquare;
htmlString += '" alt="'; htmlString += item.title + '" />';
htmlString += '</a></li>';
});
// Pop our HTML in the #images DIV
$('#images').html(htmlString);
};
// Ajax call to retrieve data
$.getJSON(query, mycallback);
Another very interesting is Star Wars Rest API:
I think that using colnames
and rownames
makes the most sense; here's why.
Using names
has several disadvantages. You have to remember that it means "column names", and it only works with data frame, so you'll need to call colnames
whenever you use matrices. By calling colnames
, you only have to remember one function. Finally, if you look at the code for colnames
, you will see that it calls names
in the case of a data frame anyway, so the output is identical.
rownames
and row.names
return the same values for data frame and matrices; the only difference that I have spotted is that where there aren't any names, rownames
will print "NULL" (as does colnames
), but row.names
returns it invisibly. Since there isn't much to choose between the two functions, rownames
wins on the grounds of aesthetics, since it pairs more prettily withcolnames
. (Also, for the lazy programmer, you save a character of typing.)
Comparison between DATETIME, TIMESTAMP and DATE
What is that [.fraction]?
Sources:
Maybe combining some javascript and PHP could achieve the trick
<?php
$string = '<script>';
$string .= 'if ( /Opera|OPR\/|Puffin|Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)) { ';
$string .= ' alert("CELL")';
$string .= ' } else {';
$string .= ' alert("NON CELL")';
$string .= ' } ';
$string .= '</script>';
echo $string;
?>
I used that with plain javascript also instead
Add line break to ::after
or ::before
pseudo-element content
.yourclass:before {
content: 'text here first \A text here second';
white-space: pre;
}
probably most will be able to find a solution from the above answers but seeing as how none worked for me (vscode v1.34
) i thought i'd share my experience. if at least one person finds it helpful then, cool not a wasted post, amiirte?
anyway, my solution (windows
) is built a-top of @noontz's. his configuration may have been sufficient for older versions of vscode
but not with 1.34
(at least, i couldn't get it working ..).
our configs are nearly identical save a single property -- that property being, the group
property. i'm not sure why but without this, my task would not even appear in the command palette.
so. a working tasks.json
for windows
users running vscode 1.34
:
{
"version": "2.0.0",
"tasks": [
{
"label": "Chrome",
"type": "process",
"command": "chrome.exe",
"windows": {
"command": "C:\\Program Files (x86)\\Google\\Chrome\\Application\\chrome.exe"
},
"args": [
"${file}"
],
"group": "build",
"problemMatcher": []
}
]
}
note that the problemMatcher
property is not required for this to work but without it an extra manual step is imposed on you. tried to read the docs on this property but i'm too thick to understand. hopefully someone will come about and school me but yeah, thanks in advance for that. all i know is -- include this property and ctrl+shift+b
opens the current html
file in a new chrome
tab, hassle free.
easy.
What you're looking for is componentWillMount
.
From the documentation:
Invoked once, both on the client and server, immediately before the initial rendering occurs. If you call
setState
within this method,render()
will see the updated state and will be executed only once despite the state change.
So you would do something like this:
componentWillMount : function () {
var data = this.getData();
this.setState({data : data});
},
This way, render()
will only be called once, and you'll have the data you're looking for in the initial render.
If its a Java
version problem, you can edit the eclipse.ini
file and assign the compatible version to the application through adding these lines:
windows example:
-vm
C:\jdk1.7.0_21\bin\javaw.exe
for more information: https://wiki.eclipse.org/Eclipse.ini
You can try this also.
simply hide it from CSS by using,
.dataTables_length {
display: none;
}
Both will work.
it would be simple to get the length as
`${NUM}`.length
where NUM is the number to get the length for
As the "GNU C Library Reference Manual" says
off_t
This is a signed integer type used to represent file sizes.
In the GNU C Library, this type is no narrower than int.
If the source is compiled with _FILE_OFFSET_BITS == 64 this
type is transparently replaced by off64_t.
and
off64_t
This type is used similar to off_t. The difference is that
even on 32 bit machines, where the off_t type would have 32 bits,
off64_t has 64 bits and so is able to address files up to 2^63 bytes
in length. When compiling with _FILE_OFFSET_BITS == 64 this type
is available under the name off_t.
Thus if you want reliable way of representing file size between client and server, you can:
off64_t
type and stat64()
function accordingly (as it fills structure stat64
, which contains off64_t
type itself). Type off64_t
guaranties the same size on 32 and 64 bit machines.-D_FILE_OFFSET_BITS == 64
and use usual off_t
and stat()
.off_t
to type int64_t
with fixed size (C99 standard).
Note: (my book 'C in a Nutshell' says that it is C99 standard, but optional in implementation). The newest C11 standard says:7.20.1.1 Exact-width integer types
1 The typedef name intN_t designates a signed integer type with width N ,
no padding bits, and a two’s complement representation. Thus, int8_t
denotes such a signed integer type with a width of exactly 8 bits.
without mentioning.
And about implementation:
7.20 Integer types <stdint.h>
... An implementation shall provide those types described as ‘‘required’’,
but need not provide any of the others (described as ‘‘optional’’).
...
The following types are required:
int_least8_t uint_least8_t
int_least16_t uint_least16_t
int_least32_t uint_least32_t
int_least64_t uint_least64_t
All other types of this form are optional.
Thus, in general, C standard can't guarantee types with fixed sizes. But most compilers (including gcc) support this feature.
This one is in my opinion the best one for online (offline however dreamweaver is best): http://www.maschek.hu/imagemap/imgmap
You can show whatever you want in list display by using a callable. It would look like this:
def book_author(object): return object.book.author class PersonAdmin(admin.ModelAdmin): list_display = [book_author,]
To run command as a system service on debian with sysv init:
Copy skeleton script and adapt it for your needs, probably all you have to do is to set some variables. Your script will inherit fine defaults from /lib/init/init-d-script
, if something does not fits your needs - override it in your script. If something goes wrong you can see details in source /lib/init/init-d-script
. Mandatory vars are DAEMON
and NAME
. Script will use start-stop-daemon
to run your command, in START_ARGS
you can define additional parameters of start-stop-daemon
to use.
cp /etc/init.d/skeleton /etc/init.d/myservice
chmod +x /etc/init.d/myservice
nano /etc/init.d/myservice
/etc/init.d/myservice start
/etc/init.d/myservice stop
That is how I run some python stuff for my wikimedia wiki:
...
DESC="mediawiki articles converter"
DAEMON='/home/mss/pp/bin/nslave'
DAEMON_ARGS='--cachedir /home/mss/cache/'
NAME='nslave'
PIDFILE='/var/run/nslave.pid'
START_ARGS='--background --make-pidfile --remove-pidfile --chuid mss --chdir /home/mss/pp/bin'
export PATH="/home/mss/pp/bin:$PATH"
do_stop_cmd() {
start-stop-daemon --stop --quiet --retry=TERM/30/KILL/5 \
$STOP_ARGS \
${PIDFILE:+--pidfile ${PIDFILE}} --name $NAME
RETVAL="$?"
[ "$RETVAL" = 2 ] && return 2
rm -f $PIDFILE
return $RETVAL
}
Besides setting vars I had to override do_stop_cmd
because of python substitutes the executable, so service did not stop properly.
Inside the function parameter list, char arr[]
is absolutely equivalent to char *arr
, so the pair of definitions and the pair of declarations are equivalent.
void function(char arr[]) { ... }
void function(char *arr) { ... }
void function(char arr[]);
void function(char *arr);
The issue is the calling context. You provided a string literal to the function; string literals may not be modified; your function attempted to modify the string literal it was given; your program invoked undefined behaviour and crashed. All completely kosher.
Treat string literals as if they were static const char literal[] = "string literal";
and do not attempt to modify them.
This was bothering me for a while with GMaps v3.
I found a way to do it like this:
google.maps.event.addListenerOnce(map, 'idle', function(){
// do something only the first time the map is loaded
});
The "idle" event is triggered when the map goes to idle state - everything loaded (or failed to load). I found it to be more reliable then tilesloaded/bounds_changed and using addListenerOnce
method the code in the closure is executed the first time "idle" is fired and then the event is detached.
See also the events section in the Google Maps Reference.
The easiest way for me was to install Anaconda: https://docs.anaconda.com/anaconda/install/
There I can create as many environments with different Python versions as I want and switch between them with a mouse click. It could not be easier.
To install different Python versions just follow these instructions https://docs.conda.io/projects/conda/en/latest/user-guide/tasks/manage-python.html
A new development environment with a different Python version was done within 2 minutes. And in the future I can easily switch back and forth.
For those who still do not understand.
>>> a = iter(list(range(10)))
>>> for i in a:
... print(i)
... next(a)
...
0 # print(i) printed this
1 # next(a) printed this
2 # print(i) printed this
3 # next(a) printed this
4 # print(i) printed this
5 # next(a) printed this
6 # print(i) printed this
7 # next(a) printed this
8 # print(i) printed this
9 # next(a) printed this
As others have already said, next
increases the iterator by 1 as expected. Assigning its returned value to a variable doesn't magically changes its behaviour.
for more advanced python editing consider installing the simplefold vim plugin. it allows you do advanced code folding using regular expressions. i use it to fold my class and method definitions for faster editing.
The accepted answer looks way too complex to me so I am adding a Ruby and NodeJS versions of it
Suppose that flat nodes list have the following structure:
nodes = [
{ id: 7, parent_id: 1 },
...
] # ruby
nodes = [
{ id: 7, parentId: 1 },
...
] # nodeJS
The functions which will turn the flat list structure above into a tree look the following way
for Ruby:
def to_tree(nodes)
nodes.each do |node|
parent = nodes.find { |another| another[:id] == node[:parent_id] }
next unless parent
node[:parent] = parent
parent[:children] ||= []
parent[:children] << node
end
nodes.select { |node| node[:parent].nil? }
end
for NodeJS:
const toTree = (nodes) => {
nodes.forEach((node) => {
const parent = nodes.find((another) => another.id == node.parentId)
if(parent == null) return;
node.parent = parent;
parent.children = parent.children || [];
parent.children = parent.children.concat(node);
});
return nodes.filter((node) => node.parent == null)
};
From this question, I came up with an alternate way to access the currently selected input
when you're within a click
event for its respective label. The reason why is because the newly selected input
isn't updated until after its label
's click event.
TL;DR
$('label').click(function() {
var selected = $('#' + $(this).attr('for')).val();
...
});
$(function() {_x000D_
// this outright does not work properly as explained above_x000D_
$('#reported label').click(function() {_x000D_
var query = $('input[name="filter"]:checked').val();_x000D_
var time = (new Date()).toString();_x000D_
_x000D_
$('.query[data-method="click event"]').html(query + ' at ' + time);_x000D_
});_x000D_
_x000D_
// this works, but fails to update when same label is clicked consecutively_x000D_
$('#reported input[name="filter"]').on('change', function() {_x000D_
var query = $('input[name="filter"]:checked').val();_x000D_
var time = (new Date()).toString();_x000D_
_x000D_
$('.query[data-method="change event"]').html(query + ' at ' + time);_x000D_
});_x000D_
_x000D_
// here is the solution I came up with_x000D_
$('#reported label').click(function() {_x000D_
var query = $('#' + $(this).attr('for')).val();_x000D_
var time = (new Date()).toString();_x000D_
_x000D_
$('.query[data-method="click event with this"]').html(query + ' at ' + time);_x000D_
});_x000D_
});
_x000D_
input[name="filter"] {_x000D_
display: none;_x000D_
}_x000D_
#reported label {_x000D_
background-color: #ccc;_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
border-radius: 5px;_x000D_
cursor: pointer;_x000D_
}_x000D_
.query {_x000D_
padding: 5px;_x000D_
margin: 5px;_x000D_
}_x000D_
.query:before {_x000D_
content: "on " attr(data-method)": ";_x000D_
}_x000D_
[data-method="click event"] {_x000D_
color: red;_x000D_
}_x000D_
[data-method="change event"] {_x000D_
color: #cc0;_x000D_
}_x000D_
[data-method="click event with this"] {_x000D_
color: green;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<form id="reported">_x000D_
<input type="radio" name="filter" id="question" value="questions" checked="checked">_x000D_
<label for="question">Questions</label>_x000D_
_x000D_
<input type="radio" name="filter" id="answer" value="answers">_x000D_
<label for="answer">Answers</label>_x000D_
_x000D_
<input type="radio" name="filter" id="comment" value="comments">_x000D_
<label for="comment">Comments</label>_x000D_
_x000D_
<input type="radio" name="filter" id="user" value="users">_x000D_
<label for="user">Users</label>_x000D_
_x000D_
<input type="radio" name="filter" id="company" value="companies">_x000D_
<label for="company">Companies</label>_x000D_
_x000D_
<div class="query" data-method="click event"></div>_x000D_
<div class="query" data-method="change event"></div>_x000D_
<div class="query" data-method="click event with this"></div>_x000D_
</form>
_x000D_
Using React on my IPad, type="number"
does not work perfectly for me.
For my floating point numbers in the range between 99.99999 - .00000 I use the regular expression (^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)
. The first group (...)
is true for all positive two digit numbers without the floating point (e.g. 23), |
or e.g. .12345 for the second group (...)
. You can adopt it for any positive floating point number by simply changing the range {0,2}
or {0,5}
respectively.
<input
className="center-align"
type="text"
pattern="(^[0-9]{0,2}$)|(^[0-9]{0,2}\.[0-9]{0,5}$)"
step="any"
maxlength="7"
validate="true"
/>
There are two possibilities to use if condition on HTML tag or templates:
If the effect you want is to center in the center of the screen no matter where you've scrolled to, it's even simpler than that:
In your CSS use (for example)
div.centered{
width: 100px;
height: 50px;
position:fixed;
top: calc(50% - 25px); // half of width
left: calc(50% - 50px); // half of height
}
No JS required.
If you want to get the visible tbody
elements, you could do this:
$('tbody:visible').highlight(myArray[i]);
It looks similar to the answer that Agent_9191 gave, but this one removes the space from the selector, which makes it selects the visible tbody
elements instead of the visible descendants.
EDIT:
If you specifically wanted to use a test on the display
CSS property of the tbody
elements, you could do this:
$('tbody').filter(function() {
return $(this).css('display') != 'none';
}).highlight(myArray[i]);
The short answer:
Use the click
event, which won't fire until after the value has been updated, and fires when you want it to:
<label><input type='checkbox' onclick='handleClick(this);'>Checkbox</label>
function handleClick(cb) {
display("Clicked, new value = " + cb.checked);
}
The longer answer:
The change
event handler isn't called until the checked
state has been updated (live example | source), but because (as Tim Büthe points out in the comments) IE doesn't fire the change
event until the checkbox loses focus, you don't get the notification proactively. Worse, with IE if you click a label for the checkbox (rather than the checkbox itself) to update it, you can get the impression that you're getting the old value (try it with IE here by clicking the label: live example | source). This is because if the checkbox has focus, clicking the label takes the focus away from it, firing the change
event with the old value, and then the click
happens setting the new value and setting focus back on the checkbox. Very confusing.
But you can avoid all of that unpleasantness if you use click
instead.
I've used DOM0 handlers (onxyz
attributes) because that's what you asked about, but for the record, I would generally recommend hooking up handlers in code (DOM2's addEventListener
, or attachEvent
in older versions of IE) rather than using onxyz
attributes. That lets you attach multiple handlers to the same element and lets you avoid making all of your handlers global functions.
An earlier version of this answer used this code for handleClick
:
function handleClick(cb) {
setTimeout(function() {
display("Clicked, new value = " + cb.checked);
}, 0);
}
The goal seemed to be to allow the click to complete before looking at the value. As far as I'm aware, there's no reason to do that, and I have no idea why I did. The value is changed before the click
handler is called. In fact, the spec is quite clear about that. The version without setTimeout
works perfectly well in every browser I've tried (even IE6). I can only assume I was thinking about some other platform where the change isn't done until after the event. In any case, no reason to do that with HTML checkboxes.
In your template, you have access to all the variables that are members of the current $scope
. So, tobedone
should be $scope.tobedone
, and then you can display it with {{tobedone}}
, or [[tobedone]]
in your case.
If you consider using fastjson, you can solve your problem, note the version
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.56</version>
</dependency>
To select every nth element from any starting position in the vector
nth_element <- function(vector, starting_position, n) {
vector[seq(starting_position, length(vector), n)]
}
# E.g.
vec <- 1:12
nth_element(vec, 1, 3)
# [1] 1 4 7 10
nth_element(vec, 2, 3)
# [1] 2 5 8 11
You can also paste mayankcpdixit's code in onAnimationComplete
option :
// ...
var myDoughnutChart = new Chart(ctx).Doughnut(data, {
onAnimationComplete: function() {
ctx.fillText(data[0].value + "%", 100 - 20, 100, 200);
}
});
Text will be shown after animation
Duplicate rows can be removed for Complex Queries by,
First storing the result to a #TempTable or @TempTableVariable
Delete from #TempTable or @TempTableVariable where your condition
Then select the rest of the data.
If need to create a row number create an identity column.
I have two button for form submission, button named save and exit bypasses the validation :
$('.save_exist').on('click', function (event) {
$('#MyformID').removeData('validator');
$('.form-control').removeClass('error');
$('.form-control').removeClass('required');
$("#loanApplication").validate().cancelSubmit = true;
$('#loanApplication').submit();
event.preventDefault();
});
The characters '<', and '>', are to indicate a place-holder, you should remove them to read:
php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME
This look like a duplicate of JSTL conditional check.
The error is having the &&
outside the expression. Instead use
<c:if test="${ISAJAX == 0 && ISDATE == 0}">
To accept all certificates in HttpClient 4.4.x you can use the following one liner when creating the httpClient:
httpClient = HttpClients.custom().setSSLHostnameVerifier(new NoopHostnameVerifier()).setSslcontext(new SSLContextBuilder().loadTrustMaterial(null, (x509Certificates, s) -> true).build()).build();
The statement icr=y;
does not make the reference refer to y
; it assigns the value of y
to the variable that icr
refers to, i
.
References are inherently const
, that is you can't change what they refer to. There are 'const
references' which are really 'references to const
', that is you can't change the value of the object they refer to. They are declared const int&
or int const&
rather than int& const
though.
Don't put quotes around the name of the file that you are trying to open; start "myfile.txt"
opens a new command prompt with the title myfile.txt
, while start myfile.txt
opens myfile.txt
in Notepad. There's no easy solution in the case where you want to start a console application with a space in its file name, but for other applications, start "" "my file.txt"
works.
setting toast at topin screen
toast.setView(view);
toast.setGravity(Gravity.BOTTOM , 0, 0); // here i am setting toast at bottom
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
now at bottom
toast.setView(view);
toast.setGravity(Gravity.BOTTOM , 0, 0); // here i am setting toast at bottom
toast.setDuration(Toast.LENGTH_LONG);
toast.show();
the same way we can set toast in left, right and also center
Click here
SELECT *
FROM logs
WHERE pw='correct'
AND CASE
WHEN id<800 THEN success=1
ELSE 1=1
END
AND YEAR(TIMESTAMP)=2011
I see there is a VBA solution and a non-VBA solution, which both are really good. I wanted to propose my Javascript solution.
There is an Excel add-in called Funfun that allows you to use javascript, HTML and css in Excel. It has an online editor with an embedded spreadsheet where you can build your chart.
I have written this code for you with Chart.js:
https://www.funfun.io/1/#/edit/5a61ed15404f66229bda3f44
To create this chart, I entered my data on the spreadsheet and read it with a json file, it is the short
file.
I make sure to put it in the right format, in script.js
, so I can add it to my chart:
var data = [];
var color = [];
var label = [];
for (var i = 1; i < $internal.data.length; i++)
{
label.push($internal.data[i][0]);
data.push([$internal.data[i][1], $internal.data[i][2]]);
color.push($internal.data[i][3]);
}
I then create the scatter chart with each dot having his designated color and position:
var dataset = [];
for (var i = 0; i < data.length; i++) {
dataset.push({
data: [{
x: data[i][0],
y: data[i][1]
}],
pointBackgroundColor: color[i],
pointStyle: "cercle",
radius: 6
});
}
After I've created my scatter chart I can upload it in Excel by pasting the URL in the funfun Excel add-in. Here is how it looks like with my example:
Once this is done You can change the color or the position of a dot instantly, in Excel, by changing the values in the spreadsheet.
If you want to add extra dots in the charts you just need to modify the radius of data
in the short
json file.
Hope this Javascript solution helps !
Disclosure : I’m a developer of funfun
While @Eli is quite correct that there usually isn't much of a need to do it, it is possible. savefig
takes a bbox_inches
argument that can be used to selectively save only a portion of a figure to an image.
Here's a quick example:
import matplotlib.pyplot as plt
import matplotlib as mpl
import numpy as np
# Make an example plot with two subplots...
fig = plt.figure()
ax1 = fig.add_subplot(2,1,1)
ax1.plot(range(10), 'b-')
ax2 = fig.add_subplot(2,1,2)
ax2.plot(range(20), 'r^')
# Save the full figure...
fig.savefig('full_figure.png')
# Save just the portion _inside_ the second axis's boundaries
extent = ax2.get_window_extent().transformed(fig.dpi_scale_trans.inverted())
fig.savefig('ax2_figure.png', bbox_inches=extent)
# Pad the saved area by 10% in the x-direction and 20% in the y-direction
fig.savefig('ax2_figure_expanded.png', bbox_inches=extent.expanded(1.1, 1.2))
The full figure:
Area inside the second subplot:
Area around the second subplot padded by 10% in the x-direction and 20% in the y-direction:
Another cause is accidentally putting the data=...
inside the aes(...)
instead of outside:
RIGHT:
ggplot(data=df[df$var7=='9-06',], aes(x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
WRONG:
ggplot(aes(data=df[df$var7=='9-06',],x=lifetime,y=rep_rate,group=mdcp,color=mdcp) ...)
In particular this can happen when you prototype your plot command with qplot()
, which doesn't use an explicit aes()
, then edit/copy-and-paste it into a ggplot()
qplot(data=..., x=...,y=..., ...)
ggplot(data=..., aes(x=...,y=...,...))
It's a pity ggplot's error message isn't Missing 'data' argument! instead of this cryptic nonsense, because that's what this message often means.
The reason your code fails is because post()
will start an asynchronous request to the server. What that means for you is that post()
returns immediately, not after the request completes, like you are expecting.
What you need, then, is for the request to be synchronous and block the current thread until the request completes. Thus,
var it_works = false;
$.ajax({
url: 'some_file.php',
async: false, # makes request synchronous
success: function() {
it_works = true;
}
});
alert(it_works);
That will work just fine. You can export an entire calendar with File
> Export…
, or individual events by dragging them to the Finder.
iCalendar (.ics
) files are human-readable, so you can always pop it open in a text editor to make sure no private events made it in there. They consist of nested sections with start with BEGIN:
and end with END:
. You'll mostly find VEVENT
sections (each of which represents an event) and VTIMEZONE
sections, each of which represents a time zone that's referenced from one or more events.
The answer to this question in 2020 is IT DOESN'T WORK AT ALL NOW.
You can attach a SLOT to the
void aboutToQuit();
signal of your QApplication. This signal should be raised just before app closes.
Note that the %
syntax for formatting strings is becoming outdated. If your version of Python supports it, you should write:
instr = "'{0}', '{1}', '{2}', '{3}', '{4}', '{5}', '{6}'".format(softname, procversion, int(percent), exe, description, company, procurl)
This also fixes the error that you happened to have.
Found this as I was searching for which way is fastest to pull the second element of a 2-tuple list. Not what I wanted but ran same test as shown with a 3rd method plus test the zip method
setup = 'elements = [(1,1) for _ in range(100000)];from operator import itemgetter'
method1 = '[x[1] for x in elements]'
method2 = 'map(itemgetter(1), elements)'
method3 = 'dict(elements).values()'
method4 = 'zip(*elements)[1]'
import timeit
t = timeit.Timer(method1, setup)
print('Method 1: ' + str(t.timeit(100)))
t = timeit.Timer(method2, setup)
print('Method 2: ' + str(t.timeit(100)))
t = timeit.Timer(method3, setup)
print('Method 3: ' + str(t.timeit(100)))
t = timeit.Timer(method4, setup)
print('Method 4: ' + str(t.timeit(100)))
Method 1: 0.618785858154
Method 2: 0.711684942245
Method 3: 0.298138141632
Method 4: 1.32586884499
So over twice as fast if you have a 2 tuple pair to just convert to a dict and take the values.
awk '{t+=length($0)}END{print t}' file3
As the accepted answer suggests you can add "using" to all views by adding to section of config file.
But for a single view you could just use
@using SomeNamespace.Extensions
Find this useful solution
function get_duplicates( $array ) {
return array_unique( array_diff_assoc( $array, array_unique( $array ) ) );
}
After that count result if greater than 0 than duplicates else unique.
I had the same issue too. The problem with me was I was displaying the modal on pressing a link and prompting for confirmation with jquery.
The code below displayed the modal and which dissapeared immediately:
<a href="" onclick="do_some_stuff()">Hey</a>
I ended up adding '#' to href so the link won't go anywhere and it solved my problem.
<a href="#" onclick="do_some_stuff()">Hey</a>
I guess you want to convert the values contained in the Map
to a list
? Easiest is to call the values()
method of the Map
interface. This will return the Collection
of value objects contained in the Map
.
Note that this Collection
is backed by the Map
object and any changes to the Map
object will reflect here. So if you want a separate copy not bound to your Map
object, simply create a new List
object like an ArrayList
passing the value Collection
as below.
ArrayList<String> list = new ArrayList<String>(map.values());
If you are writing a function, which is always preferred, you should propagate the error like this:
function() {
if some_command; then
echo worked
else
return $?
fi
}
This will propagate the error to the caller, so that he can do things like function && next
as expected.
For Mac OS X Mojave and above
To Uninstall Homebrew, run following command:
sudo ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/uninstall)"
To Install Homebrew, run following command:
ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
And if you run into Permission denied issue, try running this command followed by install command again:
sudo chown -R $(whoami):admin /usr/local/* && sudo chmod -R g+rwx /usr/local/*
put this somewhere:
public static class DateTimeUtil //or whatever name
{
public static bool IsEmpty(this DateTime dateTime)
{
return dateTime == default(DateTime);
}
}
then:
DateTime datetime = ...;
if (datetime.IsEmpty())
{
//unassigned
}
$source = "number35"
$number=$null
$result = foreach ($_ in $source.ToCharArray()){$digit="0123456789".IndexOf($\_,0);if($digit -ne -1){$number +=$\_}}[int32]$number
Just feed it digits and it wil convert to an Int32
in IIS, highlight the machine, double-click "Request Filtering", open the "Hidden Segments" tab. "App_Data" is listed there as a restricted folder. Yes i know this thread is really old, but this is still applicable.
From the comments, the problem was caused by using dlls that were built with Visual Studio 2013 in a project compiled with Visual Studio 2012. The reason for this was a third party library named the folders containing the dlls vc11, vc12. One has to be careful with any system that uses the compiler version (less than 4 digits) since this does not match the version of Visual Studio (except for Visual Studio 2010).
The Microsoft C++ runtime dlls use a 2 or 3 digit code also based on the compiler version not the version of Visual Studio.
There is binary compatibility between Visual Studio 2015, 2017 and 2019.
you gave the following example in your question:
colnames(merger)[,1]<-"Date"
the problem is the comma: colnames() returns a vector, not a matrix, so the solution is:
colnames(merger)[1]<-"Date"
I made a node module to automate this task: mddir
node mddir "../relative/path/"
To install: npm install mddir -g
To generate markdown for current directory: mddir
To generate for any absolute path: mddir /absolute/path
To generate for a relative path: mddir ~/Documents/whatever.
The md file gets generated in your working directory.
Currently ignores node_modules, and .git folders.
If you receive the error 'node\r: No such file or directory', the issue is that your operating system uses different line endings and mddir can't parse them without you explicitly setting the line ending style to Unix. This usually affects Windows, but also some versions of Linux. Setting line endings to Unix style has to be performed within the mddir npm global bin folder.
Get npm bin folder path with:
npm config get prefix
Cd into that folder
brew install dos2unix
dos2unix lib/node_modules/mddir/src/mddir.js
This converts line endings to Unix instead of Dos
Then run as normal with: node mddir "../relative/path/".
|-- .bowerrc
|-- .jshintrc
|-- .jshintrc2
|-- Gruntfile.js
|-- README.md
|-- bower.json
|-- karma.conf.js
|-- package.json
|-- app
|-- app.js
|-- db.js
|-- directoryList.md
|-- index.html
|-- mddir.js
|-- routing.js
|-- server.js
|-- _api
|-- api.groups.js
|-- api.posts.js
|-- api.users.js
|-- api.widgets.js
|-- _components
|-- directives
|-- directives.module.js
|-- vendor
|-- directive.draganddrop.js
|-- helpers
|-- helpers.module.js
|-- proprietary
|-- factory.actionDispatcher.js
|-- services
|-- services.cardTemplates.js
|-- services.cards.js
|-- services.groups.js
|-- services.posts.js
|-- services.users.js
|-- services.widgets.js
|-- _mocks
|-- mocks.groups.js
|-- mocks.posts.js
|-- mocks.users.js
|-- mocks.widgets.js
I just found the way. Right click on the desired package then Source
-> Organize Imports
.
Shortcut keys:
You can use AngularJS build-in service $rootScope
and inject this service in both of your controllers.
You can then listen for events that are fired on $rootScope object.
$rootScope provides two event dispatcher called $emit and $broadcast
which are responsible for dispatching events(may be custom events) and use $rootScope.$on
function to add event listener.
From MSDN:
To change security authentication mode:
In SQL Server Management Studio Object Explorer, right-click the server, and then click Properties.
On the Security page, under Server authentication, select the new server authentication mode, and then click OK.
In the SQL Server Management Studio dialog box, click OK to acknowledge the requirement to restart SQL Server.
In Object Explorer, right-click your server, and then click Restart. If SQL Server Agent is running, it must also be restarted.
To enable the SA login:
In Object Explorer, expand Security, expand Logins, right-click SA, and then click Properties.
On the General page, you might have to create and confirm a password for the login.
On the Status page, in the Login section, click Enabled, and then click OK.
HTML doesn't have escape characters (as it doesn't use escape-semantics for reserved characters, instead you use SGML entities: &
, <
, >
and "
).
SGML does not have a named-entity for the tab character as it exists in most character sets (i.e. 0x09
in ASCII and UTF-8), rendering it completely unnecessary (i.e. simply press the Tab key on your keyboard). If you're working with code that generates HTML (e.g. a server-side application, e.g. ASP.NET, PHP or Perl, then you might need to escape it then, but only because the server-side language demands it - it has nothing to do with HTML, like so:
echo "<pre>\t\tTABS!\t\t</pre>";
But, you can use SGML entities to represent any ISO-8859-1 character by hexadecimal value, e.g. 	
for a tab character.
You will need to draw the item yourself. Change the DrawMode to OwnerDrawFixed and handle the DrawItem event.
/// <summary>
/// Handles the DrawItem event of the listBox1 control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="System.Windows.Forms.DrawItemEventArgs"/> instance containing the event data.</param>
private void listBox1_DrawItem( object sender, DrawItemEventArgs e )
{
e.DrawBackground();
Graphics g = e.Graphics;
// draw the background color you want
// mine is set to olive, change it to whatever you want
g.FillRectangle( new SolidBrush( Color.Olive), e.Bounds );
// draw the text of the list item, not doing this will only show
// the background color
// you will need to get the text of item to display
g.DrawString( THE_LIST_ITEM_TEXT , e.Font, new SolidBrush( e.ForeColor ), new PointF( e.Bounds.X, e.Bounds.Y) );
e.DrawFocusRectangle();
}
I guess something like this would work:
Add System.ServiceProcess
to your project references (It's on the .NET tab).
using System.ServiceProcess;
ServiceController sc = new ServiceController(SERVICENAME);
switch (sc.Status)
{
case ServiceControllerStatus.Running:
return "Running";
case ServiceControllerStatus.Stopped:
return "Stopped";
case ServiceControllerStatus.Paused:
return "Paused";
case ServiceControllerStatus.StopPending:
return "Stopping";
case ServiceControllerStatus.StartPending:
return "Starting";
default:
return "Status Changing";
}
Edit: There is also a method sc.WaitforStatus()
that takes a desired status and a timeout, never used it but it may suit your needs.
Edit: Once you get the status, to get the status again you will need to call sc.Refresh()
first.
Reference: ServiceController object in .NET.
MSYS has not been updated a long time, MSYS2 is more active, you can download from MSYS2, it has both mingw
and cygwin fork
package.
To install the MinGW-w64 toolchain (Reference):
pacman -Sy pacman
to update the package databasepacman -Syu
to update the package database and core system packagespacman -Su
to update the restpacman -S mingw-w64-i686-toolchain
pacman -S mingw-w64-x86_64-toolchain
make
, run pacman -S make
bash
has a "built-in" command called "echo":
$ type echo
echo is a shell builtin
Additionally, there is an "echo" command that is a proper executable (that is, the shell forks and execs /bin/echo
, as opposed to interpreting echo
and executing it):
$ ls -l /bin/echo
-rwxr-xr-x 1 root root 22856 Jul 21 2011 /bin/echo
The behavior of either echo
's WRT to \c
and -n
varies. Your best bet is to use printf
, which is available on four different *NIX flavors that I looked at:
$ printf "a line without trailing linefeed"
$ printf "a line with trailing linefeed\n"
It appears the default setting for Adobe Reader X is for the toolbars not to be shown by default unless they are explicitly turned on by the user. And even when I turn them back on during a session, they don't show up automatically next time. As such, I suspect you have a preference set contrary to the default.
The state you desire, with the top and left toolbars not shown, is called "Read Mode". If you right-click on the document itself, and then click "Page Display Preferences" in the context menu that is shown, you'll be presented with the Adobe Reader Preferences dialog. (This is the same dialog you can access by opening the Adobe Reader application, and selecting "Preferences" from the "Edit" menu.) In the list shown in the left-hand column of the Preferences dialog, select "Internet". Finally, on the right, ensure that you have the "Display in Read Mode by default" box checked:
You can also turn off the toolbars temporarily by clicking the button at the right of the top toolbar that depicts arrows pointing to opposing corners:
Finally, if you have "Display in Read Mode by default" turned off, but want to instruct the page you're loading not to display the toolbars (i.e., override the user's current preferences), you can append the following to the URL:
#toolbar=0&navpanes=0
So, for example, the following code will disable both the top toolbar (called "toolbar") and the left-hand toolbar (called "navpane"). However, if the user knows the keyboard combination (F8, and perhaps other methods as well), they will still be able to turn them back on.
string url = @"http://www.domain.com/file.pdf#toolbar=0&navpanes=0";
this._WebBrowser.Navigate(url);
You can read more about the parameters that are available for customizing the way PDF files open here on Adobe's developer website.
1) To redirect to the login page / from the login page, don't use the Redirect() methods. Use FormsAuthentication.RedirectToLoginPage()
and FormsAuthentication.RedirectFromLoginPage()
!
2) You should just use RedirectToAction("action", "controller") in regular scenarios..
You want to redirect in side the Initialize method? Why? I don't see why would you ever want to do this, and in most cases you should review your approach imo.. If you want to do this for authentication this is DEFINITELY the wrong way (with very little chances foe an exception)
Use the [Authorize]
attribute on your controller or method instead :)
UPD: if you have some security checks in the Initialise method, and the user doesn't have access to this method, you can do a couple of things: a)
Response.StatusCode = 403;
Response.End();
This will send the user back to the login page. If you want to send him to a custom location, you can do something like this (cautios: pseudocode)
Response.Redirect(Url.Action("action", "controller"));
No need to specify the full url. This should be enough. If you completely insist on the full url:
Response.Redirect(new Uri(Request.Url, Url.Action("action", "controller")).ToString());
ObjectId is composed of following things.
Correct way to validate if the objectId is valid is by using static method from ObjectId class itself.
mongoose.Types.ObjectId.isValid(sample_object_id)
To see a list of current buffers, I use:
:ls
To open a new file, I use
:e ../myFile.pl
with enhanced tab completion (put set wildmenu
in your .vimrc
).
Note: you can also use :find
which will search a set of paths for you, but you need to customize those paths first.
To switch between all open files, I use
:b myfile
with enhanced tab completion (still set wildmenu
).
Note: :b#
chooses the last visited file, so you can use it to switch quickly between two files.
Ctrl-W s
and Ctrl-W v
to split the current window horizontally and vertically. You can also use :split
and :vertical split
(:sp
and :vs
)
Ctrl-W w
to switch between open windows, and Ctrl-W h
(or j
or k
or l
) to navigate through open windows.
Ctrl-W c
to close the current window, and Ctrl-W o
to close all windows except the current one.
Starting vim with a -o
or -O
flag opens each file in its own split.
With all these I don't need tabs in Vim, and my fingers find my buffers, not my eyes.
Note: if you want all files to go to the same instance of Vim, start Vim with the --remote-silent
option.
the file is a native DLL which means you can't add it to a .NET project via Add Reference... you can use it via DllImport (see http://msdn.microsoft.com/en-us/library/system.runtime.interopservices.dllimportattribute.aspx)
I'm using the following, though it's hardcoded for gnome-terminal
. It also changes the CWD and buffer for vim to be the same as your current buffer and it's directory.
:silent execute '!gnome-terminal -- zsh -i -c "cd ' shellescape(expand("%:h")) '; vim' shellescape(expand("%:p")) '; zsh -i"' <cr>
Python equivalent code for a QMessageBox which consist of a question in it and Yes and No button. When Yes Button is clicked it will pop up another message box saying yes is clicked and same for No button also. You can push your own code after if block.
button_reply = QMessageBox.question(self,"Test", "Are you sure want to quit??", QMessageBox.Yes,QMessageBox.No,)
if button_reply == QMessageBox.Yes:
QMessageBox.information(self, "Test", "Yes Button Was Clicked")
else :
QMessageBox.information(self, "Test", "No Button Was Clicked")
As I used ul:not(:first-child)
is a perfect solution.
div ul:not(:first-child) {
background-color: #900;
}
Why is this a perfect because by using ul:not(:first-child)
, we can apply CSS on inner elements. Like li, img, span, a
tags etc.
But when used others solutions:
div ul + ul {
background-color: #900;
}
and
div li~li {
color: red;
}
and
ul:not(:first-of-type) {}
and
div ul:nth-child(n+2) {
background-color: #900;
}
These restrict only ul level CSS. Suppose we cannot apply CSS on li
as `div ul + ul li'.
For inner level elements the first Solution works perfectly.
div ul:not(:first-child) li{
background-color: #900;
}
and so on ...
Last one is not working now, take this one, it worked for me.
in WebApiConfig.cs at App_Start
public static string _WebApiExecutionPath = "api";
public static void Register(HttpConfiguration config)
{
var basicRouteTemplate = string.Format("{0}/{1}", _WebApiExecutionPath, "{controller}");
// Controller Only
// To handle routes like `/api/VTRouting`
config.Routes.MapHttpRoute(
name: "ControllerOnly",
routeTemplate: basicRouteTemplate//"{0}/{controller}"
);
// Controller with ID
// To handle routes like `/api/VTRouting/1`
config.Routes.MapHttpRoute(
name: "ControllerAndId",
routeTemplate: string.Format ("{0}/{1}", basicRouteTemplate, "{id}"),
defaults: null,
constraints: new { id = @"^\d+$" } // Only integers
);
Global.asax
protected void Application_PostAuthorizeRequest()
{
if (IsWebApiRequest())
{
HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
}
}
private static bool IsWebApiRequest()
{
return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}
fournd here: http://forums.asp.net/t/1773026.aspx/1
Hashing is a one-way function, meaning that once you hash a password it is very difficult to get the original password back from the hash. Encryption is a two-way function, where it's much easier to get the original text back from the encrypted text.
Plain hashing is easily defeated using a dictionary attack, where an attacker just pre-hashes every word in a dictionary (or every combination of characters up to a certain length), then uses this new dictionary to look up hashed passwords. Using a unique random salt for each hashed password stored makes it much more difficult for an attacker to use this method. They would basically need to create a new unique dictionary for every salt value that you use, slowing down their attack terribly.
It's unsafe to store passwords using an encryption algorithm because if it's easier for the user or the administrator to get the original password back from the encrypted text, it's also easier for an attacker to do the same.
If you use $window.localStorage.setItem(key,value)
to store,$window.localStorage.getItem(key)
to retrieve and $window.localStorage.removeItem(key)
to remove, then you can access the values in any page.
You have to pass the $window
service to the controller. Though in JavaScript, window
object is available globally.
By using $window.localStorage.xxXX()
the user has control over the localStorage
value. The size of the data depends upon the browser. If you only use $localStorage
then value remains as long as you use window.location.href to navigate to other page and if you use <a href="location"></a>
to navigate to other page then your $localStorage
value is lost in the next page.
if
statement is not vectorized. For vectorized if statements you should use ifelse
. In your case it is sufficient to write
w <- function(a){
if (any(a>0)){
a/sum(a)
}
else 1
}
or a short vectorised version
ifelse(a > 0, a/sum(a), 1)
It depends on which do you want to use, because first function gives output vector of length 1 (in else part) and ifelse
gives output vector of length equal to length of a
.
DECIMAL
directive('decimal', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var digits = val.replace(/[^0-9.]/g, '');
if (digits.split('.').length > 2) {
digits = digits.substring(0, digits.length - 1);
}
if (digits !== val) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseFloat(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
DIGITS
directive('entero', function() {
return {
require: 'ngModel',
restrict: 'A',
link: function(scope, element, attr, ctrl) {
function inputValue(val) {
if (val) {
var value = val + ''; //convert to string
var digits = value.replace(/[^0-9]/g, '');
if (digits !== value) {
ctrl.$setViewValue(digits);
ctrl.$render();
}
return parseInt(digits);
}
return "";
}
ctrl.$parsers.push(inputValue);
}
};
});
Sure Google has a limit of downloads so that you don't abuse the system. These are the limits if you are using Gmail:
The following limits apply for Google Apps for Business or Education editions. Limits for domains during trial are lower. These limits may change without notice in order to protect Google’s infrastructure.
Bandwidth limits
Limit Per hour Per day
Download via web client 750 MB 1250 MB
Upload via web client 300 MB 500 MB
POP and IMAP bandwidth limits
Limit Per day
Download via IMAP 2500 MB
Download via POP 1250 MB
Upload via IMAP 500 MB
This is a fundamental understanding in Java, but can be a little tricky to new programmers. Do a little research on the difference between a static and instance method. The basic difference is the instance method do() is only accessible to a instance of the class foo.
You must instantiate (create an instance of) the class, creating an object, that you use to call the instance method.
I have included your example with a couple comments and example.
public class SomeName {
//this is a static method and cannot call an instance method without a object
public static void main(String[] args){
// can't do this from this static method, no object reference
// someMethod();
//create instance of object
SomeName thisObj = new SomeName();
//call instance method using object
thisObj.someMethod();
}
//instance method
public void someMethod(){
System.out.print("some message...");
}
}// end class SomeName
If you don't care about legacy browsers:
if ( bank_holidays.indexOf( '06/04/2012' ) > -1 )
if you do care about legacy browsers, there is a shim available on MDN. Otherwise, jQuery provides an equivalent function:
if ( $.inArray( '06/04/2012', bank_holidays ) > -1 )
<Grid >
<Grid.ColumnDefinitions>
<ColumnDefinition Width="*"/>
</Grid.ColumnDefinitions>
<Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>
</Grid>
the code behind for the window:
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
DataContext = new ViewModelBase();
}
}
The ViewModel:
public class ViewModelBase
{
private ICommand _clickCommand;
public ICommand ClickCommand
{
get
{
return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
}
}
public bool CanExecute
{
get
{
// check if executing is allowed, i.e., validate, check if a process is running, etc.
return true/false;
}
}
public void MyAction()
{
}
}
Command Handler:
public class CommandHandler : ICommand
{
private Action _action;
private Func<bool> _canExecute;
/// <summary>
/// Creates instance of the command handler
/// </summary>
/// <param name="action">Action to be executed by the command</param>
/// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
public CommandHandler(Action action, Func<bool> canExecute)
{
_action = action;
_canExecute = canExecute;
}
/// <summary>
/// Wires CanExecuteChanged event
/// </summary>
public event EventHandler CanExecuteChanged
{
add { CommandManager.RequerySuggested += value; }
remove { CommandManager.RequerySuggested -= value; }
}
/// <summary>
/// Forcess checking if execute is allowed
/// </summary>
/// <param name="parameter"></param>
/// <returns></returns>
public bool CanExecute(object parameter)
{
return _canExecute.Invoke();
}
public void Execute(object parameter)
{
_action();
}
}
I hope this will give you the idea.
use net stop mysql57 instead, it should be the version that is not specified
Finally, i solved the problem by using following way, in which the position of the spinner can be get by its string
private int getPostiton(String locationid,Cursor cursor)
{
int i;
cursor.moveToFirst();
for(i=0;i< cursor.getCount()-1;i++)
{
String locationVal = cursor.getString(cursor.getColumnIndex(RoadMoveDataBase.LT_LOCATION));
if(locationVal.equals(locationid))
{
position = i+1;
break;
}
else
{
position = 0;
}
cursor.moveToNext();
}
Calling the method
Spinner location2 = (Spinner)findViewById(R.id.spinner1);
int location2id = getPostiton(cursor.getString(3),cursor);
location2.setSelection(location2id);
I hope it will help for some one..
By Adding MONTH(date_column)
in GROUP BY
.
SELECT Closing_Date, Category, COUNT(Status)TotalCount
FROM MyTable
WHERE Closing_Date >= '2012-02-01' AND Closing_Date <= '2012-12-31'
AND Defect_Status1 IS NOT NULL
GROUP BY MONTH(Closing_Date), Category
<script language="javascript">_x000D_
_x000D_
// Set values to variable_x000D_
var sectionName = "TestSection";_x000D_
var fileMap = "fileMapData";_x000D_
var fileId = "foobar";_x000D_
var fileValue= "foobar.png";_x000D_
var fileId2 = "barfoo";_x000D_
var fileValue2= "barfoo.jpg";_x000D_
_x000D_
// Create top-level image object_x000D_
var images = {};_x000D_
_x000D_
// Create second-level object in images object with_x000D_
// the name of sectionName value_x000D_
images[sectionName] = {};_x000D_
_x000D_
// Create a third level object_x000D_
var fileMapObj = {};_x000D_
_x000D_
// Add the third level object to the second level object_x000D_
images[sectionName][fileMap] = fileMapObj;_x000D_
_x000D_
// Add forth level associate array key and value data_x000D_
images[sectionName][fileMap][fileId] = fileValue;_x000D_
images[sectionName][fileMap][fileId2] = fileValue2;_x000D_
_x000D_
_x000D_
// All variables_x000D_
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);_x000D_
_x000D_
// All keys with dots_x000D_
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);_x000D_
_x000D_
// Mixed with a different final key_x000D_
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);_x000D_
_x000D_
// Mixed brackets and dots..._x000D_
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);_x000D_
_x000D_
// This will FAIL! variable names must be in brackets!_x000D_
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);_x000D_
// Produces: "Example 5 Value: undefined"._x000D_
_x000D_
// This will NOT work either. Values must be quoted in brackets._x000D_
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);_x000D_
// Throws and exception and stops execution with error: fileMapData is not defined_x000D_
_x000D_
// We never get here because of the uncaught exception above..._x000D_
alert ("The End!");_x000D_
</script>
_x000D_
Your file seems quite small (297 lines) so you can read and write them quite quickly. You refer to Excel CSV, which does not exists, and you show space delimited data in your example. Furthermore, Access is limited to 255 columns, and a CSV is not, so there is no guarantee this will work
Sub StripHeaderAndFooter()
Dim fs As Object ''FileSystemObject
Dim tsIn As Object, tsOut As Object ''TextStream
Dim sFileIn As String, sFileOut As String
Dim aryFile As Variant
sFileIn = "z:\docs\FileName.csv"
sFileOut = "z:\docs\FileOut.csv"
Set fs = CreateObject("Scripting.FileSystemObject")
Set tsIn = fs.OpenTextFile(sFileIn, 1) ''ForReading
sTmp = tsIn.ReadAll
Set tsOut = fs.CreateTextFile(sFileOut, True) ''Overwrite
aryFile = Split(sTmp, vbCrLf)
''Start at line 3 and end at last line -1
For i = 3 To UBound(aryFile) - 1
tsOut.WriteLine aryFile(i)
Next
tsOut.Close
DoCmd.TransferText acImportDelim, , "NewCSV", sFileOut, False
End Sub
Edit re various comments
It is possible to import a text file manually into MS Access and this will allow you to choose you own cell delimiters and text delimiters. You need to choose External data from the menu, select your file and step through the wizard.
About importing and linking data and database objects -- Applies to: Microsoft Office Access 2003
Introduction to importing and exporting data -- Applies to: Microsoft Access 2010
Once you get the import working using the wizards, you can save an import specification and use it for you next DoCmd.TransferText as outlined by @Olivier Jacot-Descombes. This will allow you to have non-standard delimiters such as semi colon and single-quoted text.
myDiv.textContent = arbitraryHtmlString
as @Dan pointed out, do not use innerHTML, even in nodes you don't append to the document because deffered callbacks and scripts are always executed. You can check this https://gomakethings.com/preventing-cross-site-scripting-attacks-when-using-innerhtml-in-vanilla-javascript/ for more info.
it simple, select columns want to insert primary key and click on Key icon on header and save table
happy coding..,
Prior Swift 3.0 :
String(data: yourData, encoding: NSUTF8StringEncoding)
For Swift 4.0:
String(data: yourData, encoding: .utf8)
NULL can also be found in:
#include <string.h>
String.h will pull in the NULL from somewhere else.
You can use a \r
(carriage return) to return the cursor to the beginning of the line:
printf("hello");
printf("\rbye");
This will print bye on the same line. It won't erase the existing characters though, and because bye is shorter than hello, you will end up with byelo. To erase it you can make your new print longer to overwrite the extra characters:
printf("hello");
printf("\rbye ");
Or, first erase it with a few spaces, then print your new string:
printf("hello");
printf("\r ");
printf("\rbye");
That will print hello, then go to the beginning of the line and overwrite it with spaces, then go back to the beginning again and print bye.
Check the properties of App.xaml. Is the Build Action
still ApplicationDefinition
?
You can set a control variable in vars files located in group_vars/
or directly in hosts file like this:
[vagrant:vars]
test_var=true
[location-1]
192.168.33.10 hostname=apollo
[location-2]
192.168.33.20 hostname=zeus
[vagrant:children]
location-1
location-2
And run tasks like this:
- name: "test"
command: "echo {{test_var}}"
when: test_var is defined and test_var
You can not do that directly. You need to use std::remove
algorithm to move the element to be erased to the end of the vector and then use erase
function. Something like: myVector.erase(std::remove(myVector.begin(), myVector.end(), 8), myVec.end());
. See this erasing elements from vector for more details.
I am new to AJAX and I have tried this and it works well.
function q1mrks(country,m) {
// alert("hellow");
if (country.length==0) {
//alert("hellow");
document.getElementById("q1mrks").innerHTML="";
return;
}
if (window.XMLHttpRequest) {
// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp=new XMLHttpRequest();
} else {
// code for IE6, IE5
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange=function() {
if (xmlhttp.readyState==4 && xmlhttp.status==200) {
document.getElementById("q1mrks").innerHTML=xmlhttp.responseText;
}
}
xmlhttp.open("GET","../location/cal_marks.php?q1mrks="+country+"&marks="+m,true);
//mygetrequest.open("GET", "basicform.php?name="+namevalue+"&age="+agevalue, true)
xmlhttp.send();
}
This is to answer the part:
I was trying to understand whether dimension tables can be fact table as well or not?
The short answer (INMO) is No.That is because the 2 types of tables are created for different reasons. However, from a database design perspective, a dimension table could have a parent table as the case with the fact table which always has a dimension table (or more) as a parent. Also, fact tables may be aggregated, whereas Dimension tables are not aggregated. Another reason is that fact tables are not supposed to be updated in place whereas Dimension tables could be updated in place in some cases.
More details:
Fact and dimension tables appear in a what is commonly known as a Star Schema. A primary purpose of star schema is to simplify a complex normalized set of tables and consolidate data (possibly from different systems) into one database structure that can be queried in a very efficient way.
On its simplest form, it contains a fact table (Example: StoreSales) and a one or more dimension tables. Each Dimension entry has 0,1 or more fact tables associated with it (Example of dimension tables: Geography, Item, Supplier, Customer, Time, etc.). It would be valid also for the dimension to have a parent, in which case the model is of type "Snow Flake". However, designers attempt to avoid this kind of design since it causes more joins that slow performance. In the example of StoreSales, The Geography dimension could be composed of the columns (GeoID, ContenentName, CountryName, StateProvName, CityName, StartDate, EndDate)
In a Snow Flakes model, you could have 2 normalized tables for Geo information, namely: Content Table, Country Table.
You can find plenty of examples on Star Schema. Also, check this out to see an alternative view on the star schema model Inmon vs. Kimball. Kimbal has a good forum you may also want to check out here: Kimball Forum.
Edit: To answer comment about examples for 4NF:
Sales Fact (ID, BranchID, SalesPersonID, ItemID, Amount, TimeID)
AggregatedSales (BranchID, TotalAmount)
Here the relation is in 4NF
The last example is rather uncommon.
There are two extensions for memcached in PHP, "memcache" and "memcached".
It looks like you're trying to use one ("memcache"), but the other is installed ("memcached").
As the createdb documentation states:
The first database is always created by the initdb command when the data storage area is initialized... This database is called postgres.
So if certain OS/postgresql distributions do that differently, it is certainly not the default/standard (just verified that initdb
on openSUSE 13.1 creates the DB "postgres", but not "<user>"). Long story short, psql -d postgres
is expected to be used when using a user other than "postgres".
Obviously the accepted answer, running createdb
to create a DB named like the user, works as well, but creates a superfluous DB.
Using str_replace()
to remove the dots is not overkill.
$string_number = '1.512.523,55';
// NOTE: You don't really have to use floatval() here, it's just to prove that it's a legitimate float value.
$number = floatval(str_replace(',', '.', str_replace('.', '', $string_number)));
// At this point, $number is a "natural" float.
print $number;
This is almost certainly the least CPU-intensive way you can do this, and odds are that even if you use some fancy function to do it, that this is what it does under the hood.
ChangeDetectorRef.detectChanges()
is usually the most focused way of doing this. ApplicationRef.tick()
is usually too much of a sledgehammer approach.
To use ChangeDetectorRef.detectChanges()
, you'll need this at the top of your component:
import { ChangeDetectorRef } from '@angular/core';
... then, usually you alias that when you inject it in your constructor like this:
constructor( private cdr: ChangeDetectorRef ) { ... }
Then, in the appropriate place, you call it like this:
this.cdr.detectChanges();
Where you call ChangeDetectorRef.detectChanges()
can be highly significant. You need to completely understand the life cycle and exactly how your application is functioning and rendering its components. There's no substitute here for completely doing your homework and making sure you understand the Angular lifecycle inside out. Then, once you understand that, you can use ChangeDetectorRef.detectChanges()
appropriately (sometimes it's very easy to understand where you should use it, other times it can be very complex).
Looks like you might have until the end of 2013 before they officially close it down. http://groups.google.com/group/google-ajax-search-api/browse_thread/thread/6aaa1b3529620610/d70f8eec3684e431?lnk=gst&q=news+api#d70f8eec3684e431
Also, it sounds like they are building a replacement... but it's going to cost you.
I'd say, go to a different service. I think bing has a news API.
You might enjoy (or not) reading: http://news.ycombinator.com/item?id=1864625
Use your jquery like this
$('.home').css({'background-image':'url(images/tabs3.png)'});
This works for me.
@Test
public void cloneTest() {
List<Part> parts = new ArrayList<Part>();
Part part1 = new Part(1);
parts.add(part1);
Part part2 = new Part(2);
parts.add(part2);
try {
ObjectMapper objectMapper = new ObjectMapper();
String jsonStr = objectMapper.writeValueAsString(parts);
List<Part> cloneParts = objectMapper.readValue(jsonStr, new TypeReference<ArrayList<Part>>() {});
} catch (Exception e) {
//fail("failed.");
e.printStackTrace();
}
//TODO: Assert: compare both list values.
}
David's answer is correct. I'd like to add that you might be getting a sign from God that your design is messed up, and that "Son" ought not to be a subclass of "Super", but that, instead, Super has some implementation detail best expressed by having the functionality that Son provides, as a strategy of sorts.
EDIT: Jon Skeet's answer is awesomest.
sudo add-apt-repository -y ppa:webupd8team/java
sudo apt-get update
sudo apt-get install oracle-java7-installer oracle-java7-set-default
wget https://dl.google.com/dl/android/studio/ide-zips/2.2.0.12/android-studio-ide-145.3276617-linux.zip
unzip android-studio-ide-145.3276617-linux.zip
cd android-studio/bin
./studio.sh
Edit: seems I was wrong in assuming you could not get the element. As others have posted here, you can get it with:
$('#element').get(0);
I have verified this actually returns the DOM element that was matched.
The change in Manifest file did not change the App name,
<application android:icon="@drawable/ic__logo" android:theme="@style/AppTheme" android:largeHeap="true" android:label="@string/app_name">
but changing the Label
attribute in the MainLauncher
did the trick for me .
[Activity(Label = "@string/app_name", MainLauncher = true, Theme = "@style/MainActivityNoActionBarTheme", ScreenOrientation = ScreenOrientation.Portrait)]
Firstly the setting of IDENTITY_INSERT on or off for that matter will not work for what you require (it is used for inserting new values, such as plugging gaps).
Doing the operation through the GUI just creates a temporary table, copies all the data across to a new table without an identity field, and renames the table.
I did not find the -q1
option on my netcat. Instead I used the -w1
option. Below is the bash script I did to send an udp packet to any host and port:
#!/bin/bash
def_host=localhost
def_port=43211
HOST=${2:-$def_host}
PORT=${3:-$def_port}
echo -n "$1" | nc -4u -w1 $HOST $PORT
While I know many architectures like ASP.NET MVC have built-in functionality to handle JSON.stringify as the contentType my situation is a little different so maybe this may help someone in the future. I know it would have saved me hours!
Since my http requests are being handled by a CGI API from IBM (AS400 environment) on a different subdomain these requests are cross origin, hence the jsonp. I actually send my ajax via javascript object(s). Here is an example of my ajax POST:
var data = {USER : localProfile,
INSTANCE : "HTHACKNEY",
PAGE : $('select[name="PAGE"]').val(),
TITLE : $("input[name='TITLE']").val(),
HTML : html,
STARTDATE : $("input[name='STARTDATE']").val(),
ENDDATE : $("input[name='ENDDATE']").val(),
ARCHIVE : $("input[name='ARCHIVE']").val(),
ACTIVE : $("input[name='ACTIVE']").val(),
URGENT : $("input[name='URGENT']").val(),
AUTHLST : authStr};
//console.log(data);
$.ajax({
type: "POST",
url: "http://www.domian.com/webservicepgm?callback=?",
data: data,
dataType:'jsonp'
}).
done(function(data){
//handle data.WHATEVER
});
I'm facing same issue. Solved it using by http://
or https://
in react js.
Like as:
<a target="_blank" href="http://www.example.com/" title="example">See detail</a>
The answer is no, but you can use collections.OrderedDict
from the Python standard library with just keys (and values as None
) for the same purpose.
Update: As of Python 3.7 (and CPython 3.6), standard dict
is guaranteed to preserve order and is more performant than OrderedDict
. (For backward compatibility and especially readability, however, you may wish to continue using OrderedDict
.)
Here's an example of how to use dict
as an ordered set to filter out duplicate items while preserving order, thereby emulating an ordered set. Use the dict
class method fromkeys()
to create a dict, then simply ask for the keys()
back.
>>> keywords = ['foo', 'bar', 'bar', 'foo', 'baz', 'foo']
>>> list(dict.fromkeys(keywords))
['foo', 'bar', 'baz']
Start with:
setup.exe /?
And you should see a dialog popup with some options displayed.
In case it helps anyone, my issue was extremely silly. Totally my fault of course. A notification was triggering a method that was calling the modal. But I wasn't removing the notification correctly, so at some point, I would have more than one notification, so the modal would get called multiple times. Of course, after you call the modal once, the viewcontroller that calls it it's not longer in the view hierarchy, that's why we see this issue. My situation caused a bunch of other issue too, as you would expect.
So to summarize, whatever you're doing make sure the modal is not being called more than once.
See the documentation for the HTTP module for a full example:
https://nodejs.org/api/http.html#http_http_request_options_callback
Try this:
update Projects
set KickOffStatus=2
where KickOffStatus is null
It has been asked in the past, apparently it costs a lot to mobile browsers, so it's been disabled.
Check this comment by @PaulIrish:
Fixed-backgrounds have huge repaint cost and decimate scrolling performance, which is, I believe, why it was disabled.
you can see workarounds to this in this posts:
You can use a Python script with scp and os library to make a system call.
import os
cmd = 'scp user@remote_server_address:remote_file_path local_file_path'
os.system(cmd)
There's a simple online tool that can do this called sqlizer.io.
You upload an XLSX file to it, enter a sheet name and cell range, and it will generate a CREATE TABLE statement and a bunch of INSERT statements to import all your data into a MySQL database.
(Disclaimer: I help run SQLizer)
<input type="text" class="form-control" id="odometer_reading" name="odometer_reading" placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
I had a similar symptom. In my case though, my idiocy was in unintentionally also having an empty index.html file in the web root folder. Apache was serving this rather than index.php when I didn't explicitly request index.php, since DirectoryIndex
was configured as follows in mods-available/dir.conf
:
DirectoryIndex index.html index.cgi index.pl index.php index.xhtml index.htm
That is, 'index.html' appears ahead of 'index.php' in the priority list. Removing the index.html file from the web root naturally resolved the problem. D'oh!
You have to use CASE Statement/Expression
Select * from Customer
WHERE (I.IsClose=@ISClose OR @ISClose is NULL)
AND
(C.FirstName like '%'+@ClientName+'%' or @ClientName is NULL )
AND
CASE @Value
WHEN 2 THEN (CASE I.RecurringCharge WHEN @Total or @Total is NULL)
WHEN 3 THEN (CASE WHEN I.RecurringCharge like
'%'+cast(@Total as varchar(50))+'%'
or @Total is NULL )
END