Here's an easy solution and it's great for encoding accented characters too!
String in = "Hi Lârry & Môe!";
StringBuilder out = new StringBuilder();
for(int i = 0; i < in.length(); i++) {
char c = in.charAt(i);
if(c < 31 || c > 126 || "<>\"'\\&".indexOf(c) >= 0) {
out.append("&#" + (int) c + ";");
} else {
out.append(c);
}
}
System.out.printf("%s%n", out);
Outputs
Hi Lârry & Môe!
I update this function
now you can print any tag or any part of the page with its full style
must include jquery.js file
HTML
<div id='DivIdToPrint'>
<p>This is a sample text for printing purpose.</p>
</div>
<p>Do not print.</p>
<input type='button' id='btn' value='Print' onclick='printtag("DivIdToPrint");' >
JavaScript
function printtag(tagid) {
var hashid = "#"+ tagid;
var tagname = $(hashid).prop("tagName").toLowerCase() ;
var attributes = "";
var attrs = document.getElementById(tagid).attributes;
$.each(attrs,function(i,elem){
attributes += " "+ elem.name+" ='"+elem.value+"' " ;
})
var divToPrint= $(hashid).html() ;
var head = "<html><head>"+ $("head").html() + "</head>" ;
var allcontent = head + "<body onload='window.print()' >"+ "<" + tagname + attributes + ">" + divToPrint + "</" + tagname + ">" + "</body></html>" ;
var newWin=window.open('','Print-Window');
newWin.document.open();
newWin.document.write(allcontent);
newWin.document.close();
// setTimeout(function(){newWin.close();},10);
}
<?php
$post = ['batch_id'=> "2"];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL,'https://example.com/student_list.php');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($post));
$response = curl_exec($ch);
$result = json_decode($response);
curl_close($ch); // Close the connection
$new= $result->status;
if( $new =="1")
{
echo "<script>alert('Student list')</script>";
}
else
{
echo "<script>alert('Not Removed')</script>";
}
?>
git clone -o <sha1-of-the-commit> <repository-url> <local-dir-name>
git
uses the word origin
in stead of popularly known revision
Following is a snippet from the manual $ git help clone
--origin <name>, -o <name>
Instead of using the remote name origin to keep track of the upstream repository, use <name>.
The recommended way for Python 2.7 and 3.1 and later is to use importlib
module:
importlib.import_module(name, package=None)
Import a module. The name argument specifies what module to import in absolute or relative terms (e.g. either pkg.mod or ..mod). If the name is specified in relative terms, then the package argument must be set to the name of the package which is to act as the anchor for resolving the package name (e.g. import_module('..mod', 'pkg.subpkg') will import pkg.mod).
e.g.
my_module = importlib.import_module('os.path')
Currently experienced this problem with my Nexus 5, when attempting to sideload latest 4.4.1 OTA update via stock recovery.
Solution:
Err.. If you are a git noob are you sure you have git commit
before git push
? I made this mistake the first time!
A CharSequence
is an interface, not an actual class. An interface is just a set of rules (methods) that a class must contain if it implements the interface. In Android a CharSequence
is an umbrella for various types of text strings. Here are some of the common ones:
String
(immutable text with no styling spans)StringBuilder
(mutable text with no styling spans)SpannableString
(immutable text with styling spans)SpannableStringBuilder
(mutable text with styling spans)(You can read more about the differences between these here.)
If you have a CharSequence
object, then it is actually an object of one of the classes that implement CharSequence
. For example:
CharSequence myString = "hello";
CharSequence mySpannableStringBuilder = new SpannableStringBuilder();
The benefit of having a general umbrella type like CharSequence
is that you can handle multiple types with a single method. For example, if I have a method that takes a CharSequence
as a parameter, I could pass in a String
or a SpannableStringBuilder
and it would handle either one.
public int getLength(CharSequence text) {
return text.length();
}
You could say that a String
is just one kind of CharSequence
. However, unlike CharSequence
, it is an actual class, so you can make objects from it. So you could do this:
String myString = new String();
but you can't do this:
CharSequence myCharSequence = new CharSequence(); // error: 'CharSequence is abstract; cannot be instantiated
Since CharSequence
is just a list of rules that String
conforms to, you could do this:
CharSequence myString = new String();
That means that any time a method asks for a CharSequence
, it is fine to give it a String
.
String myString = "hello";
getLength(myString); // OK
// ...
public int getLength(CharSequence text) {
return text.length();
}
However, the opposite is not true. If the method takes a String
parameter, you can't pass it something that is only generally known to be a CharSequence
, because it might actually be a SpannableString
or some other kind of CharSequence
.
CharSequence myString = "hello";
getLength(myString); // error
// ...
public int getLength(String text) {
return text.length();
}
adapt-strap has very light weight module for this. here is the fiddle. Here are some attributes that are supported. There are more.
ad-drag="true"
ad-drag-data="car"
ad-drag-begin="onDragStart($data, $dragElement, $event);"
ad-drag-end="onDataEnd($data, $dragElement, $event);"
chars are just integers, so you can actually do a straight comparison of your character against literals:
if( c >= '0' && c <= '9' ){
This applies to all characters. See your ascii table.
ctype.h also provides functions to do this for you.
import AVFoundation
import AudioToolbox
public final class MP3Player : NSObject {
// Singleton class
static let shared:MP3Player = MP3Player()
private var player: AVAudioPlayer? = nil
// Play only mp3 which are stored in the local
public func playLocalFile(name:String) {
guard let url = Bundle.main.url(forResource: name, withExtension: "mp3") else { return }
do {
try AVAudioSession.sharedInstance().setCategory(AVAudioSession.Category.playback)
try AVAudioSession.sharedInstance().setActive(true)
player = try AVAudioPlayer(contentsOf: url, fileTypeHint: AVFileType.mp3.rawValue)
guard let player = player else { return }
player.play()
}catch let error{
print(error.localizedDescription)
}
}
}
To call this function
MP3Player.shared.playLocalFile(name: "JungleBook")
If you don't want to use CSS try this one between your rows:
<tr>
<td class="divider"><hr /></td>
</tr>
Cheers!!
https://www.microsoft.com/en-us/download/details.aspx?id=20098 - when you run this software . it will extract dll file. and paste two dll file(php_pdo_sqlsrv_55_ts.dll,extension=php_sqlsrv_55_ts.dll) this location C:\wamp\bin\php\php5.6.40\ext\ (pls make sure your current version)
2)edit php.ini file add below line extension=php_pdo_sqlsrv_55_ts.dll extension=php_sqlsrv_55_ts.dll
Please refer screenshort add dll in your php.ini file
Just put ScriptManager
inside form
tag like this:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server">
</asp:ScriptManager>
If it has Master Page
then Put this in the Master Page itself.
Yeah, by using $(this)
, you enabled jQuery functionality for the object. By just using this
, it only has generic Javascript functionality.
If you are looking for an alternative solution and can manage the vimeo account there is another way, you simply add every video you want to show into an album and then use the API to request the album details - it then shows all the thumbnails and links. It's not ideal but might help.
Twitter convo with @vimeoapi
Basically, you need to include the Wordpress loop in your search.php template to loop through the search results and show them as part of the template.
Below is a very basic example from The WordPress Theme Search Template and Page Template over at ThemeShaper.
<?php
/**
* The template for displaying Search Results pages.
*
* @package Shape
* @since Shape 1.0
*/
get_header(); ?>
<section id="primary" class="content-area">
<div id="content" class="site-content" role="main">
<?php if ( have_posts() ) : ?>
<header class="page-header">
<h1 class="page-title"><?php printf( __( 'Search Results for: %s', 'shape' ), '<span>' . get_search_query() . '</span>' ); ?></h1>
</header><!-- .page-header -->
<?php shape_content_nav( 'nav-above' ); ?>
<?php /* Start the Loop */ ?>
<?php while ( have_posts() ) : the_post(); ?>
<?php get_template_part( 'content', 'search' ); ?>
<?php endwhile; ?>
<?php shape_content_nav( 'nav-below' ); ?>
<?php else : ?>
<?php get_template_part( 'no-results', 'search' ); ?>
<?php endif; ?>
</div><!-- #content .site-content -->
</section><!-- #primary .content-area -->
<?php get_sidebar(); ?>
<?php get_footer(); ?>
If you would like to output array within string using puts
, you will get the same result as if you were using print
:
puts "#{[0, 1, nil]}":
[0, 1, nil]
But if not withing a quoted string then yes. The only difference is between new line when we use puts
.
class Globals {
static String ouch = "I'm global.."
}
println Globals.ouch
Your box doesn't have a size. If you set the width and height, it works just fine:
var Box = React.createClass({_x000D_
getInitialState: function() {_x000D_
return {_x000D_
color: 'black'_x000D_
};_x000D_
},_x000D_
_x000D_
changeColor: function() {_x000D_
var newColor = this.state.color == 'white' ? 'black' : 'white';_x000D_
this.setState({_x000D_
color: newColor_x000D_
});_x000D_
},_x000D_
_x000D_
render: function() {_x000D_
return (_x000D_
<div>_x000D_
<div_x000D_
style = {{_x000D_
background: this.state.color,_x000D_
width: 100,_x000D_
height: 100_x000D_
}}_x000D_
onClick = {this.changeColor}_x000D_
>_x000D_
</div>_x000D_
</div>_x000D_
);_x000D_
}_x000D_
});_x000D_
_x000D_
ReactDOM.render(_x000D_
<Box />,_x000D_
document.getElementById('box')_x000D_
);
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
_x000D_
<div id='box'></div>
_x000D_
In general, it's not safe, though for some collections it may be. The obvious alternative is to use some kind of for loop. But you didn't say what collection you're using, so that may or may not be possible.
I know this is a very old question, but this worked for me:
UPDATE TABLE SET FIELD1 =
CASE
WHEN FIELD1 = Condition1 THEN 'Result1'
WHEN FIELD1 = Condition2 THEN 'Result2'
WHEN FIELD1 = Condition3 THEN 'Result3'
END;
Regards
In year of 2020, these code seems to return exception as
System.Net.Mail.SmtpStatusCode.MustIssueStartTlsFirst or The SMTP server requires a secure connection or the client was not authenticated. The server response was: 5.7.57 SMTP; Client was not authenticated to send anonymous mail during MAIL FROM
This code is working for me.
using (SmtpClient client = new SmtpClient()
{
Host = "smtp.office365.com",
Port = 587,
UseDefaultCredentials = false, // This require to be before setting Credentials property
DeliveryMethod = SmtpDeliveryMethod.Network,
Credentials = new NetworkCredential("[email protected]", "password"), // you must give a full email address for authentication
TargetName = "STARTTLS/smtp.office365.com", // Set to avoid MustIssueStartTlsFirst exception
EnableSsl = true // Set to avoid secure connection exception
})
{
MailMessage message = new MailMessage()
{
From = new MailAddress("[email protected]"), // sender must be a full email address
Subject = subject,
IsBodyHtml = true,
Body = "<h1>Hello World</h1>",
BodyEncoding = System.Text.Encoding.UTF8,
SubjectEncoding = System.Text.Encoding.UTF8,
};
var toAddresses = recipients.Split(',');
foreach (var to in toAddresses)
{
message.To.Add(to.Trim());
}
try
{
client.Send(message);
}
catch (Exception ex)
{
Debug.WriteLine(ex.Message);
}
}
Use money-rails gem. It nicely handles money and currencies in your model and also has a bunch of helpers to format your prices.
you can try in this way if you are using thymeleaf
sec:authorize="hasAnyRole(T(com.orsbv.hcs.model.SystemRole).ADMIN.getName(),
T(com.orsbv.hcs.model.SystemRole).SUPER_USER.getName(),'ROLE_MANAGEMENT')"
this will return true if the user has the mentioned roles,false otherwise.
Please note you have to use sec tag in your html declaration tag like this
<html xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity4">
You are probably having a problem with the sort of CSV file that you have.
Open the CSV file with a text editor, check that all the separations are done with the comma, and not semicolon and try the script again. It should work fine.
public String hashString(String s) throws NoSuchAlgorithmException {
byte[] hash = null;
try {
MessageDigest md = MessageDigest.getInstance("SHA-256");
hash = md.digest(s.getBytes());
} catch (NoSuchAlgorithmException e) { e.printStackTrace(); }
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hash.length; ++i) {
String hex = Integer.toHexString(hash[i]);
if (hex.length() == 1) {
sb.append(0);
sb.append(hex.charAt(hex.length() - 1));
} else {
sb.append(hex.substring(hex.length() - 2));
}
}
return sb.toString();
}
How is this different from the following?
This line of code here:
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
constructs a new String object (i.e. a copy of oldString
), while this line of code:
String newString = oldString;
declares a new variable of type java.lang.String
and initializes it to refer to the same String object as the variable oldString
.
Is there any scenario in which the two lines will have different outputs?
Absolutely:
String newString = oldString;
boolean isSameInstance = newString == oldString; // isSameInstance == true
vs.
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
// isSameInstance == false (in most cases)
boolean isSameInstance = newString == oldString;
a_horse_with_no_name (see comment) is right of course. The equivalent of
String newString = new String(oldString.getBytes("UTF-8"), "UTF-8"));
is
String newString = new String(oldString);
minus the subtle difference wrt the encoding that Peter Lawrey explains in his answer.
Change to the touchstart
event instead of touchmove
. Under One Finger Events it says that no events are sent during a pan, so touchmove
may be too late.
I added the listener to document, not body.
Example:
document.ontouchstart = function(e){
e.preventDefault();
}
mysql_query
function is used for executing mysql query in php. mysql_query
returns false if query execution fails.Alternatively you can try using mysql_error()
function
For e.g
$result=mysql_query($sql)
or
die(mysql_error());
In above code snippet if query execution fails then it will terminate the execution and display mysql error while execution of sql query.
you did not use S anywhere in your algorithm (besides modifying it). the idea of dijkstra is once a vertex is on S, it will not be modified ever again. in this case, once B is inside S, you will not reach it again via C.
this fact ensures the complexity of O(E+VlogV) [otherwise, you will repeat edges more then once, and vertices more then once]
in other words, the algorithm you posted, might not be in O(E+VlogV), as promised by dijkstra's algorithm.
Dinah:
In the Context of a Repository the Aggregate Root is an Entity with no parent Entity. It contains zero, One or Many Child Entities whose existence is dependent upon the Parent for it's identity. That's a One To Many relationship in a Repository. Those Child Entities are plain Aggregates.
The proper way to install an MSI silently is via the msiexec.exe command line
as follows:
msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"
Quick explanation:
/L*V "C:\Temp\msilog.log"= verbose logging
/QN = run completely silently
/i = run install sequence
There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.
throw
is for rethrowing a caught exception. This can be useful if you want to do something with the exception before passing it up the call chain.
Using throw
without any arguments preserves the call stack for debugging purposes.
select t1.id, t1.SomeNumt, SUM(t2.SomeNumt) as sum
from @t t1
inner join @t t2 on t1.id >= t2.id
group by t1.id, t1.SomeNumt
order by t1.id
Output
| ID | SOMENUMT | SUM |
-----------------------
| 1 | 10 | 10 |
| 2 | 12 | 22 |
| 3 | 3 | 25 |
| 4 | 15 | 40 |
| 5 | 23 | 63 |
Edit: this is a generalized solution that will work across most db platforms. When there is a better solution available for your specific platform (e.g., gareth's), use it!
You can use the System.Diagnostics.Process.Start method to start a process. You can even pass a URL as a string and it'll kick off the default browser.
you can use the return
statement without any parameter to exit a function
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
return
do much much more...
or raise an exception if you want to be informed of the problem
def foo(element):
do something
if check is true:
do more (because check was succesful)
else:
raise Exception("cause of the problem")
do much much more...
No, there is no built-in support for number formatting, but googling will turn up loads of code snippets that will do this for you.
EDIT: I missed the last sentence of your post. Try http://code.google.com/p/jquery-utils/wiki/StringFormat for a jQuery solution.
Just for fun, I'm going to use a single event on the whole document instead of adding an event to all the anchor tags:
document.body.onclick = function( e ) {
// Cross-browser handling
var evt = e || window.event,
target = evt.target || evt.srcElement;
// If the element clicked is an anchor
if ( target.nodeName === 'A' ) {
// Add the confirm box
return confirm( 'Are you sure?' );
}
};
This method would be more efficient if you had many anchor tags. Of course, it becomes even more efficient when you add this event to the container having all the anchor tags.
Hash map works on the principle of hashing
HashMap get(Key k) method calls hashCode method on the key object and applies returned hashValue to its own static hash function to find a bucket location(backing array) where keys and values are stored in form of a nested class called Entry (Map.Entry) . So you have concluded that from the previous line that Both key and value is stored in the bucket as a form of Entry object . So thinking that Only value is stored in the bucket is not correct and will not give a good impression on the interviewer .
If key is null , then Null keys always map to hash 0, thus index 0.
If key is not null then , it will call hashfunction on the key object , see line 4 in above method i.e. key.hashCode() ,so after key.hashCode() returns hashValue , line 4 looks like
int hash = hash(hashValue)
and now ,it applies returned hashValue into its own hashing function .
We might wonder why we are calculating the hashvalue again using hash(hashValue). Answer is It defends against poor quality hash functions.
Now final hashvalue is used to find the bucket location at which the Entry object is stored . Entry object stores in the bucket like this (hash,key,value,bucketindex)
Have a look to this wiki: LaTeX/Labels and Cross-referencing:
The hyperref package automatically includes the nameref package, and a similarly named command. It inserts text corresponding to the section name, for example:
\section{MyFirstSection}
\label{marker}
\section{MySecondSection} In section \nameref{marker} we defined...
1: Add the following line into the AssemblyInfo class
[assembly: log4net.Config.XmlConfigurator(Watch = true)]
2: Make sure you don't use .Net Framework 4 Client Profile
as Target Framework
(I think this is OK on your side because otherwise it even wouldn't compile)
3: Make sure you log very early in your program. Otherwise, in some scenarios, it will not be initialized properly (read more on log4net FAQ).
So log something during application startup in the Global.asax
public class Global : System.Web.HttpApplication
{
private static readonly log4net.ILog Log = log4net.LogManager.GetLogger(typeof(Global));
protected void Application_Start(object sender, EventArgs e)
{
Log.Info("Startup application.");
}
}
4: Make sure you have permission to create files and folders on the given path (if the folder itself also doesn't exist)
5: The rest of your given information looks ok
Hope this will help you. I am using this solution for Search on some columns but i don't want to display them on frontend.
$(document).ready(function() {
$('#example').dataTable({
"scrollY": "500px",
"scrollCollapse": true,
"scrollX": false,
"bPaginate": false,
"columnDefs": [
{
"width": "30px",
"targets": 0,
},
{
"width": "100px",
"targets": 1,
},
{
"width": "100px",
"targets": 2,
},
{
"width": "76px",
"targets": 5,
},
{
"width": "80px",
"targets": 6,
},
{
"targets": [ 7 ],
"visible": false,
"searchable": true
},
{
"targets": [ 8 ],
"visible": false,
"searchable": true
},
{
"targets": [ 9 ],
"visible": false,
"searchable": true
},
]
});
});
I solved this problem by running commands on windows 7 CMD as given in this here is the link last post on this thread,
https://github.com/mitchellh/vagrant/issues/6744
Some commands that will reinitialize various network states:
Reset WINSOCK entries to installation defaults : netsh winsock reset catalog
Reset TCP/IP stack to installation defaults : netsh int ip reset reset.log
Flush DNS resolver cache : ipconfig /flushdns
Renew DNS client registration and refresh DHCP leases : ipconfig /registerdns
Flush routing table : route /f
var d = new Date();_x000D_
document.write(d + "<br/>");_x000D_
d.setMonth(d.getMonth() - 6);_x000D_
document.write(d);
_x000D_
Use ldapsearch
to authenticate. The opends
version might be used as follows:
ldapsearch --hostname hostname --port port \
--bindDN userdn --bindPassword password \
--baseDN '' --searchScope base 'objectClass=*' 1.1
What you have is correct, though you will not call it global, it is a class attribute and can be accessed via class e.g Shape.lolwut
or via an instance e.g. shape.lolwut
but be careful while setting it as it will set an instance level attribute not class attribute
class Shape(object):
lolwut = 1
shape = Shape()
print Shape.lolwut, # 1
print shape.lolwut, # 1
# setting shape.lolwut would not change class attribute lolwut
# but will create it in the instance
shape.lolwut = 2
print Shape.lolwut, # 1
print shape.lolwut, # 2
# to change class attribute access it via class
Shape.lolwut = 3
print Shape.lolwut, # 3
print shape.lolwut # 2
output:
1 1 1 2 3 2
Somebody may expect output to be 1 1 2 2 3 3
but it would be incorrect
String onevalue;
if(request.getParameterMap().containsKey("one")!=false)
{
onevalue=request.getParameter("one").toString();
}
I was having the same issue, and for me it worked by simply concatenating https:${image.getAttribute('src')}
Working with a dictionary ->level2 above comes from a dictionary in my case (just in case anybody will find it useful) Trying the first example I stumbled over this error: "This document already has a 'DocumentElement' node." I was inspired by the answer here
and edited my code: (xmlDoc.DocumentElement.AppendChild(body))
//a dictionary:
Dictionary<string, string> Level2Data
{
{"level2", "text"},
{"level2", "other text"},
{"same_level2", "more text"}
}
//xml Decalration:
XmlDocument xmlDoc = new XmlDocument();
XmlDeclaration xmlDeclaration = xmlDoc.CreateXmlDeclaration("1.0", "UTF-8", null);
XmlElement root = xmlDoc.DocumentElement;
xmlDoc.InsertBefore(xmlDeclaration, root);
// add body
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.AppendChild(body);
XmlElement body = xmlDoc.CreateElement(string.Empty, "body", string.Empty);
xmlDoc.DocumentElement.AppendChild(body); //without DocumentElement ->ERR
foreach (KeyValuePair<string, string> entry in Level2Data)
{
//write to xml: - it works version 1.
XmlNode keyNode = xmlDoc.CreateElement(entry.Key); //open TAB
keyNode.InnerText = entry.Value;
body.AppendChild(keyNode); //close TAB
//Write to xmml verdion 2: (uncomment the next 4 lines and comment the above 3 - version 1
//XmlElement key = xmlDoc.CreateElement(string.Empty, entry.Key, string.Empty);
//XmlText value = xmlDoc.CreateTextNode(entry.Value);
//key.AppendChild(value);
//body.AppendChild(key);
}
Both versions (1 and 2 inside foreach loop) give the output:
<?xml version="1.0" encoding="UTF-8"?>
<body>
<level1>
<level2>text</level2>
<level2>ther text</level2>
<same_level2>more text</same_level2>
</level1>
</body>
(Note: third line "same level2" in dictionary can be also level2 as the others but I wanted to ilustrate the advantage of the dictionary - in my case I needed level2 with different names.
I found the below works for my setup using cards and grid system. I set the flex-grow property of card-image-top class to 1 and the object fit on the same to contain and the flex-grow property of the body to 0.
HTML
<div class="container-fluid">
<div class="row row-cols-2 row-cols-md-4">
<div class="col mb-4">
<div class="card h-100">
<img src="https://i0.wp.com/www.impact-media.be/wp-content/uploads/2019/09/placeholder-1-e1533569576673-960x960.png" class="card-img-top">
<div class="card-body">
<p class="card-text">Test</p>
</div>
</div>
</div>
<div class="col mb-4">
<div class="card h-100">
<img src="http://www.nebero.com/wp-content/uploads/2014/05/placeholder.jpg" class="card-img-top">
<div class="card-body">
<p class="card-text">Test</p>
</div>
</div>
</div>
<div class="col mb-4">
<div class="card h-100">
<img src="http://www.nebero.com/wp-content/uploads/2014/05/placeholder.jpg" class="card-img-top">
<div class="card-body">
<p class="card-text">Test</p>
</div>
</div>
</div>
<div class="col mb-4">
<div class="card h-100">
<img src="https://i0.wp.com/www.impact-media.be/wp-content/uploads/2019/09/placeholder-1-e1533569576673-960x960.png" class="card-img-top">
<div class="card-body">
<p class="card-text">Test</p>
</div>
</div>
</div>
</div>
</div>
CSS
.card-img-top {
flex-grow: 1;
object-fit:contain;
}
.card-body{
flex-grow:0;
}
5623125698541159
is treated as a single number (out of range of int
on most architecture). You need to write numbers in your file as
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
for 16 numbers.
If your file has input
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
then change %d
specifier in your fscanf
to %d,
.
fscanf(myFile, "%d,", &numberArray[i] );
Here is your full code after few modifications:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
If you are looking for readability, I believe that this is that code:
print '%(kg).2f kg = %(lb).2f lb = %(gal).2f gal = %(l).2f l' % {
'kg': var1,
'lb': var2,
'gal': var3,
'l': var4,
}
It can be done easily by the following
Calendar calendar = Calendar.getInstance();
// from current time
long curTimeInMills = new Date().getTime();
long timeInMills = curTimeInMills - 5 * (24*60*60*1000); // `enter code here`subtract like 5 days
calendar.setTimeInMillis(timeInMills);
System.out.println(calendar.getTime());
// from specific time like (08 05 2015)
calendar.set(Calendar.DAY_OF_MONTH, 8);
calendar.set(Calendar.MONTH, (5-1));
calendar.set(Calendar.YEAR, 2015);
timeInMills = calendar.getTimeInMillis() - 5 * (24*60*60*1000);
calendar.setTimeInMillis(timeInMills);
System.out.println(calendar.getTime());
Try this
let val = this.SurveysList.filter(xi => {
if (xi.id == parseInt(this.apiId ? '0' : this.apiId))
return xi.Description;
})
console.log('Description : ', val );
In order to change date format in the views.py and then assign it to template.
# get the object details
home = Home.objects.get(home_id=homeid)
# get the start date
_startDate = home.home_startdate.strftime('%m/%d/%Y')
# assign it to template
return render_to_response('showme.html'
{'home_startdate':_startDate},
context_instance=RequestContext(request) )
So apparently, all I needed was the "build-essential" package, then to run autoconf
first, which made the Makefile.pre.in
, then the ./configure
then the make
which works perfectly...
maybe not the most efficient, but reads data in one line:
#include<iostream>
#include<vector>
#include<iterator>
main(int argc,char *argv[]){
// read standard input into vector:
std::vector<char>v(std::istream_iterator<char>(std::cin),
std::istream_iterator<char>());
std::cout << "read " << v.size() << "chars\n";
}
I was not able to uninstall PostgreSQL 9.0.8. But I finally found this. (I installed Postgres using homebrew)
brew list
Look for the correct folder name. Something like.
postgresql9
Once you find the correct name do:
brew uninstall postgresql9
That should uninstall it.
EDIT: Cactus is now a dead project: http://attic.apache.org/projects/jakarta-cactus.html
You may want to look at cactus.
http://jakarta.apache.org/cactus/
Project Description
Cactus is a simple test framework for unit testing server-side java code (Servlets, EJBs, Tag Libs, Filters, ...).
The intent of Cactus is to lower the cost of writing tests for server-side code. It uses JUnit and extends it.
Cactus implements an in-container strategy, meaning that tests are executed inside the container.
you can loop through the data frame like this .
for ad in range(1,dataframe_c.size):
print(dataframe_c.values[ad])
For Xamarin iOS
btnObj.SendActionForControlEvents(UIControlEvent.TouchUpInside);
This is a dirty hack, but may work.
s2 = ""
for i in s:
if ord(i) < 128:
s2 += i
In First activity:
ArrayList<ContactBean> fileList = new ArrayList<ContactBean>();
Intent intent = new Intent(MainActivity.this, secondActivity.class);
intent.putExtra("FILES_TO_SEND", fileList);
startActivity(intent);
In receiver activity:
ArrayList<ContactBean> filelist = (ArrayList<ContactBean>)getIntent().getSerializableExtra("FILES_TO_SEND");`
A lambda
is an anonymous function:
>>> f = lambda: 'foo'
>>> print f()
foo
It is often used in functions such as sorted()
that take a callable as a parameter (often the key
keyword parameter). You could provide an existing function instead of a lambda
there too, as long as it is a callable object.
Take the sorted()
function as an example. It'll return the given iterable in sorted order:
>>> sorted(['Some', 'words', 'sort', 'differently'])
['Some', 'differently', 'sort', 'words']
but that sorts uppercased words before words that are lowercased. Using the key
keyword you can change each entry so it'll be sorted differently. We could lowercase all the words before sorting, for example:
>>> def lowercased(word): return word.lower()
...
>>> lowercased('Some')
'some'
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lowercased)
['differently', 'Some', 'sort', 'words']
We had to create a separate function for that, we could not inline the def lowercased()
line into the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
File "<stdin>", line 1
sorted(['Some', 'words', 'sort', 'differently'], key=def lowercased(word): return word.lower())
^
SyntaxError: invalid syntax
A lambda
on the other hand, can be specified directly, inline in the sorted()
expression:
>>> sorted(['Some', 'words', 'sort', 'differently'], key=lambda word: word.lower())
['differently', 'Some', 'sort', 'words']
Lambdas are limited to one expression only, the result of which is the return value.
There are loads of places in the Python library, including built-in functions, that take a callable as keyword or positional argument. There are too many to name here, and they often play a different role.
Adding background color helped me.
<CalendarView
android:layout_width="match_parent"
android:id="@+id/calendarView"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_height="wrap_content"
android:elevation="5dp"
android:background="@color/windowBackground"
/>
I have the same problem, but you know why? because I didn't put .txt in the end of my File and so it was File not a textFile, you shoud do just two things:
This is my solution to handle with Cookies and WKWebView in iOS 9 or later.
import WebKit
extension WebView {
enum LayoutMode {
case fillContainer
}
func autoLayout(_ view: UIView?, mode: WebView.LayoutMode = .fillContainer) {
guard let view = view else { return }
self.translatesAutoresizingMaskIntoConstraints = false
view.addSubview(self)
switch mode {
case .fillContainer:
NSLayoutConstraint.activate([
self.topAnchor.constraint(equalTo: view.topAnchor),
self.leadingAnchor.constraint(equalTo: view.leadingAnchor),
self.trailingAnchor.constraint(equalTo: view.trailingAnchor),
self.bottomAnchor.constraint(equalTo: view.bottomAnchor)
])
}
}
}
class WebView : WKWebView {
var request : URLRequest?
func load(url: URL, useSharedCookies: Bool = false) {
if useSharedCookies, let cookies = HTTPCookieStorage.shared.cookies(for: url) {
self.load(url: url, withCookies: cookies)
} else {
self.load(URLRequest(url: url))
}
}
func load(url: URL, withCookies cookies: [HTTPCookie]) {
self.request = URLRequest(url: url)
let headers = HTTPCookie.requestHeaderFields(with: cookies)
self.request?.allHTTPHeaderFields = headers
self.load(request!)
}
}
Just to expand on pcperini's answer. As he mentions you will need to add the following code to your application:didFinishLaunchingWithOptions:
method;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
You Also need to increment then decrement the badge in your application:didReceiveRemoteNotification:
method if you are trying to clear the message from the message centre so that when a user enters you app from pressing a notification the message centre will also clear, ie;
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 1];
[[UIApplication sharedApplication] setApplicationIconBadgeNumber: 0];
[[UIApplication sharedApplication] cancelAllLocalNotifications];
Combining the answers from @Ortomala Lokni and @rogerdpack, another alternative is to have the dependent service monitor when the first one has started / done the thing you're waiting for.
For example, here's how I am making the fail2ban service wait for Docker to open port 443 (so that fail2ban's iptables entries take priority over Docker's):
[Service]
ExecStartPre=/bin/bash -c '(while ! nc -z -v -w1 localhost 443 > /dev/null; do echo "Waiting for port 443 to open..."; sleep 2; done); sleep 2'
Simply replace nc -z -v -w1 localhost 443
with a command that fails (non-zero exit code) while the first service is starting and succeeds once it is up.
For the Cassandra case, the ideal would be a command that only returns 0 when the cluster is available.
Now , Facebook need SSL
-> Important added S, https -> https://graph.facebook.com/userId/?fields=picture&type=large
Works In June / 2014
try by this
if(!Yii::$app->request->getIsPost())
{
Yii::$app->response->redirect(array('user/index','id'=>302));
exit(0);
}
It can be caused by a classpath contamination. Check that you /WEB-INF/lib
doesn't contain something like jsp-api-*.jar
.
POD is the official way to do multi line comments in Perl,
From faq.perl.org[perlfaq7]
The quick-and-dirty way to comment out more than one line of Perl is to surround those lines with Pod directives. You have to put these directives at the beginning of the line and somewhere where Perl expects a new statement (so not in the middle of statements like the # comments). You end the comment with
=cut
, ending the Pod section:
=pod
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=cut
The quick-and-dirty method only works well when you don't plan to leave the commented code in the source. If a Pod parser comes along, your multiline comment is going to show up in the Pod translation. A better way hides it from Pod parsers as well.
The
=begin
directive can mark a section for a particular purpose. If the Pod parser doesn't want to handle it, it just ignores it. Label the comments withcomment
. End the comment using=end
with the same label. You still need the=cut
to go back to Perl code from the Pod comment:
=begin comment
my $object = NotGonnaHappen->new();
ignored_sub();
$wont_be_assigned = 37;
=end comment
=cut
This question is for ruby 1.8 but it still comes on top when googling.
in ruby >= 1.9 you can use
File.write("public/temp.json",tempHash.to_json)
other than what mentioned in other answers, in ruby 1.8 you can also use one liner form
File.open("public/temp.json","w"){ |f| f.write tempHash.to_json }
This is a great solution! With a few additional CSS rules you can format it just like an MS Word outline list with a hanging first line indent:
OL {
counter-reset: item;
}
LI {
display: block;
}
LI:before {
content: counters(item, ".") ".";
counter-increment: item;
padding-right:10px;
margin-left:-20px;
}
You can try this:
int cleft = 1;
intaleft = 1;
private void button2_Click(object sender, EventArgs e)
{
TextBox txt = new TextBox();
this.Controls.Add(txt);
txt.Top = cleft * 40;
txt.Size = new Size(200, 16);
txt.Left = 150;
cleft = cleft + 1;
Label lbl = new Label();
this.Controls.Add(lbl);
lbl.Top = aleft * 40;
lbl.Size = new Size(100, 16);
lbl.ForeColor = Color.Blue;
lbl.Text = "BoxNo/CardNo";
lbl.Left = 70;
aleft = aleft + 1;
return;
}
private void btd_Click(object sender, EventArgs e)
{
//Here you Delete Text Box One By One(int ix for Text Box)
for (int ix = this.Controls.Count - 2; ix >= 0; ix--)
//Here you Delete Lable One By One(int ix for Lable)
for (int x = this.Controls.Count - 2; x >= 0; x--)
{
if (this.Controls[ix] is TextBox)
this.Controls[ix].Dispose();
if (this.Controls[x] is Label)
this.Controls[x].Dispose();
return;
}
}
The reason of why your code throws an UnboundLocalError
is already well explained in other answers.
But it seems to me that you're trying to build something that works like itertools.count()
.
So why don't you try it out, and see if it suits your case:
>>> from itertools import count
>>> counter = count(0)
>>> counter
count(0)
>>> next(counter)
0
>>> counter
count(1)
>>> next(counter)
1
>>> counter
count(2)
Use jquery animate and give it a long duration say 2000
$("#Friends").animate({
top: "-=30px",
}, duration );
The -= means that the animation will be relative to the current top position.
Note that the Friends
element must have position set to relative in the css:
#Friends{position:relative;}
If anyone is looking for an updated solution, Fernando's answer is pretty much perfect. Except that ComponentMetadata
has been deprecated. Using Component
instead worked for me.
The full Custom Decorator CustomDecorator.ts
file looks like this:
import 'zone.js';
import 'reflect-metadata';
import { Component } from '@angular/core';
import { isPresent } from "@angular/platform-browser/src/facade/lang";
export function CustomComponent(annotation: any) {
return function (target: Function) {
var parentTarget = Object.getPrototypeOf(target.prototype).constructor;
var parentAnnotations = Reflect.getMetadata('annotations', parentTarget);
var parentAnnotation = parentAnnotations[0];
Object.keys(parentAnnotation).forEach(key => {
if (isPresent(parentAnnotation[key])) {
// verify is annotation typeof function
if(typeof annotation[key] === 'function'){
annotation[key] = annotation[key].call(this, parentAnnotation[key]);
}else if(
// force override in annotation base
!isPresent(annotation[key])
){
annotation[key] = parentAnnotation[key];
}
}
});
var metadata = new Component(annotation);
Reflect.defineMetadata('annotations', [ metadata ], target);
}
}
Then import it in to your new component sub-component.component.ts
file and use @CustomComponent
instead of @Component
like this:
import { CustomComponent } from './CustomDecorator';
import { AbstractComponent } from 'path/to/file';
...
@CustomComponent({
selector: 'subcomponent'
})
export class SubComponent extends AbstractComponent {
constructor() {
super();
}
// Add new logic here!
}
It's Really Simple Just go to your styles.xml
change the parent Theme to either
Theme.AppCompat.Light.NoActionBar
or Theme.AppCompat.NoActionbar
and you are done.. :)
I ran into this problem when trying to pull a third party package which was apparently including windows.h somewhere in it's mess of headers. Defining _WINSOCKAPI_
at the project level was much easier (not to mention more maintainable) than wading through their soup and fixing the problematic include.
If you are trying to add an image in a button dynamically based on the context of your project, you can use the ? take to reference the source based on an outcome. Here I am using mvvm design to let my Model.Phases[0] value determine whether I want my button to be populated with images of a lightbulb on or off based on the value of the light phase.
Not sure if this helps. I'm using JqueryUI, Blueprint, and CSS. The class definition should allow you to style the button based on whatever you'd like.
<button>
<img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
<img class="@(Model.Phases[0] ? "light-on": "light-off")" src="@(Model.Phases[0] ? "~/Images/LightBulbOn.png" : "~/Images/LightBulbOff.png")"/>
The code provided by this answer is right, but incomplete, I've tested it. There are missing properties in "UserEmail" class:
public UserTest UserTest { get; set; }
public EmailTest EmailTest { get; set; }
I post the code I've tested if someone is interested. Regards
using System.Data.Entity;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Web;
#region example2
public class UserTest
{
public int UserTestID { get; set; }
public string UserTestname { get; set; }
public string Password { get; set; }
public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
public static void DoSomeTest(ApplicationDbContext context)
{
for (int i = 0; i < 5; i++)
{
var user = context.UserTest.Add(new UserTest() { UserTestname = "Test" + i });
var address = context.EmailTest.Add(new EmailTest() { Address = "address@" + i });
}
context.SaveChanges();
foreach (var user in context.UserTest.Include(t => t.UserTestEmailTests))
{
foreach (var address in context.EmailTest)
{
user.UserTestEmailTests.Add(new UserTestEmailTest() { UserTest = user, EmailTest = address, n1 = user.UserTestID, n2 = address.EmailTestID });
}
}
context.SaveChanges();
}
}
public class EmailTest
{
public int EmailTestID { get; set; }
public string Address { get; set; }
public ICollection<UserTestEmailTest> UserTestEmailTests { get; set; }
}
public class UserTestEmailTest
{
public int UserTestID { get; set; }
public UserTest UserTest { get; set; }
public int EmailTestID { get; set; }
public EmailTest EmailTest { get; set; }
public int n1 { get; set; }
public int n2 { get; set; }
//Call this code from ApplicationDbContext.ConfigureMapping
//and add this lines as well:
//public System.Data.Entity.DbSet<yournamespace.UserTest> UserTest { get; set; }
//public System.Data.Entity.DbSet<yournamespace.EmailTest> EmailTest { get; set; }
internal static void RelateFluent(System.Data.Entity.DbModelBuilder builder)
{
// Primary keys
builder.Entity<UserTest>().HasKey(q => q.UserTestID);
builder.Entity<EmailTest>().HasKey(q => q.EmailTestID);
builder.Entity<UserTestEmailTest>().HasKey(q =>
new
{
q.UserTestID,
q.EmailTestID
});
// Relationships
builder.Entity<UserTestEmailTest>()
.HasRequired(t => t.EmailTest)
.WithMany(t => t.UserTestEmailTests)
.HasForeignKey(t => t.EmailTestID);
builder.Entity<UserTestEmailTest>()
.HasRequired(t => t.UserTest)
.WithMany(t => t.UserTestEmailTests)
.HasForeignKey(t => t.UserTestID);
}
}
#endregion
A simple comparison should be
ReactJs
return(
<div>
<p>Hello World</p>
</div>
)
React Native
return(
<View>
<Text>Hello World</Text>
</View>
)
React Native don't have Html Elements like div
, p
, h1
, etc, instead it have components that make sense for mobile.
More details at https://reactnative.dev/docs/components-and-apis
You can have many java versions in your system.
I think you should add the java 8 in yours JREs installed or edit.
Take a look my screen:
If you click in edit (check your java 8 path):
You can use .change
for what you want
$("input[@name='lom']").change(function(){
// Do something interesting here
});
as of jQuery 1.3
you no longer need the '@'. Correct way to select is:
$("input[name='lom']")
FOR /r %%X IN (*) DO (ECHO %%X & DEL %%X)
Yes, that is supported.
Check the documentation provided here for the supported keywords inside method names.
You can just define the method in the repository interface without using the @Query annotation and writing your custom query. In your case it would be as followed:
List<Inventory> findByIdIn(List<Long> ids);
I assume that you have the Inventory entity and the InventoryRepository interface. The code in your case should look like this:
The Entity
@Entity
public class Inventory implements Serializable {
private static final long serialVersionUID = 1L;
private Long id;
// other fields
// getters/setters
}
The Repository
@Repository
@Transactional
public interface InventoryRepository extends PagingAndSortingRepository<Inventory, Long> {
List<Inventory> findByIdIn(List<Long> ids);
}
adding to scotty's answer:
Option 1: Either include this in your JS file:
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.0rc1/angular-route.min.js"></script>
Option 2: or just use the URL to download 'angular-route.min.js' to your local.
and then (whatever option you choose) add this 'ngRoute' as dependency.
explained:
var app = angular.module('myapp', ['ngRoute']);
Cheers!!!
It seems that you have invalid JSON. In that case, that's totally dependent on the data the server sends you which you have not shown. I would suggest running the response through a JSON validator.
Just following on Matt and Dirk. If you want to recreate your existing data frame without changing the global option, you can recreate it with an apply statement:
bob <- data.frame(lapply(bob, as.character), stringsAsFactors=FALSE)
This will convert all variables to class "character", if you want to only convert factors, see Marek's solution below.
As @hadley points out, the following is more concise.
bob[] <- lapply(bob, as.character)
In both cases, lapply
outputs a list; however, owing to the magical properties of R, the use of []
in the second case keeps the data.frame class of the bob
object, thereby eliminating the need to convert back to a data.frame using as.data.frame
with the argument stringsAsFactors = FALSE
.
in case if your table has tbody
let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)
In case you're sure you have only one space between two words, you can use this one
str.replace(/\s+/g, ' ').split(' ')
so you replace one space by two, the split by space
I dont know about XamGrid
but that's what i'll do with a standard wpf DataGrid
:
<DataGrid>
<DataGrid.Columns>
<DataGridTemplateColumn>
<DataGridTemplateColumn.CellTemplate>
<DataTemplate>
<TextBlock Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellTemplate>
<DataGridTemplateColumn.CellEditingTemplate>
<DataTemplate>
<TextBox Text="{Binding DataContext.MyProperty, RelativeSource={RelativeSource AncestorType=MyUserControl}}"/>
</DataTemplate>
</DataGridTemplateColumn.CellEditingTemplate>
</DataGridTemplateColumn>
</DataGrid.Columns>
</DataGrid>
Since the TextBlock
and the TextBox
specified in the cell templates will be part of the visual tree, you can walk up and find whatever control you need.
If you want to run the script file then use below in cmd
sqlcmd -U user -P pass -S servername -d databasename -i "G:\Hiren\Lab_Prodution.sql"
If you declare a pointer to a function like this:
int (*func)(int a, int b);
You can assign a place in memory to that function like this (requires libdl
and dlopen
)
#include <dlfcn.h>
int main(void)
{
void *handle;
char *func_name = "bla_bla_bla";
handle = dlopen("foo.so", RTLD_LAZY);
*(void **)(&func) = dlsym(handle, func_name);
return func(1,2);
}
To load a local symbol using indirection, you can use dlopen
on the calling binary (argv[0]
).
The only requirement for this (other than dlopen()
, libdl
, and dlfcn.h
) is knowing the arguments and type of the function.
For detecting if the form is present, I'm using
if($('form[name="frmSave"]').length > 0) {
//do something
}
This is called the "shape" in NumPy, and can be requested via the .shape
attribute:
>>> a = zeros((2, 5))
>>> a.shape
(2, 5)
If you prefer a function, you could also use numpy.shape(a)
.
I know this is an old question. The way I solved it - after failing by increasing the length or even changing to data type text - was creating an XLSX file and importing. It accurately detected the data type instead of setting all columns as varchar(50)
. Turns out nvarchar(255)
for that column would have done it too.
Try using .pull-left to left align image along with text.
Ex:
<p>At the time all text elements goes here.At the time all text elements goes here. At the time all text elements goes here.<img src="images/hello-missing.jpg" class="pull-left img-responsive" style="padding:15px;" /> to uncovering the truth .</p>
We have been solving the same problem just today, and all you need to do is to increase the runtime version of .NET
4.5.2 didn't work for us with the above problem, while 4.6.1 was OK
If you need to keep the .NET version, then set
ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls | SecurityProtocolType.Tls11 | SecurityProtocolType.Tls12;
There is always a proper syntax for every language. Similarly SQL(Structured Query Language) has also specific syntax for update query which we have to follow if we want to use update query. Otherwise it will not give the expected results.
You can delete a particular single line with its line number by
sed -i '33d' file
This will delete the line on 33 line number and save the updated file.
This is what I got working- set UIButton in xCode's IB to transparent/clear, and no bg image.
UIColor *pinkDarkOp = [UIColor colorWithRed:0.9f green:0.53f blue:0.69f alpha:1.0];
UIColor *pinkLightOp = [UIColor colorWithRed:0.79f green:0.45f blue:0.57f alpha:1.0];
CAGradientLayer *gradient = [CAGradientLayer layer];
gradient.frame = [[shareWordButton layer] bounds];
gradient.cornerRadius = 7;
gradient.colors = [NSArray arrayWithObjects:
(id)pinkDarkOp.CGColor,
(id)pinkLightOp.CGColor,
nil];
gradient.locations = [NSArray arrayWithObjects:
[NSNumber numberWithFloat:0.0f],
[NSNumber numberWithFloat:0.7],
nil];
[[recordButton layer] insertSublayer:gradient atIndex:0];
Add this in composer.json
. Then dusk has to be installed explicitly in your project:
"extra": {
"laravel": {
"dont-discover": [
"laravel/dusk"
]
}
},
You need a ResourceLink in your META-INF/context.xml
file to make the global resource available to the web application.
<ResourceLink name="jdbc/mydb"
global="jdbc/mydb"
type="javax.sql.DataSource" />
In ipython
, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):
print paramdata.head(100).to_string()
with 2008 Server 2008 and 2008 R2
Add-PSSnapin -Name SqlServerCmdletSnapin100, SqlServerProviderSnapin100
with 2012 and 2014
Push-Location
Import-Module -Name SQLPS -DisableNameChecking
Pop-Location
If you need the URL till hostname and not the path use Apache's Common Lib StringUtil
, and from URL extract the substring till third indexOf /
.
public static String getURL(HttpServletRequest request){
String fullURL = request.getRequestURL().toString();
return fullURL.substring(0,StringUtils.ordinalIndexOf(fullURL, "/", 3));
}
Example: If fullURL is https://example.com/path/after/url/
then
Output will be https://example.com
The maven dependency plugin can potentially solve your problem.
If you have a pom
with all your project dependencies specified, all you would need to do is run
mvn dependency:copy-dependencies
and you will find the target/dependencies
folder filled with all the dependencies, including transitive.
Adding Gustavo's answer from below: To download the dependency sources, you can use
mvn dependency:copy-dependencies -Dclassifier=sources
If you just want to update the property on all elements then
someList.All(x => { x.SomeProp = "foo"; return true; })
To see your log in SQL Developer
then press:
CTRL+SHIFT + L (or CTRL + CMD + L on macOS)
or
View -> Log
or by using mysql query
show errors;
Two different characters for different Operating Systems. Also this plays a role in data transmitted over TCP/IP
which requires the use of \r\n
.
\n
Unix
\r
Mac
\r\n
Windows and DOS.
Try using Delete method:
DataRow[] drr = dt.Select("Student=' " + id + " ' ");
for (int i = 0; i < drr.Length; i++)
drr[i].Delete();
dt.AcceptChanges();
SOA is a buzzword that was invented by technology vendors to help sell their Enterprise Service Bus related technologies. The idea is that you make your little island applications in the enterprise (eg: accounting system, stock control system, etc) all expose services, so that they can be orchestrated flexibly into 'applications', or rather become parts of aggregate enterprise scoped business logic.
Basically a load of old bollocks that nearly never works, because it misses the point that the reasons why technology is the way it is in an organisation is down to culture, evolution, history of the firm, and the lock in is so high that any attempt to restructure the technology is bound to fail.
It's all about display: block
:)
Updated:
Ok so you have the table, tr and td tags:
<table>
<tr>
<td>
<!-- your image goes here -->
</td>
</tr>
</table>
Lets say your table
or td
(whatever define your width) has property width: 360px;
. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%;
which should fully fill out the td
cell you will face the problem.
The problem is that your table cell (td
) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).
How to solve this in a simpliest way?
You are working with the tables, right? You just need to add the display property to your image so that it has the following:
img {
width: 100%;
display: block;
}
Next matches all greater or equal to 11100
:
^([1-9][1-9][1-9]\d{2}\d*|[1-9][2-9]\d{3}\d*|[2-9]\d{4}\d*|\d{6}\d*)$
^([5-9]\d{1}\d*|\d{3}\d*)$
See pattern and modify to any number. Also it would be great to find some recursive forward/backward operators for large numbers.
Thanks to David as his solution helped me come up with my solution for uploading multi-part files from my Heroku hosted site to S3 bucket. I did it using formidable to handle incoming form and fs to get the file content. Hopefully, it may help you.
api.service.ts
public upload(files): Observable<any> {
const formData: FormData = new FormData();
files.forEach(file => {
// create a new multipart-form for every file
formData.append('file', file, file.name);
});
return this.http.post(uploadUrl, formData).pipe(
map(this.extractData),
catchError(this.handleError));
}
}
server.js
app.post('/api/upload', upload);
app.use('/api/upload', router);
upload.js
const IncomingForm = require('formidable').IncomingForm;
const fs = require('fs');
const AWS = require('aws-sdk');
module.exports = function upload(req, res) {
var form = new IncomingForm();
const bucket = new AWS.S3(
{
signatureVersion: 'v4',
accessKeyId: process.env.AWS_ACCESS_KEY_ID,
secretAccessKey: process.env.AWS_SECRET_ACCESS_KEY,
region: 'us-east-1'
}
);
form.on('file', (field, file) => {
const fileContent = fs.readFileSync(file.path);
const s3Params = {
Bucket: process.env.AWS_S3_BUCKET,
Key: 'folder/' + file.name,
Expires: 60,
Body: fileContent,
ACL: 'public-read'
};
bucket.upload(s3Params, function(err, data) {
if (err) {
throw err;
}
console.log('File uploaded to: ' + data.Location);
fs.unlink(file.path, function (err) {
if (err) {
console.error(err);
}
console.log('Temp File Delete');
});
});
});
// The second callback is called when the form is completely parsed.
// In this case, we want to send back a success status code.
form.on('end', () => {
res.status(200).json('upload ok');
});
form.parse(req);
}
upload-image.component.ts
import { Component, OnInit, ViewChild, Output, EventEmitter, Input } from '@angular/core';
import { ApiService } from '../api.service';
import { MatSnackBar } from '@angular/material/snack-bar';
@Component({
selector: 'app-upload-image',
templateUrl: './upload-image.component.html',
styleUrls: ['./upload-image.component.css']
})
export class UploadImageComponent implements OnInit {
public files: Set<File> = new Set();
@ViewChild('file', { static: false }) file;
public uploadedFiles: Array<string> = new Array<string>();
public uploadedFileNames: Array<string> = new Array<string>();
@Output() filesOutput = new EventEmitter<Array<string>>();
@Input() CurrentImage: string;
@Input() IsPublic: boolean;
@Output() valueUpdate = new EventEmitter();
strUploadedFiles:string = '';
filesUploaded: boolean = false;
constructor(private api: ApiService, public snackBar: MatSnackBar,) { }
ngOnInit() {
}
updateValue(val) {
this.valueUpdate.emit(val);
}
reset()
{
this.files = new Set();
this.uploadedFiles = new Array<string>();
this.uploadedFileNames = new Array<string>();
this.filesUploaded = false;
}
upload() {
this.api.upload(this.files).subscribe(res => {
this.filesOutput.emit(this.uploadedFiles);
if (res == 'upload ok')
{
this.reset();
}
}, err => {
console.log(err);
});
}
onFilesAdded() {
var txt = '';
const files: { [key: string]: File } = this.file.nativeElement.files;
for (let key in files) {
if (!isNaN(parseInt(key))) {
var currentFile = files[key];
var sFileExtension = currentFile.name.split('.')[currentFile.name.split('.').length - 1].toLowerCase();
var iFileSize = currentFile.size;
if (!(sFileExtension === "jpg"
|| sFileExtension === "png")
|| iFileSize > 671329) {
txt = "File type : " + sFileExtension + "\n\n";
txt += "Size: " + iFileSize + "\n\n";
txt += "Please make sure your file is in jpg or png format and less than 655 KB.\n\n";
alert(txt);
return false;
}
this.files.add(files[key]);
this.uploadedFiles.push('https://gourmet-philatelist-assets.s3.amazonaws.com/folder/' + files[key].name);
this.uploadedFileNames.push(files[key].name);
if (this.IsPublic && this.uploadedFileNames.length == 1)
{
this.filesUploaded = true;
this.updateValue(files[key].name);
break;
}
else if (!this.IsPublic && this.uploadedFileNames.length == 3)
{
this.strUploadedFiles += files[key].name;
this.updateValue(this.strUploadedFiles);
this.filesUploaded = true;
break;
}
else
{
this.strUploadedFiles += files[key].name + ",";
this.updateValue(this.strUploadedFiles);
}
}
}
}
addFiles() {
this.file.nativeElement.click();
}
openSnackBar(message: string, action: string) {
this.snackBar.open(message, action, {
duration: 2000,
verticalPosition: 'top'
});
}
}
upload-image.component.html
<input type="file" #file style="display: none" (change)="onFilesAdded()" multiple />
<button mat-raised-button color="primary"
[disabled]="filesUploaded" (click)="$event.preventDefault(); addFiles()">
Add Files
</button>
<button class="btn btn-success" [disabled]="uploadedFileNames.length == 0" (click)="$event.preventDefault(); upload()">
Upload
</button>
When cloning, by default it will not clone the events. The added rows do not have an event handler attached to them. If you call clone(true)
then it should handle them as well.
I had a similar issue except my problem was silly - I had 2 instances of the built-in web server running under 2 different ports AND I had my project -> properties -> web -> "Start URL" pointing to a fixed port but the web app was not actually running under that port. So my browser was being redirected to the "Start URL" which referred to 1539 but the code/debug instance was running under port 50803.
I changed the builtin web server to run under a fixed port and adjusted my "Start URL" to use that port as well. project -> properties -> web -> "Servers" section -> "Use Visual Studio Development Server" -> specific port
From the term "automatic login" I suppose security (password protection) is not of key importance here.
The guidelines for solution could be to use a JavaScript bookmark (idea borrowed form a nice game published on M&M's DK site).
The idea is to create a javascript file and store it locally. It should do the login data entering depending on current site address. Just an example using jQuery:
// dont forget to include jQuery code
// preferably with .noConflict() in order not to break the site scripts
if (window.location.indexOf("mail.google.com") > -1) {
// Lets login to Gmail
jQuery("#Email").val("[email protected]");
jQuery("#Passwd").val("superSecretPassowrd");
jQuery("#gaia_loginform").submit();
}
Now save this as say login.js
Then create a bookmark (in any browser) with this (as an) url:
javascript:document.write("<script type='text/javascript' src='file:///path/to/login.js'></script>");
Now when you go to Gmail and click this bookmark you will get automatically logged in by your script.
Multiply the code blocks in your script, to add more sites in the similar manner. You could even combine it with window.open(...)
functionality to open more sites, but that may get the script inclusion more complicated.
Note: This only illustrates an idea and needs lots of further work, it's not a complete solution.
You probably have an old version of wget. I suggest installing wget using Chocolatey, the package manager for Windows. This should give you a more recent version (if not the latest).
Run this command after having installed Chocolatey (as Administrator):
choco install wget
Comparing the two Databases in SQL Database. Try this Query it may help.
SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS
system_data_type FROM [***Database Name 1***].sys.[tables] AS T
INNER JOIN [***Database Name 1***].sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN [***Database Name 1***].sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]
EXCEPT SELECT T.[name] AS [table_name], AC.[name] AS [column_name], TY.[name] AS system_data_type FROM ***Database Name 2***.sys.[tables] AS T
INNER JOIN ***Database Name 2***.sys.[all_columns] AC ON T.[object_id] = AC.[object_id]
INNER JOIN ***Database Name 2***.sys.[types] TY ON AC.[system_type_id] = TY.[system_type_id]
This should now work with Internet Explorer, Firefox v12+ and Chrome 28+
<img src="'../images/foo.gif'"
alt="line 1
line 2" title="line 1
line 2">
Try a JavaScript tooltip library for a better result, something like OverLib.
Change the and
s to or
s.
Assuming that "a" and "b" are bean properties
rendered="#{bean.a==12 and (bean.b==13 or bean.b==15)}"
You may look at JSF EL operators
Java 9 offers a Matcher.replaceAll()
that accepts a replacement function:
resultString = regexMatcher.replaceAll(
m -> String.valueOf(Integer.parseInt(m.group()) * 3));
The easiest way I found was to copy your file contents into you browser console and hit enter. The disadvantage of this approach is that you can only debug with console.log statements.
Assuming thant the content of mandrill_events
is an object (not a string), you can also use shift()
function:
var req = { mandrill_events: [{"event":"inbound","ts":1426249238}] };
var event-property = req.mandrill_events.shift().event;
A better solution would be to make an Ajax call inside the iframe to the page that would get/set cookies...
Either you experienced database connection issue or you missed any of the hibernate configurations to connect to database such as database DIALECT.
Happens if your database server was disconnected due to network related issue.
If you're using spring boot along with hibernate connected to Oracle Db, use
hibernate.dialect=org.hibernate.dialect.HSQLDialect
hibernate.show_sql=true
hibernate.hbm2ddl.auto=update
hibernate.generate_statistics=true
entitymanager.packagesToScan: com
If you are using requests
module, an alternative option is to write an auth class, as discussed in "New Forms of Authentication":
import requests
class BearerAuth(requests.auth.AuthBase):
def __init__(self, token):
self.token = token
def __call__(self, r):
r.headers["authorization"] = "Bearer " + self.token
return r
and then can you send requests like this
response = requests.get('https://www.example.com/', auth=BearerAuth('3pVzwec1Gs1m'))
which allows you to use the same auth
argument just like basic auth, and may help you in certain situations.
you can try this:"Filename.txt" file will be created automatically in the bin->debug folder everytime you run this code or you can specify path of the file like: @"C:/...". you can check ëxistance of "Hello" by going to the bin -->debug folder
P.S dont forget to add Console.Readline() after this code snippet else console will not appear.
TextWriter tw = new StreamWriter("filename.txt");
String text = "Hello";
tw.WriteLine(text);
tw.Close();
TextReader tr = new StreamReader("filename.txt");
Console.WriteLine(tr.ReadLine());
tr.Close();
Well the most used pattern for reusable logic I have come across is either writing a hook or creating a utils file. It depends on what you want to accomplish.
hooks/useForm.js
Like if you want to validate form data then I would create a custom hook named useForm.js and provide it form data and in return it would return me an object containing two things:
Object: {
value,
error,
}
You can definitely return more things from it as you progress.
utils/URL.js
Another example would be like you want to extract some information from a URL then I would create a utils file for it containing a function and import it where needed:
export function getURLParam(p) {
...
}
Unfortunately, not really implemented in ES6. You have this feature with OrderedMap.sort() from ImmutableJS or _.sortBy() from Lodash.
Try these commands to remove all users' usernames and emails.
git config --global --unset-all user.name
git config --global --unset-all user.email
def is_prime(x):
if x < 2:
return False
elif x == 2:
return True
for n in range(2, x):
if x % n ==0:
return False
return True
The feedback you get on the interactive interpreter uses repr
too. When you type in an expression (let it be expr
), the interpreter basically does result = expr; if result is not None: print repr(result)
. So the second line in your example is formatting the string foo
into the representation you want ('foo'
). And then the interpreter creates the repr
esentation of that, leaving you with double quotes.
Why when I combine %r with double-quote and single quote escapes and print them out, it prints it the way I'd write it in my .py file but not the way I'd like to see it?
I'm not sure what you're asking here. The text single ' and double " quotes
, when run through repr
, includes escapes for one kind of quote. Of course it does, otherwise it wouldn't be a valid string literal by Python rules. That's precisely what you asked for by calling repr
.
Also note that the eval(repr(x)) == x
analogy isn't meant literal. It's an approximation and holds true for most (all?) built-in types, but the main thing is that you get a fairly good idea of the type and logical "value" from looking the the repr
output.
$("#div_element").load('script.php');
demo: http://sandbox.phpcode.eu/g/2ecbe/3
whole code:
<div id="submit">ajax</div>
<div id="div_element"></div>
<script>
$('#submit').click(function(event){
$("#div_element").load('script.php?html=some_arguments');
});
</script>
It should be,
*/15 * * * * your_command_or_whatever
This problem is solved easily with moment.js, like this example:
var difference = mostDate.diff(minorDate, "minutes");
The second parameter can be changed for another parameters, see the moment.js documentation.
e.g.: "days", "hours", "minutes", etc.
The CDN for moment.js is available here:
https://cdnjs.com/libraries/moment.js
Thanks.
EDIT:
mostDate and minorDate should be a moment type.
EDIT 2:
For those who are reading my answer in 2020+, momentjs is now a legacy project.
If you are still looking for a well-known library to do this job, I would recommend date-fns.
// How many minutes are between 2 July 2014 12:07:59 and 2 July 2014 12:20:00?
var result = differenceInMinutes(
new Date(2014, 6, 2, 12, 20, 0),
new Date(2014, 6, 2, 12, 7, 59)
)
//=> 12
the behaviour of fixed elements (and absolute elements) as defined in CSS Spec:
They behave as they are detached from document, and placed in the nearest fixed/absolute positioned parent. (not a word by word quote)
This makes zindex calculation a bit complicated, I solved my problem (the same situation) by dynamically creating a container in body element and moving all such elements (which are class-ed as "my-fixed-ones" inside that body-level element)
There is a small error in the code of @DyingCactus. Here is the correct solution to add an UILabel to an UIButton to align the button text to better control the button 'title':
NSString *myLabelText = @"Hello World";
UIButton *myButton = [UIButton buttonWithType:UIButtonTypeCustom];
// position in the parent view and set the size of the button
myButton.frame = CGRectMake(myX, myY, myWidth, myHeight);
CGRect myButtonRect = myButton.bounds;
UILabel *myLabel = [[UILabel alloc] initWithFrame: myButtonRect];
myLabel.text = myLabelText;
myLabel.backgroundColor = [UIColor clearColor];
myLabel.textColor = [UIColor redColor];
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];
myLabel.textAlignment = UITextAlignmentLeft;
[myButton addSubview:myLabel];
[myLabel release];
Hope this helps....
Al
It's possible to use a udev rule to let the system decide on the scheduler based on some characteristics of the hw.
An example udev rule for SSDs and other non-rotational drives might look like
# set noop scheduler for non-rotating disks
ACTION=="add|change", KERNEL=="sd[a-z]", ATTR{queue/rotational}=="0", ATTR{queue/scheduler}="noop"
inside a new udev rules file (e.g., /etc/udev/rules.d/60-ssd-scheduler.rules
). This answer is based on the debian wiki
To check whether ssd disks would use the rule, it's possible to check for the trigger attribute in advance:
for f in /sys/block/sd?/queue/rotational; do printf "$f "; cat $f; done
As mentioned by alko989, there is a major security flaw with _blank
(details here).
To avoid it from pure JS code:
const openInNewTab = (url) => {
const newWindow = window.open(url, '_blank', 'noopener,noreferrer')
if (newWindow) newWindow.opener = null
}
Then add to your onClick
onClick={() => openInNewTab('https://stackoverflow.com')}
The third param can also take these optional values, based on your needs.
Well, it would be more accurate to rely on the feature and not a variable value. Especially as there are 2 possible variables for Windows.
function getUserHome() {
return process.env.HOME || process.env.USERPROFILE;
}
EDIT: as mentioned in a more recent answer, https://stackoverflow.com/a/32556337/103396 is the right way to go (require('os').homedir()
).
You can make symbolic link to you pip3:
sudo ln -s $(which pip3) /usr/bin/pip3
It helps me in RHEL 7.6
Here's the answer I found:
Just to make the definition complete, in the Cartesian coordinate system:
The conversion is:
x = R * cos(lat) * cos(lon)
y = R * cos(lat) * sin(lon)
z = R *sin(lat)
Where R is the approximate radius of earth (e.g. 6371 km).
If your trigonometric functions expect radians (which they probably do), you will need to convert your longitude and latitude to radians first. You obviously need a decimal representation, not degrees\minutes\seconds (see e.g. here about conversion).
The formula for back conversion:
lat = asin(z / R)
lon = atan2(y, x)
asin is of course arc sine. read about atan2 in wikipedia. Don’t forget to convert back from radians to degrees.
This page gives c# code for this (note that it is very different from the formulas), and also some explanation and nice diagram of why this is correct,
This may be old, but I may as well write what I've learned down. So anyway I did it this way.
---------->
Before you start, make sure the Apache rewrites module is enabled and then follow the steps below.
1) Log-in to your Magento administration area then go to System > Configuration > Web.
2) Navigate to the Unsecure and Secure tabs. Make sure the Unsecured and Secure - Base Url options have your domain name within it, and do not leave the forward slash off at the end of the URL. Example: http://www.yourdomain.co.uk/
3) While still on the Web page, navigate to Search Engine Optimisation tab and select YES underneath the Use Web Server Rewrites option.
4) Navigate to the Secure tab again (if not already on it) and select Yes on the Use Secure URLs in Front-End option.
5) Now go to the root of your Magento website folder and use this code for your .htaccess:
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
Save the .htaccess and replace the original file. (PLEASE MAKE SURE TO BACKUP YOUR ORIGINAL .htaccess FILE BEFORE MESSING WITH IT!!!)
6) Now go to System > Cache Management and select all fields and make sure the Actions dropdown is set on Refresh, then submit. (This will of-course refresh the Cache.)
---------->
If this did not work please follow these extra steps.
7) Go to System > Configuration > web again. This time look for the Current Configuration Scope and select your website from the dropdown menu. (This is of course, it is set to Default Config)
8) Make sure the Unsecure and Secure fields contain the same domain as the previous Default Config file.
9) Navigate to the Search Engines Optimisation tab and select Yes underneath the Use Web Server Rewrites section.
10) Once the URLs are the same, and the rewrite is enabled save that page, then go back and make sure they are all checked as default, then save again if needed.
11) Repeat step 6.
Now your index.php problem should be fixed and all should be well!!!
I hope this helps, and good luck.
If we have fewer number of reports which are less complex and consumed by asp.net web pages. It's better to go with rdlc,reason is we can avoid maintaing reports on RS instance. but we have to fetch the data from DB manually and bind it to rdlc.
Cons:designing rdlc in visual studio is little difficult compared to SSrs designer.
Pro:Maintenance is easy. while exporting the report from we page,observed that performance gain compared to server side reports.
Assuming the application you are attempting to run in the background is CLI based, you can try calling the scheduled jobs using Hidden Start
Also see: http://www.howtogeek.com/howto/windows/hide-flashing-command-line-and-batch-file-windows-on-startup/
Both IP and DNS can be specified with the keytool additional argument -ext SAN=dns:abc.com,ip:1.1.1.1
Example:
keytool -genkeypair -keystore <keystore> -dname "CN=test, OU=Unknown, O=Unknown, L=Unknown, ST=Unknown, C=Unknown" -keypass <keypwd> -storepass <storepass> -keyalg RSA -alias unknown -ext SAN=dns:test.abc.com,ip:1.1.1.1
There is a way to do this without installing putty on your Mac. You can easily convert your existing PPK file to a PEM file using PuTTYgen on Windows.
Launch PuTTYgen and then load the existing private key file using the Load button. From the "Conversions" menu select "Export OpenSSH key" and save the private key file with the .pem file extension.
Copy the PEM file to your Mac and set it to be read-only by your user:
chmod 400 <private-key-filename>.pem
Then you should be able to use ssh to connect to your remote server
ssh -i <private-key-filename>.pem username@hostname
Another interesting way to quickly repeat n character is to use idea from quick exponentiation algorithm:
var repeatString = function(string, n) {
var result = '', i;
for (i = 1; i <= n; i *= 2) {
if ((n & i) === i) {
result += string;
}
string = string + string;
}
return result;
};
No expensive forks, no pipes, no bashisms:
$ set -- $STRING
$ eval echo \${$N}
three
But beware of globbing.
With C++11 you can use the constexpr
keyword and write in your header:
private:
static constexpr const char* SOMETHING = "something";
Notes:
constexpr
makes SOMETHING
a constant pointer so you cannot write
SOMETHING = "something different";
later on.
Depending on your compiler, you might also need to write an explicit definition in the .cpp file:
constexpr const char* MyClass::SOMETHING;
Try with
f.mkdirs()
then createNewFile()
I wanted to add a method which I think was simplest of all.
Simply right click the pfx file, click "Install" follow the wizard, and add it to a store (I added to the Personal store).
In start menu type certmgr.msc and go to CertManager program.
Find your pfx certificate (tabs at top are the various stores), click the export button and follow the wizard (there is an option to export as .CER)
Essentially it does the same thing as Andrew's answer, but it avoids using Windows Management Console (goes straight to the import/export).
Without the question if it is proper or not, you can add PCH file manually:
Add new PCH file to the project: New file > Other > PCH file.
At the Target's Build Settings option, set the value of Prefix Header to your PCH file name, with the project name as prefix (i.e. for project named TestProject
and PCH file named MyPrefixHeaderFile
, add the value TestProject/MyPrefixHeaderFile.pch
to the plist).
TIP: You can use things like $(SRCROOT)
or $(PROJECT_DIR)
to get to the path of where you put the .pch
in the project.
At the Target's Build Settings option, set the value of Precompile Prefix Header to YES
.
well sometimes this is also useful.
import java.util.Date;
public class DisplayDate {
public static void main(String args[]) {
// Instantiate an object
Date date = new Date();
// display time and date
System.out.println(date.toString());}}
sample output: Mon Jul 03 19:07:15 IST 2017
Just do delete
. This is from the SQLite documentation:
"When the WHERE is omitted from a DELETE statement and the table being deleted has no triggers, SQLite uses an optimization to erase the entire table content without having to visit each row of the table individually. This "truncate" optimization makes the delete run much faster. Prior to SQLite version 3.6.5, the truncate optimization also meant that the sqlite3_changes() and sqlite3_total_changes() interfaces and the count_changes pragma will not actually return the number of deleted rows. That problem has been fixed as of version 3.6.5."
The problem here is that you cannot define the background color using a color selector, you need a drawable selector. So, the necessary changes would look like this:
<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item
android:state_pressed="true"
android:drawable="@drawable/selected_state" />
</selector>
You would also need to move that resource to the drawable
directory where it would make more sense since it's not a color selector per se.
Then you would have to create the res/drawable/selected_state.xml
file like this:
<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="rectangle">
<solid android:color="@color/semitransparent_white" />
</shape>
and finally, you would use it like this:
android:background="@drawable/selector"
Note: the reason why the OP was getting an image resource drawn is probably because he tried to just reference his resource that was still in the color directory but using @drawable
so he ended up with an ID collision, selecting the wrong resource.
Hope this can still help someone even if the OP probably has, I hope, solved his problem by now.
function getCityState($zip, $blnUSA = true) {
$url = "http://maps.googleapis.com/maps/api/geocode/json?address=" . $zip . "&sensor=true";
$address_info = file_get_contents($url);
$json = json_decode($address_info);
$city = "";
$state = "";
$country = "";
if (count($json->results) > 0) {
//break up the components
$arrComponents = $json->results[0]->address_components;
foreach($arrComponents as $index=>$component) {
$type = $component->types[0];
if ($city == "" && ($type == "sublocality_level_1" || $type == "locality") ) {
$city = trim($component->short_name);
}
if ($state == "" && $type=="administrative_area_level_1") {
$state = trim($component->short_name);
}
if ($country == "" && $type=="country") {
$country = trim($component->short_name);
if ($blnUSA && $country!="US") {
$city = "";
$state = "";
break;
}
}
if ($city != "" && $state != "" && $country != "") {
//we're done
break;
}
}
}
$arrReturn = array("city"=>$city, "state"=>$state, "country"=>$country);
die(json_encode($arrReturn));
}
Iterating over dictionaries using 'for' loops
d = {'x': 1, 'y': 2, 'z': 3} for key in d: ...
How does Python recognize that it needs only to read the key from the dictionary? Is key a special word in Python? Or is it simply a variable?
It's not just for
loops. The important word here is "iterating".
A dictionary is a mapping of keys to values:
d = {'x': 1, 'y': 2, 'z': 3}
Any time we iterate over it, we iterate over the keys. The variable name key
is only intended to be descriptive - and it is quite apt for the purpose.
This happens in a list comprehension:
>>> [k for k in d]
['x', 'y', 'z']
It happens when we pass the dictionary to list (or any other collection type object):
>>> list(d)
['x', 'y', 'z']
The way Python iterates is, in a context where it needs to, it calls the __iter__
method of the object (in this case the dictionary) which returns an iterator (in this case, a keyiterator object):
>>> d.__iter__()
<dict_keyiterator object at 0x7fb1747bee08>
We shouldn't use these special methods ourselves, instead, use the respective builtin function to call it, iter
:
>>> key_iterator = iter(d)
>>> key_iterator
<dict_keyiterator object at 0x7fb172fa9188>
Iterators have a __next__
method - but we call it with the builtin function, next
:
>>> next(key_iterator)
'x'
>>> next(key_iterator)
'y'
>>> next(key_iterator)
'z'
>>> next(key_iterator)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
StopIteration
When an iterator is exhausted, it raises StopIteration
. This is how Python knows to exit a for
loop, or a list comprehension, or a generator expression, or any other iterative context. Once an iterator raises StopIteration
it will always raise it - if you want to iterate again, you need a new one.
>>> list(key_iterator)
[]
>>> new_key_iterator = iter(d)
>>> list(new_key_iterator)
['x', 'y', 'z']
We've seen dicts iterating in many contexts. What we've seen is that any time we iterate over a dict, we get the keys. Back to the original example:
d = {'x': 1, 'y': 2, 'z': 3} for key in d:
If we change the variable name, we still get the keys. Let's try it:
>>> for each_key in d:
... print(each_key, '=>', d[each_key])
...
x => 1
y => 2
z => 3
If we want to iterate over the values, we need to use the .values
method of dicts, or for both together, .items
:
>>> list(d.values())
[1, 2, 3]
>>> list(d.items())
[('x', 1), ('y', 2), ('z', 3)]
In the example given, it would be more efficient to iterate over the items like this:
for a_key, corresponding_value in d.items():
print(a_key, corresponding_value)
But for academic purposes, the question's example is just fine.
To do this, I think you should probably have an additional "ORDER" table which defines the mapping of IDs to order (effectively doing what your response to your own question said), which you can then use as an additional column on your select which you can then sort on.
In that way, you explicitly describe the ordering you desire in the database, where it should be.
:~$ tmux new-session "tmux source-file ~/session1"
neww
split-window -v 'ipython'
split-window -h
new-window 'mutt'
:~$ echo `alias tmux_s1='tmux new-session "tmux source-file ~/session1"'` >>~/.bashrc
:~$ . ~/.bashrc
:~$ tmux_s1
And, how about this ...
string[] sizes = new string[] { "105", "101", "102", "103", "90" };
var size = from x in sizes
orderby x.Length, x
select x;
foreach (var p in size)
{
Console.WriteLine(p);
}
Like this:
import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);
Or adding from an Array/ or multiple literals; wrap to a list, first.
Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b)); // from an array variable
b.addAll( Arrays.asList( 8, 9, 10)); // from literals
To get the intersection:
// copies all from A; then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print; r.toString() implied.
System.out.println("A intersect B="+r);
Hope this answer helps. Vote for it!
If you are using python 2.7 or later, the easiest way to do this is to use the subprocess.check_output()
command. Here is an example:
output = subprocess.check_output('ls')
To also redirect stderr you can use the following:
output = subprocess.check_output('ls', stderr=subprocess.STDOUT)
In the case that you want to pass parameters to the command, you can either use a list or use invoke a shell and use a single string.
output = subprocess.check_output(['ls', '-a'])
output = subprocess.check_output('ls -a', shell=True)
You may also want to have a look at httplib2, with examples. I find using httplib2 is more concise than using the built-in HTTP modules.
SQL Server Profiler 2014 lists the content of table value parameter. Might work in previous versions too. Enable SP:Starting or RPC:Completed event in Stored Procedures group and TextData column and when you click on entry in log you'll have the insert statements for table variable. You can then copy the text and run in Management Studio.
Sample output:
declare @p1 dbo.TableType
insert into @p1 values(N'A',N'B')
insert into @p1 values(N'C',N'D')
exec uspWhatever @PARAM=@p1
function random_color(){
return sprintf('#%06X', mt_rand(0, 0xFFFFFF));
}
Using JQuery would take care of that browser inconsistency. With the jquery library included in your project simply write:
$('#yourDivName').html('yourtHTML');
You may also consider using:
$('#yourDivName').append('yourtHTML');
This will add your gallery as the last item in the selected div. Or:
$('#yourDivName').prepend('yourtHTML');
This will add it as the first item in the selected div.
See the JQuery docs for these functions:
To sum things up, there are 4 solutions to this:
Solution 1: turn off ProxyCreation for the DBContext and restore it in the end.
private DBEntities db = new DBEntities();//dbcontext
public ActionResult Index()
{
bool proxyCreation = db.Configuration.ProxyCreationEnabled;
try
{
//set ProxyCreation to false
db.Configuration.ProxyCreationEnabled = false;
var data = db.Products.ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
finally
{
//restore ProxyCreation to its original state
db.Configuration.ProxyCreationEnabled = proxyCreation;
}
}
Solution 2: Using JsonConvert by Setting ReferenceLoopHandling to ignore on the serializer settings.
//using using Newtonsoft.Json;
private DBEntities db = new DBEntities();//dbcontext
public ActionResult Index()
{
try
{
var data = db.Products.ToList();
JsonSerializerSettings jss = new JsonSerializerSettings { ReferenceLoopHandling = ReferenceLoopHandling.Ignore };
var result = JsonConvert.SerializeObject(data, Formatting.Indented, jss);
return Json(result, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
Following two solutions are the same, but using a model is better because it's strong typed.
Solution 3: return a Model which includes the needed properties only.
private DBEntities db = new DBEntities();//dbcontext
public class ProductModel
{
public int Product_ID { get; set;}
public string Product_Name { get; set;}
public double Product_Price { get; set;}
}
public ActionResult Index()
{
try
{
var data = db.Products.Select(p => new ProductModel
{
Product_ID = p.Product_ID,
Product_Name = p.Product_Name,
Product_Price = p.Product_Price
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
Solution 4: return a new dynamic object which includes the needed properties only.
private DBEntities db = new DBEntities();//dbcontext
public ActionResult Index()
{
try
{
var data = db.Products.Select(p => new
{
Product_ID = p.Product_ID,
Product_Name = p.Product_Name,
Product_Price = p.Product_Price
}).ToList();
return Json(data, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(ex.Message);
}
}
class Grandpa
{
public function __construct()
{
echo"Hello Kiddo";
}
}
class Papa extends Grandpa
{
public function __construct()
{
}
public function CallGranddad()
{
parent::__construct();
}
}
class Kiddo extends Papa
{
public function __construct()
{
}
public function needSomethingFromGrandDad
{
parent::CallGranddad();
}
}
#Server Connection to MySQL:
import MySQLdb
conn = MySQLdb.connect(host= "localhost",
user="root",
passwd="newpassword",
db="engy1")
x = conn.cursor()
try:
x.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
conn.commit()
except:
conn.rollback()
conn.close()
edit working for me:
>>> import MySQLdb
>>> #connect to db
... db = MySQLdb.connect("localhost","root","password","testdb" )
>>>
>>> #setup cursor
... cursor = db.cursor()
>>>
>>> #create anooog1 table
... cursor.execute("DROP TABLE IF EXISTS anooog1")
__main__:2: Warning: Unknown table 'anooog1'
0L
>>>
>>> sql = """CREATE TABLE anooog1 (
... COL1 INT,
... COL2 INT )"""
>>> cursor.execute(sql)
0L
>>>
>>> #insert to table
... try:
... cursor.execute("""INSERT INTO anooog1 VALUES (%s,%s)""",(188,90))
... db.commit()
... except:
... db.rollback()
...
1L
>>> #show table
... cursor.execute("""SELECT * FROM anooog1;""")
1L
>>> print cursor.fetchall()
((188L, 90L),)
>>>
>>> db.close()
table in mysql;
mysql> use testdb;
Reading table information for completion of table and column names
You can turn off this feature to get a quicker startup with -A
Database changed
mysql> SELECT * FROM anooog1;
+------+------+
| COL1 | COL2 |
+------+------+
| 188 | 90 |
+------+------+
1 row in set (0.00 sec)
mysql>
You can use the function below which replaces the first occurrence of the word from right.
def replace_from_right(text: str, original_text: str, new_text: str) -> str:
""" Replace first occurrence of original_text by new_text. """
return text[::-1].replace(original_text[::-1], new_text[::-1], 1)[::-1]
Saw this thread but I wanted to search for IDs that did not match my search. Code to do that:
found = $filter('filter')($scope.fish, {id: '!fish_id'}, false);
Here is a more complete answer with regard to InnoDB. It is a bit of a lengthy process, but can be worth the effort.
Keep in mind that /var/lib/mysql/ibdata1
is the busiest file in the InnoDB infrastructure. It normally houses six types of information:
Pictorial Representation of ibdata1
Many people create multiple ibdata
files hoping for better disk-space management and performance, however that belief is mistaken.
OPTIMIZE TABLE
?Unfortunately, running OPTIMIZE TABLE
against an InnoDB table stored in the shared table-space file ibdata1
does two things:
ibdata1
ibdata1
grow because the contiguous data and index pages are appended to ibdata1
You can however, segregate Table Data and Table Indexes from ibdata1
and manage them independently.
OPTIMIZE TABLE
with innodb_file_per_table
?Suppose you were to add innodb_file_per_table
to /etc/my.cnf (my.ini)
. Can you then just run OPTIMIZE TABLE
on all the InnoDB Tables?
Good News : When you run OPTIMIZE TABLE
with innodb_file_per_table
enabled, this will produce a .ibd
file for that table. For example, if you have table mydb.mytable
witha datadir of /var/lib/mysql
, it will produce the following:
/var/lib/mysql/mydb/mytable.frm
/var/lib/mysql/mydb/mytable.ibd
The .ibd
will contain the Data Pages and Index Pages for that table. Great.
Bad News : All you have done is extract the Data Pages and Index Pages of mydb.mytable
from living in ibdata
. The data dictionary entry for every table, including mydb.mytable
, still remains in the data dictionary (See the Pictorial Representation of ibdata1). YOU CANNOT JUST SIMPLY DELETE ibdata1
AT THIS POINT !!! Please note that ibdata1
has not shrunk at all.
To shrink ibdata1
once and for all you must do the following:
Dump (e.g., with mysqldump
) all databases into a .sql
text file (SQLData.sql
is used below)
Drop all databases (except for mysql
and information_schema
) CAVEAT : As a precaution, please run this script to make absolutely sure you have all user grants in place:
mkdir /var/lib/mysql_grants
cp /var/lib/mysql/mysql/* /var/lib/mysql_grants/.
chown -R mysql:mysql /var/lib/mysql_grants
Login to mysql and run SET GLOBAL innodb_fast_shutdown = 0;
(This will completely flush all remaining transactional changes from ib_logfile0
and ib_logfile1
)
Shutdown MySQL
Add the following lines to /etc/my.cnf
(or my.ini
on Windows)
[mysqld]
innodb_file_per_table
innodb_flush_method=O_DIRECT
innodb_log_file_size=1G
innodb_buffer_pool_size=4G
(Sidenote: Whatever your set for innodb_buffer_pool_size
, make sure innodb_log_file_size
is 25% of innodb_buffer_pool_size
.
Also: innodb_flush_method=O_DIRECT
is not available on Windows)
Delete ibdata*
and ib_logfile*
, Optionally, you can remove all folders in /var/lib/mysql
, except /var/lib/mysql/mysql
.
Start MySQL (This will recreate ibdata1
[10MB by default] and ib_logfile0
and ib_logfile1
at 1G each).
Import SQLData.sql
Now, ibdata1
will still grow but only contain table metadata because each InnoDB table will exist outside of ibdata1
. ibdata1
will no longer contain InnoDB data and indexes for other tables.
For example, suppose you have an InnoDB table named mydb.mytable
. If you look in /var/lib/mysql/mydb
, you will see two files representing the table:
mytable.frm
(Storage Engine Header)mytable.ibd
(Table Data and Indexes)With the innodb_file_per_table
option in /etc/my.cnf
, you can run OPTIMIZE TABLE mydb.mytable
and the file /var/lib/mysql/mydb/mytable.ibd
will actually shrink.
I have done this many times in my career as a MySQL DBA. In fact, the first time I did this, I shrank a 50GB ibdata1
file down to only 500MB!
Give it a try. If you have further questions on this, just ask. Trust me; this will work in the short term as well as over the long haul.
At Step 6, if mysql cannot restart because of the mysql
schema begin dropped, look back at Step 2. You made the physical copy of the mysql
schema. You can restore it as follows:
mkdir /var/lib/mysql/mysql
cp /var/lib/mysql_grants/* /var/lib/mysql/mysql
chown -R mysql:mysql /var/lib/mysql/mysql
Go back to Step 6 and continue
With regard to setting innodb_log_file_size to 25% of innodb_buffer_pool_size in Step 5, that's blanket rule is rather old school.
Back on July 03, 2006
, Percona had a nice article why to choose a proper innodb_log_file_size. Later, on Nov 21, 2008
, Percona followed up with another article on how to calculate the proper size based on peak workload keeping one hour's worth of changes.
I have since written posts in the DBA StackExchange about calculating the log size and where I referenced those two Percona articles.
Aug 27, 2012
: Proper tuning for 30GB InnoDB table on server with 48GB RAMJan 17, 2013
: MySQL 5.5 - Innodb - innodb_log_file_size higher than 4GB combined?Personally, I would still go with the 25% rule for an initial setup. Then, as the workload can more accurate be determined over time in production, you could resize the logs during a maintenance cycle in just minutes.
After show table, above the table ( +options ) Hyperlink is there.
Here is a performance comparison between using Entity Framework and using SqlBulkCopy class on a realistic example: How to Bulk Insert Complex Objects into SQL Server Database
As others already emphasized, ORMs are not meant to be used in bulk operations. They offer flexibility, separation of concerns and other benefits, but bulk operations (except bulk reading) are not one of them.
in eclipse go run - > run configuration
in there go to JRE tab in right side panels
in VM Arguments section paste this
-Duser.timezone=GMT
then Apply - > Run
As a follow-up to this question - since it relates specifically to creation time and discusses obtaining it via the new nio classes - it seems right now in JDK7's implementation you're out of luck. Addendum: same behaviour is in OpenJDK7.
On Unix filesystems you cannot retrieve the creation timestamp, you simply get a copy of the last modification time. So sad, but unfortunately true. I'm not sure why that is but the code specifically does that as the following will demonstrate.
import java.io.IOException;
import java.nio.file.*;
import java.nio.file.attribute.*;
public class TestFA {
static void getAttributes(String pathStr) throws IOException {
Path p = Paths.get(pathStr);
BasicFileAttributes view
= Files.getFileAttributeView(p, BasicFileAttributeView.class)
.readAttributes();
System.out.println(view.creationTime()+" is the same as "+view.lastModifiedTime());
}
public static void main(String[] args) throws IOException {
for (String s : args) {
getAttributes(s);
}
}
}
You can use the JsonTextReader
to read the JSON and iterate over the tokens:
using (var reader = new JsonTextReader(new StringReader(jsonText)))
{
while (reader.Read())
{
Console.WriteLine("{0} - {1} - {2}",
reader.TokenType, reader.ValueType, reader.Value);
}
}
I recommendo to you use TtoC from ConvUnicode.h
const CString word= "hello";
const char* myFile = TtoC(path.GetString());
It is a macro to do conversions per Unicode
select previous, Present, previous-Present as Difference from tablename
or
select previous, Present, previous-Present as Difference from #TEMP1
size_t is defined by the C standard to be the unsigned integer return type of the sizeof operator (C99 6.3.5.4.4), and the argument of malloc and friends (C99 7.20.3.3 etc). The actual range is set such that the maximum (SIZE_MAX) is at least 65535 (C99 7.18.3.2).
However, this doesn't let us determine sizeof(size_t). The implementation is free to use any representation it likes for size_t - so there is no upper bound on size - and the implementation is also free to define a byte as 16-bits, in which case size_t can be equivalent to unsigned char.
Putting that aside, however, in general you'll have 32-bit size_t on 32-bit programs, and 64-bit on 64-bit programs, regardless of the data model. Generally the data model only affects static data; for example, in GCC:
`-mcmodel=small'
Generate code for the small code model: the program and its
symbols must be linked in the lower 2 GB of the address space.
Pointers are 64 bits. Programs can be statically or dynamically
linked. This is the default code model.
`-mcmodel=kernel'
Generate code for the kernel code model. The kernel runs in the
negative 2 GB of the address space. This model has to be used for
Linux kernel code.
`-mcmodel=medium'
Generate code for the medium model: The program is linked in the
lower 2 GB of the address space but symbols can be located
anywhere in the address space. Programs can be statically or
dynamically linked, but building of shared libraries are not
supported with the medium model.
`-mcmodel=large'
Generate code for the large model: This model makes no assumptions
about addresses and sizes of sections.
You'll note that pointers are 64-bit in all cases; and there's little point to having 64-bit pointers but not 64-bit sizes, after all.
If those are the only changes, you can simply do
git commit -a
to commit all changes. That will include deleted files.
As you said, Safari sends Cache-Control: max-age=0
on reload. Express (or more specifically, Express's dependency, node-fresh) considers the cache stale when Cache-Control: no-cache
headers are received, but it doesn't do the same for Cache-Control: max-age=0
. From what I can tell, it probably should. But I'm not an expert on caching.
The fix is to change (what is currently) line 37 of node-fresh/index.js
from
if (cc && cc.indexOf('no-cache') !== -1) return false;
to
if (cc && (cc.indexOf('no-cache') !== -1 ||
cc.indexOf('max-age=0') !== -1)) return false;
I forked node-fresh and express to include this fix in my project's package.json
via npm
, you could do the same. Here are my forks, for example:
https://github.com/stratusdata/node-fresh https://github.com/stratusdata/express#safari-reload-fix
The safari-reload-fix branch is based on the 3.4.7 tag.
Two options:
char c1 = '\u0001';
char c1 = (char) 1;
Try this code. It works for me:
unzip(zipfile="<directory and filename>",
exdir="<directory where the content will be extracted>")
Example:
unzip(zipfile="./data/Data.zip",exdir="./data")
Use slicing and is
to check for the last element:
for data in data_list:
<code_that_is_done_for_every_element>
if not data is data_list[-1]:
<code_that_is_done_between_elements>
Caveat emptor: This only works if all elements in the list are actually different (have different locations in memory). Under the hood, Python may detect equal elements and reuse the same objects for them. For instance, for strings of the same value and common integers.
It is not true that quicksort is better. ALso, it depends on what you mean better, memory consumption, or speed.
In terms of memory consumption, in worst case, but quicksort can use n^2 memory (i.e. each partition is 1 to n-1), whereas merge sort uses nlogn.
The above follows in terms of speed.
The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?
For example, we have i values and get the value of id field
alert(obj[i].id); //works!
But what if we need key with spaces?
In this case, the following construction can help (without point between [] blocks):
alert(obj[i]["No. of interfaces"]); //works too!